[clang] [llvm] Move several vector intrinsics out of experimental namespace (PR #88748)

2024-04-25 Thread Cullen Rhodes via cfe-commits

c-rhodes wrote:

> Rebased on newer LLVM + forcing to re-run the testing which previously failed 
> on some not related issues.

Not sure if you missed my previous comment but you need to update the 
`interleave2` intrinsic in MLIR. MLIR doesn't build with this patch which you 
can see in pre-commit:
> _bk;t=1713985770943In file included from 
> /var/lib/buildkite-agent/builds/linux-56-59b8f5d88-zw2hg-1/llvm-project/github-pull-requests/mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMIRToLLVMTranslation.cpp:39:
_bk;t=1713985770943/var/lib/buildkite-agent/builds/linux-56-59b8f5d88-zw2hg-1/llvm-project/github-pull-requests/build/tools/mlir/include/mlir/Dialect/LLVMIR/LLVMConvertibleLLVMIRIntrinsics.inc:156:18:
 error: no member named 'experimental_vector_interleave2' 
in namespace 'llvm::Intrinsic'
_bk;t=1713985770943llvm::Intrinsic::experimental_vector_interleave2,


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


[clang] 9b0651f - [clang][dataflow] Don't propagate result objects in nested declarations. (#89903)

2024-04-25 Thread via cfe-commits

Author: martinboehme
Date: 2024-04-25T09:22:14+02:00
New Revision: 9b0651f5ae6510577302ea527b2cc79e80ec9ccc

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

LOG: [clang][dataflow] Don't propagate result objects in nested declarations. 
(#89903)

Trying to do so can cause crashes -- see newly added test and the
comments in
the fix.

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 3cb656adcbdc0c..636d2302093983 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -333,6 +333,18 @@ class ResultObjectVisitor : public 
RecursiveASTVisitor {
 }
   }
 
+  bool TraverseDecl(Decl *D) {
+// Don't traverse nested record or function declarations.
+// - We won't be analyzing code contained in these anyway
+// - We don't model fields that are used only in these nested declaration,
+//   so trying to propagate a result object to initializers of such fields
+//   would cause an error.
+if (isa_and_nonnull(D) || isa_and_nonnull(D))
+  return true;
+
+return RecursiveASTVisitor::TraverseDecl(D);
+  }
+
   bool TraverseBindingDecl(BindingDecl *BD) {
 // `RecursiveASTVisitor` doesn't traverse holding variables for
 // `BindingDecl`s by itself, so we need to tell it to.

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 215e208615ac23..5c7c39e52612ec 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3309,6 +3309,28 @@ TEST(TransferTest, 
ResultObjectLocationPropagatesThroughConditionalOperator) {
   });
 }
 
+TEST(TransferTest, ResultObjectLocationDontVisitNestedRecordDecl) {
+  // This is a crash repro.
+  // We used to crash because when propagating result objects, we would visit
+  // nested record and function declarations, but we don't model fields used
+  // only in these.
+  std::string Code = R"(
+struct S1 {};
+struct S2 { S1 s1; };
+void target() {
+  struct Nested {
+void f() {
+  S2 s2 = { S1() };
+}
+  };
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {});
+}
+
 TEST(TransferTest, StaticCast) {
   std::string Code = R"(
 void target(int Foo) {



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


[clang] [clang][dataflow] Don't propagate result objects in nested declarations. (PR #89903)

2024-04-25 Thread via cfe-commits

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


[clang] [clang][dataflow] Crash fix for `widenDistinctValues()`. (PR #89895)

2024-04-25 Thread via cfe-commits

martinboehme wrote:

Code formatting failure is an infrastructure error.

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


[clang] b9208ce - [clang][dataflow] Crash fix for `widenDistinctValues()`. (#89895)

2024-04-25 Thread via cfe-commits

Author: martinboehme
Date: 2024-04-25T09:24:08+02:00
New Revision: b9208ce318907b1a5ea4ad0d2aa4414dfba0616c

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

LOG: [clang][dataflow] Crash fix for `widenDistinctValues()`. (#89895)

We used to crash if the previous iteration contained a `BoolValue` and
the
current iteration contained an `IntegerValue`. The accompanying test
sets up
this situation -- see comments there for details.

While I'm here, clean up the tests for integral casts to use the test
helpers we
have available now. I was looking at these tests to understand how we
handle
integral casts, and the test helpers make the tests easier to read.

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 636d2302093983..d79e734402892a 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -157,7 +157,13 @@ static WidenResult widenDistinctValues(QualType Type, 
Value &Prev,
Value &Current, Environment &CurrentEnv,
Environment::ValueModel &Model) {
   // Boolean-model widening.
-  if (auto *PrevBool = dyn_cast(&Prev)) {
+  if (isa(Prev) && isa(Current)) {
+// FIXME: Checking both values should be unnecessary, but we can currently
+// end up with `BoolValue`s in integer-typed variables. See comment in
+// `joinDistinctValues()` for details.
+auto &PrevBool = cast(Prev);
+auto &CurBool = cast(Current);
+
 if (isa(Prev))
   // Safe to return `Prev` here, because Top is never dependent on the
   // environment.
@@ -166,13 +172,12 @@ static WidenResult widenDistinctValues(QualType Type, 
Value &Prev,
 // We may need to widen to Top, but before we do so, check whether both
 // values are implied to be either true or false in the current 
environment.
 // In that case, we can simply return a literal instead.
-auto &CurBool = cast(Current);
-bool TruePrev = PrevEnv.proves(PrevBool->formula());
+bool TruePrev = PrevEnv.proves(PrevBool.formula());
 bool TrueCur = CurrentEnv.proves(CurBool.formula());
 if (TruePrev && TrueCur)
   return {&CurrentEnv.getBoolLiteralValue(true), LatticeEffect::Unchanged};
 if (!TruePrev && !TrueCur &&
-PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool->formula())) &&
+PrevEnv.proves(PrevEnv.arena().makeNot(PrevBool.formula())) &&
 CurrentEnv.proves(CurrentEnv.arena().makeNot(CurBool.formula(
   return {&CurrentEnv.getBoolLiteralValue(false), 
LatticeEffect::Unchanged};
 

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 5c7c39e52612ec..d204700919d315 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -3370,20 +3370,11 @@ TEST(TransferTest, IntegralCast) {
   Code,
   [](const llvm::StringMap> &Results,
  ASTContext &ASTCtx) {
-ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
-
-const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
-ASSERT_THAT(BarDecl, NotNull());
-
-const auto *FooVal = Env.getValue(*FooDecl);
-const auto *BarVal = Env.getValue(*BarDecl);
-EXPECT_TRUE(isa(FooVal));
-EXPECT_TRUE(isa(BarVal));
-EXPECT_EQ(FooVal, BarVal);
+const auto &FooVal = getValueForDecl(ASTCtx, Env, "Foo");
+const auto &BarVal = getValueForDecl(ASTCtx, Env, "Bar");
+EXPECT_EQ(&FooVal, &BarVal);
   });
 }
 
@@ -3398,17 +3389,10 @@ TEST(TransferTest, IntegraltoBooleanCast) {
   Code,
   [](const llvm::StringMap> &Results,
  ASTContext &ASTCtx) {
-ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
 const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
-
-const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
-ASSERT_THAT(BarDecl, NotNull());
-
-const auto *FooVal = Env.getValue(*FooDecl);
-const auto *BarVal = Env.getValue(*BarDecl);
+const auto &FooVal = getValueForDecl(ASTCtx, Env, "Foo");
+const auto &BarVal = get

[clang] [clang][dataflow] Crash fix for `widenDistinctValues()`. (PR #89895)

2024-04-25 Thread via cfe-commits

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


[clang] [clang][dataflow] Crash fix for `widenDistinctValues()`. (PR #89895)

2024-04-25 Thread via cfe-commits

martinboehme wrote:

> LGTM! Do we want to open tickets to track these FIXMEs?

Sounds good -- done: https://github.com/llvm/llvm-project/issues/90024

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


[clang] [clang] pointer to member with qualified-id enclosed in parentheses in unevaluated context should be invalid (PR #89713)

2024-04-25 Thread via cfe-commits

https://github.com/zwuis updated https://github.com/llvm/llvm-project/pull/89713

>From f6fd1e5e5f42b3c72cb5aeaf9e6d4e91d5424bee Mon Sep 17 00:00:00 2001
From: YanzuoLiu 
Date: Tue, 23 Apr 2024 14:56:12 +0800
Subject: [PATCH 1/5] Add missing check when making pointer to member

---
 clang/lib/Sema/SemaExpr.cpp| 11 +++
 .../CXX/expr/expr.unary/expr.unary.op/p3.cpp   | 18 +-
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 5c861467bc1023..824667fb722365 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14644,6 +14644,17 @@ QualType Sema::CheckAddressOfOperand(ExprResult 
&OrigOp, SourceLocation OpLoc) {
 return QualType();
   }
 
+  // C++11 [expr.unary.op] p4:
+  // A pointer to member is only formed when an explicit & is used and
+  // its operand is a qualified-id not enclosed in parentheses.
+  if (isa(OrigOp.get())) {
+// `op->getEndLoc()` is the last part of the qualified-id.
+// For example, "baz" in "foo::bar::baz".
+Diag(op->getEndLoc(), diag::err_invalid_non_static_member_use)
+<< dcl->getDeclName() << op->getSourceRange();
+return QualType();
+  }
+
   while (cast(Ctx)->isAnonymousStructOrUnion())
 Ctx = Ctx->getParent();
 
diff --git a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp 
b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
index 08ab0ca56fb632..73d850a6839da7 100644
--- a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
+++ b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only %s -verify 
-// expected-no-diagnostics
 
 namespace rdar10544564 {
   // Check that we don't attempt to use an overloaded operator& when
@@ -27,3 +26,20 @@ namespace rdar10544564 {
   X (Y::*func_mem_ptr1)() = &Y::memfunc1;
   X (Y::*func_mem_ptr2)() = &Y::memfunc2;
 }
+
+namespace test2 {
+  struct A {
+int val;
+void func() {}
+  };
+
+  void test() {
+decltype(&(A::val)) ptr1; // expected-error {{invalid use of non-static 
data member 'val'}}
+int A::* ptr2 = &(A::val); // expected-error {{invalid use of non-static 
data member 'val'}}
+
+// FIXME: Error messages in these cases are less than clear, we can do
+// better.
+int size = sizeof(&(A::func)); // expected-error {{call to non-static 
member function without an object argument}}
+void (A::* ptr3)() = &(A::func); // expected-error {{call to non-static 
member function without an object argument}}
+  }
+}

>From 22b18d32d79e5dcd0390aa17c454f373e565868a Mon Sep 17 00:00:00 2001
From: YanzuoLiu 
Date: Wed, 24 Apr 2024 17:21:14 +0800
Subject: [PATCH 2/5] Apply suggestion from cor3ntin

Co-authored-by: cor3ntin 
---
 clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp 
b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
index 73d850a6839da7..3e99b333d0e584 100644
--- a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
+++ b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
@@ -27,7 +27,7 @@ namespace rdar10544564 {
   X (Y::*func_mem_ptr2)() = &Y::memfunc2;
 }
 
-namespace test2 {
+namespace GH40906 {
   struct A {
 int val;
 void func() {}

>From 81fd55780b34c92566bdfb7fc1a2cde690675d66 Mon Sep 17 00:00:00 2001
From: YanzuoLiu 
Date: Wed, 24 Apr 2024 17:39:45 +0800
Subject: [PATCH 3/5] Move tests to the right place

---
 .../CXX/expr/expr.unary/expr.unary.op/p3.cpp   | 18 +-
 .../CXX/expr/expr.unary/expr.unary.op/p4.cpp   | 17 +
 2 files changed, 18 insertions(+), 17 deletions(-)

diff --git a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp 
b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
index 3e99b333d0e584..08ab0ca56fb632 100644
--- a/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
+++ b/clang/test/CXX/expr/expr.unary/expr.unary.op/p3.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only %s -verify 
+// expected-no-diagnostics
 
 namespace rdar10544564 {
   // Check that we don't attempt to use an overloaded operator& when
@@ -26,20 +27,3 @@ namespace rdar10544564 {
   X (Y::*func_mem_ptr1)() = &Y::memfunc1;
   X (Y::*func_mem_ptr2)() = &Y::memfunc2;
 }
-
-namespace GH40906 {
-  struct A {
-int val;
-void func() {}
-  };
-
-  void test() {
-decltype(&(A::val)) ptr1; // expected-error {{invalid use of non-static 
data member 'val'}}
-int A::* ptr2 = &(A::val); // expected-error {{invalid use of non-static 
data member 'val'}}
-
-// FIXME: Error messages in these cases are less than clear, we can do
-// better.
-int size = sizeof(&(A::func)); // expected-error {{call to non-static 
member function without an object argument}}
-void (A::* ptr3)() = &(A::func); // expec

[clang] Push immediate function context while transforming lambdas in templates. (PR #89702)

2024-04-25 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/89702

>From ba1c87956f74248467d2f85c20c2f450eef953bd Mon Sep 17 00:00:00 2001
From: Dan Katz 
Date: Mon, 22 Apr 2024 22:39:06 -0400
Subject: [PATCH] Push immediate function context while transforming lambdas in
 templates.

---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/TreeTransform.h |  2 ++
 clang/test/SemaCXX/cxx2a-consteval.cpp | 20 
 3 files changed, 25 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45a9a79739a4eb..0efdcac3c4b8e1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -420,6 +420,9 @@ Bug Fixes in This Version
 - Fixed a regression in CTAD that a friend declaration that befriends itself 
may cause
   incorrect constraint substitution. (#GH86769).
 
+- Fixed bug in which the body of a consteval lambda within a template was not 
parsed as within an
+  immediate function context.
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 284c9173e68ed5..a3ddebb3ca5963 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -14044,6 +14044,8 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
   // FIXME: Sema's lambda-building mechanism expects us to push an expression
   // evaluation context even if we're not transforming the function body.
   getSema().PushExpressionEvaluationContext(
+  E->getCallOperator()->isConsteval() ?
+  Sema::ExpressionEvaluationContext::ImmediateFunctionContext :
   Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
 
   Sema::CodeSynthesisContext C;
diff --git a/clang/test/SemaCXX/cxx2a-consteval.cpp 
b/clang/test/SemaCXX/cxx2a-consteval.cpp
index 192621225a543c..e198074372072d 100644
--- a/clang/test/SemaCXX/cxx2a-consteval.cpp
+++ b/clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -260,6 +260,26 @@ int(*test)(int)  = l1;
 
 }
 
+namespace consteval_lambda_in_template {
+struct S {
+int *value;
+constexpr S(int v) : value(new int {v}) {}
+constexpr ~S() { delete value; }
+};
+consteval S fn() { return S(5); }
+
+template 
+void fn2() {
+(void)[]() consteval -> int {
+  return *(fn().value);  // OK, immediate context
+};
+}
+
+void caller() {
+fn2();
+}
+}
+
 namespace std {
 
 template  struct remove_reference { using type = T; };

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


[clang] 5e767bd - Push immediate function context while transforming lambdas in templates. (#89702)

2024-04-25 Thread via cfe-commits

Author: Daniel M. Katz
Date: 2024-04-25T09:41:25+02:00
New Revision: 5e767bd7d16dcdfc1ad8b32ba399f969dd940f57

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

LOG: Push immediate function context while transforming lambdas in templates. 
(#89702)

The following program is [accepted](https://godbolt.org/z/oEc34Trh4) by
Clang, EDG, and MSVC, but rejected by Clang:
```cpp
#include 

consteval auto fn() { return std::vector {1,2,3}; }

template 
void fn2() {
(void)[]() consteval {
  for (auto e : fn()) {}
};
}

void caller() {
fn2();
}
```

The stated diagnostic is:
```cpp
:8:21: error: call to consteval function 'fn' is not a constant 
expression
8 |   for (auto e : fn()) {}
```

The body of the lambda should be evaluated as within an immediate
function context when the lambda is marked as `consteval`.

Co-authored-by: cor3ntin 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/TreeTransform.h
clang/test/SemaCXX/cxx2a-consteval.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7bea43ec64f062..0bad03eda8cb54 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -564,6 +564,8 @@ Bug Fixes to C++ Support
 - Fixed a crash when trying to evaluate a user-defined ``static_assert`` 
message whose ``size()``
   function returns a large or negative value. Fixes (#GH89407).
 - Fixed a use-after-free bug in parsing of type constraints with default 
arguments that involve lambdas. (#GH67235)
+- Fixed bug in which the body of a consteval lambda within a template was not 
parsed as within an
+  immediate function context.
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 9404be5a46f3f7..1d30ba31e17940 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -14186,6 +14186,8 @@ TreeTransform::TransformLambdaExpr(LambdaExpr 
*E) {
   // FIXME: Sema's lambda-building mechanism expects us to push an expression
   // evaluation context even if we're not transforming the function body.
   getSema().PushExpressionEvaluationContext(
+  E->getCallOperator()->isConsteval() ?
+  Sema::ExpressionEvaluationContext::ImmediateFunctionContext :
   Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
 
   Sema::CodeSynthesisContext C;

diff  --git a/clang/test/SemaCXX/cxx2a-consteval.cpp 
b/clang/test/SemaCXX/cxx2a-consteval.cpp
index 192621225a543c..e198074372072d 100644
--- a/clang/test/SemaCXX/cxx2a-consteval.cpp
+++ b/clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -260,6 +260,26 @@ int(*test)(int)  = l1;
 
 }
 
+namespace consteval_lambda_in_template {
+struct S {
+int *value;
+constexpr S(int v) : value(new int {v}) {}
+constexpr ~S() { delete value; }
+};
+consteval S fn() { return S(5); }
+
+template 
+void fn2() {
+(void)[]() consteval -> int {
+  return *(fn().value);  // OK, immediate context
+};
+}
+
+void caller() {
+fn2();
+}
+}
+
 namespace std {
 
 template  struct remove_reference { using type = T; };



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


[clang] Push immediate function context while transforming lambdas in templates. (PR #89702)

2024-04-25 Thread via cfe-commits

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


[clang] fe47e8f - [NFC] [ASTUnit] [Serialization] Transalte local decl ID to global decl ID before consuming

2024-04-25 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-04-25T15:55:46+08:00
New Revision: fe47e8ff3ae7fc8975eaade6bfa6679737c28b93

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

LOG: [NFC] [ASTUnit] [Serialization] Transalte local decl ID to global decl ID 
before consuming

Discovered from
https://github.com/llvm/llvm-project/commit/d86cc73bbfd9a22d9a0d498d72c9b2ee235128e9.

There is a potential issue of using DeclID in ASTUnit. ASTUnit may
record the declaration ID from ASTWriter. And after loading the
preamble, the ASTUnit may consume the recorded declaration ID directly
in ExternalASTSource. This is not good. According to the design, all
local declaration ID consumed in ASTReader need to be translated by
`ASTReader::getGlobaldeclID()`.

This will be problematic if we changed the encodings of declaration IDs or if we
make preamble to work more complexly.

Added: 


Modified: 
clang/lib/Frontend/ASTUnit.cpp

Removed: 




diff  --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index 2f75313e8a4c50..1b93588553a276 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -1467,13 +1467,12 @@ void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
 
   std::vector Resolved;
   Resolved.reserve(TopLevelDeclsInPreamble.size());
-  ExternalASTSource &Source = *getASTContext().getExternalSource();
+  // The module file of the preamble.
+  serialization::ModuleFile &MF = 
Reader->getModuleManager().getPrimaryModule();
   for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
 // Resolve the declaration ID to an actual declaration, possibly
 // deserializing the declaration in the process.
-//
-// FIMXE: We shouldn't convert a LocalDeclID to GlobalDeclID directly.
-if (Decl *D = Source.GetExternalDecl(GlobalDeclID(TopLevelDecl.get(
+if (Decl *D = Reader->GetDecl(Reader->getGlobalDeclID(MF, TopLevelDecl)))
   Resolved.push_back(D);
   }
   TopLevelDeclsInPreamble.clear();



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


[clang] [clang][analyzer] Fix alpha.unix.BlockInCriticalSection for CTU (PR #90030)

2024-04-25 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 created 
https://github.com/llvm/llvm-project/pull/90030

In CTU there is not always an AnalysisDeclContext for a given call. This
led to crashes. The AnalysisDeclContext access is now checked.


From de695f8e556e1efd6b2a4e69f916467af94e0c0d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Tue, 9 Apr 2024 10:44:43 +0200
Subject: [PATCH] [clang][analyzer] Fix alpha.unix.BlockInCriticalSection for
 CTU

In CTU there is not always an AnalysisDeclContext for a given call. This
led to crashes. The AnalysisDeclContext access is now checked.
---
 .../Checkers/BlockInCriticalSectionChecker.cpp| 8 +---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index e4373915410fb2..9874a68ebe47af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -14,6 +14,7 @@
 //
 
//===--===//
 
+#include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -103,9 +104,10 @@ class RAIIMutexDescriptor {
   // this function is called instead of early returning it. To avoid this, 
a
   // bool variable (IdentifierInfoInitialized) is used and the function 
will
   // be run only once.
-  Guard = &Call.getCalleeAnalysisDeclContext()->getASTContext().Idents.get(
-  GuardName);
-  IdentifierInfoInitialized = true;
+  if (AnalysisDeclContext *CalleCtx = Call.getCalleeAnalysisDeclContext()) 
{
+Guard = &CalleCtx->getASTContext().Idents.get(GuardName);
+IdentifierInfoInitialized = true;
+  }
 }
   }
 

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


[clang] [clang][analyzer] Fix alpha.unix.BlockInCriticalSection for CTU (PR #90030)

2024-04-25 Thread via cfe-commits

llvmbot wrote:



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

@llvm/pr-subscribers-clang

Author: Endre Fülöp (gamesh411)


Changes

In CTU there is not always an AnalysisDeclContext for a given call. This
led to crashes. The AnalysisDeclContext access is now checked.


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


1 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp (+5-3) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index e4373915410fb2..9874a68ebe47af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -14,6 +14,7 @@
 //
 
//===--===//
 
+#include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -103,9 +104,10 @@ class RAIIMutexDescriptor {
   // this function is called instead of early returning it. To avoid this, 
a
   // bool variable (IdentifierInfoInitialized) is used and the function 
will
   // be run only once.
-  Guard = &Call.getCalleeAnalysisDeclContext()->getASTContext().Idents.get(
-  GuardName);
-  IdentifierInfoInitialized = true;
+  if (AnalysisDeclContext *CalleCtx = Call.getCalleeAnalysisDeclContext()) 
{
+Guard = &CalleCtx->getASTContext().Idents.get(GuardName);
+IdentifierInfoInitialized = true;
+  }
 }
   }
 

``




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


[clang] [Coverage] Add a new flag to split region after every call. (PR #90031)

2024-04-25 Thread via cfe-commits

https://github.com/c01db33f created 
https://github.com/llvm/llvm-project/pull/90031

This helps with displaying more precise coverage when a function causes the 
program to exit, crashes, or similar. For example, using this flag should 
address the case listed in the documentation under "Drawbacks and limitations":

```
int f() {
  may_throw();
  return 0;
}
```

If the call to `may_throw` propagates an exception into `f`, the `return` 
statement should not be marked as executed.

This change adds a significant number of basic blocks, so likely has a 
performance and size overhead, so I've not made it the default behaviour.

>From d534e1b04d7b2d9faf8fb10f4f6e44b99b3cbb45 Mon Sep 17 00:00:00 2001
From: Mark Brand 
Date: Wed, 24 Apr 2024 17:44:34 +0200
Subject: [PATCH] [Coverage] Add a new flag to split region after every call.

This helps with displaying more precise coverage when a function
causes the program to exit, crashes, or similar. For example,
using this flag should address the case listed in the documentation
under "Drawbacks and limitations":

```
int f() {
  may_throw();
  return 0;
}
```

If the call to `may_throw` propagates an exception into `f`, the
`return` statement should not be marked as executed.

This change adds a significant number of basic blocks, so likely
has a performance and size overhead, so I've not made it the
default behaviour.
---
 clang/lib/CodeGen/CoverageMappingGen.cpp |  7 -
 clang/test/CoverageMapping/branch-return.cpp | 31 
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CoverageMapping/branch-return.cpp

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 733686d4946b3c..32fdfb0d35063b 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -45,6 +45,11 @@ static llvm::cl::opt EmptyLineCommentCoverage(
"disable it on test)"),
 llvm::cl::init(true), llvm::cl::Hidden);
 
+static llvm::cl::opt CallsEndCoverageRegion(
+"calls-end-coverage-region",
+llvm::cl::desc("Force a coverage region end after every call expression"),
+llvm::cl::init(false), llvm::cl::Hidden);
+
 llvm::cl::opt SystemHeadersCoverage(
 "system-headers-coverage",
 llvm::cl::desc("Enable collecting coverage from system headers"),
@@ -1484,7 +1489,7 @@ struct CounterCoverageMappingBuilder
 // Terminate the region when we hit a noreturn function.
 // (This is helpful dealing with switch statements.)
 QualType CalleeType = E->getCallee()->getType();
-if (getFunctionExtInfo(*CalleeType).getNoReturn())
+if (CallsEndCoverageRegion || 
getFunctionExtInfo(*CalleeType).getNoReturn())
   terminateRegion(E);
   }
 
diff --git a/clang/test/CoverageMapping/branch-return.cpp 
b/clang/test/CoverageMapping/branch-return.cpp
new file mode 100644
index 00..16c1b88607d590
--- /dev/null
+++ b/clang/test/CoverageMapping/branch-return.cpp
@@ -0,0 +1,31 @@
+// Test that branch regions are generated for return paths when 
calls-end-coverage-region is set.
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -main-file-name branch-return.cpp %s | FileCheck %s 
-check-prefix=WITHOUT
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 
-fprofile-instrument=clang -fcoverage-mapping -mllvm -calls-end-coverage-region 
-dump-coverage-mapping -emit-llvm-only -main-file-name branch-return.cpp %s | 
FileCheck %s -check-prefix=WITH
+
+// CHECK-LABEL: _Z5func1ii:
+// WITHOUT: File 0, [[@LINE+2]]:26 -> [[@LINE+4]]:2 = #0
+// WITH: File 0, [[@LINE+1]]:26 -> [[@LINE+3]]:2 = #0
+bool func1(int a, int b) {
+  return (a | b) < 100;
+}
+
+// CHECK-LABEL: _Z5func2ii:
+// WITHOUT: File 0, [[@LINE+2]]:26 -> [[@LINE+4]]:2 = #0
+// WITH: File 0, [[@LINE+1]]:26 -> [[@LINE+3]]:2 = #0
+bool func2(int a, int b) {
+  return (a ^ b) > 10;
+}
+
+// CHECK-LABEL: _Z5func3ii:
+// WITHOUT: File 0, [[@LINE+6]]:26 -> [[@LINE+10]]:2 = #0
+// WITH: File 0, [[@LINE+5]]:26 -> [[@LINE+9]]:2 = #0
+// WITH: Gap,File 0, [[@LINE+5]]:27 -> [[@LINE+6]]:3 = 0
+// WITH: File 0, [[@LINE+5]]:3 -> [[@LINE+5]]:26 = 0
+// WITH: Gap,File 0, [[@LINE+4]]:27 -> [[@LINE+5]]:3 = 0
+// WITH: File 0, [[@LINE+4]]:3 -> [[@LINE+4]]:22 = 0
+bool func3(int a, int b) {
+  bool val1 = func1(a, b);
+  bool val2 = func2(a, b);
+  return val1 || val2;
+}

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


[clang] [Coverage] Add a new flag to split region after every call. (PR #90031)

2024-04-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [Coverage] Add a new flag to split region after every call. (PR #90031)

2024-04-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (c01db33f)


Changes

This helps with displaying more precise coverage when a function causes the 
program to exit, crashes, or similar. For example, using this flag should 
address the case listed in the documentation under "Drawbacks and limitations":

```
int f() {
  may_throw();
  return 0;
}
```

If the call to `may_throw` propagates an exception into `f`, the `return` 
statement should not be marked as executed.

This change adds a significant number of basic blocks, so likely has a 
performance and size overhead, so I've not made it the default behaviour.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CoverageMappingGen.cpp (+6-1) 
- (added) clang/test/CoverageMapping/branch-return.cpp (+31) 


``diff
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 733686d4946b3c..32fdfb0d35063b 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -45,6 +45,11 @@ static llvm::cl::opt EmptyLineCommentCoverage(
"disable it on test)"),
 llvm::cl::init(true), llvm::cl::Hidden);
 
+static llvm::cl::opt CallsEndCoverageRegion(
+"calls-end-coverage-region",
+llvm::cl::desc("Force a coverage region end after every call expression"),
+llvm::cl::init(false), llvm::cl::Hidden);
+
 llvm::cl::opt SystemHeadersCoverage(
 "system-headers-coverage",
 llvm::cl::desc("Enable collecting coverage from system headers"),
@@ -1484,7 +1489,7 @@ struct CounterCoverageMappingBuilder
 // Terminate the region when we hit a noreturn function.
 // (This is helpful dealing with switch statements.)
 QualType CalleeType = E->getCallee()->getType();
-if (getFunctionExtInfo(*CalleeType).getNoReturn())
+if (CallsEndCoverageRegion || 
getFunctionExtInfo(*CalleeType).getNoReturn())
   terminateRegion(E);
   }
 
diff --git a/clang/test/CoverageMapping/branch-return.cpp 
b/clang/test/CoverageMapping/branch-return.cpp
new file mode 100644
index 00..16c1b88607d590
--- /dev/null
+++ b/clang/test/CoverageMapping/branch-return.cpp
@@ -0,0 +1,31 @@
+// Test that branch regions are generated for return paths when 
calls-end-coverage-region is set.
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -main-file-name branch-return.cpp %s | FileCheck %s 
-check-prefix=WITHOUT
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 
-fprofile-instrument=clang -fcoverage-mapping -mllvm -calls-end-coverage-region 
-dump-coverage-mapping -emit-llvm-only -main-file-name branch-return.cpp %s | 
FileCheck %s -check-prefix=WITH
+
+// CHECK-LABEL: _Z5func1ii:
+// WITHOUT: File 0, [[@LINE+2]]:26 -> [[@LINE+4]]:2 = #0
+// WITH: File 0, [[@LINE+1]]:26 -> [[@LINE+3]]:2 = #0
+bool func1(int a, int b) {
+  return (a | b) < 100;
+}
+
+// CHECK-LABEL: _Z5func2ii:
+// WITHOUT: File 0, [[@LINE+2]]:26 -> [[@LINE+4]]:2 = #0
+// WITH: File 0, [[@LINE+1]]:26 -> [[@LINE+3]]:2 = #0
+bool func2(int a, int b) {
+  return (a ^ b) > 10;
+}
+
+// CHECK-LABEL: _Z5func3ii:
+// WITHOUT: File 0, [[@LINE+6]]:26 -> [[@LINE+10]]:2 = #0
+// WITH: File 0, [[@LINE+5]]:26 -> [[@LINE+9]]:2 = #0
+// WITH: Gap,File 0, [[@LINE+5]]:27 -> [[@LINE+6]]:3 = 0
+// WITH: File 0, [[@LINE+5]]:3 -> [[@LINE+5]]:26 = 0
+// WITH: Gap,File 0, [[@LINE+4]]:27 -> [[@LINE+5]]:3 = 0
+// WITH: File 0, [[@LINE+4]]:3 -> [[@LINE+4]]:22 = 0
+bool func3(int a, int b) {
+  bool val1 = func1(a, b);
+  bool val2 = func2(a, b);
+  return val1 || val2;
+}

``




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


[clang] Notifying assume directive as 'worked on'. (PR #90022)

2024-04-25 Thread via cfe-commits

https://github.com/SunilKuravinakop updated 
https://github.com/llvm/llvm-project/pull/90022

>From 031b44a69d2b2d408bf07714be0427bab65f29ca Mon Sep 17 00:00:00 2001
From: Sunil Kuravinakop 
Date: Thu, 25 Apr 2024 01:45:29 -0500
Subject: [PATCH 1/2] Notifying assume directive as 'worked on'. When checked
 on slack channel, nobody was working on assume directive.

 Changes to be committed:
modified:   clang/docs/OpenMPSupport.rst
---
 clang/docs/OpenMPSupport.rst | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index f8146bc365e833..3562872b407bf7 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -310,7 +310,9 @@ implementation.
 
+--+--+--+---+
 | misc | dispatch construct and function variant 
argument adjustment  | :part:`worked on`| D99537, D99679
|
 
+--+--+--+---+
-| misc | assume and assumes directives 
   | :part:`worked on`| 
  |
+| misc | assumes directives
| :part:`worked on`|
   |
++--+--+--+---+
+| misc | assume directive  
  | :part:`worked on`|  
 |
 
+--+--+--+---+
 | misc | nothing directive 
   | :good:`done` | D123286 
  |
 
+--+--+--+---+

>From f4c250f463ee73aac0fab44057ebfaa645f47039 Mon Sep 17 00:00:00 2001
From: Sunil Kuravinakop 
Date: Thu, 25 Apr 2024 03:09:34 -0500
Subject: [PATCH 2/2] Minor change to prevent failure while building
 clang/docs.

---
 clang/docs/OpenMPSupport.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index 3562872b407bf7..5e63b2c0f0be6b 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -310,9 +310,9 @@ implementation.
 
+--+--+--+---+
 | misc | dispatch construct and function variant 
argument adjustment  | :part:`worked on`| D99537, D99679
|
 
+--+--+--+---+
-| misc | assumes directives
| :part:`worked on`|
   |
+| misc | assumes directives
   | :part:`worked on`| 
  |
 
+--+--+--+---+
-| misc | assume directive  
  | :part:`worked on`|  
 |
+| misc | assume directive  
   | :part:`worked on`| 
  |
 
+--+--+--+---+
 | m

[clang] [Modules] No transitive source location change (PR #86912)

2024-04-25 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/86912

>From 2c20a6200fb2790b3a891ffc8c43682c113c7e8a Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Mon, 18 Mar 2024 08:36:55 +0800
Subject: [PATCH] [Modules] No transitive source location change

---
 clang/include/clang/Basic/SourceLocation.h|  1 +
 .../include/clang/Serialization/ASTBitCodes.h | 56 +---
 clang/include/clang/Serialization/ASTReader.h | 48 ++
 clang/include/clang/Serialization/ASTWriter.h |  4 +
 .../include/clang/Serialization/ModuleFile.h  | 14 ++-
 .../Serialization/SourceLocationEncoding.h| 91 +--
 clang/lib/Frontend/ASTUnit.cpp|  2 -
 clang/lib/Serialization/ASTReader.cpp | 57 
 clang/lib/Serialization/ASTReaderDecl.cpp |  2 +-
 clang/lib/Serialization/ASTWriter.cpp | 41 +++--
 clang/lib/Serialization/ASTWriterDecl.cpp |  8 +-
 clang/lib/Serialization/ModuleFile.cpp|  1 -
 .../no-transitive-source-location-change.cppm | 69 ++
 clang/test/Modules/pr61067.cppm   | 25 -
 .../SourceLocationEncodingTest.cpp| 12 ++-
 15 files changed, 269 insertions(+), 162 deletions(-)
 create mode 100644 clang/test/Modules/no-transitive-source-location-change.cppm

diff --git a/clang/include/clang/Basic/SourceLocation.h 
b/clang/include/clang/Basic/SourceLocation.h
index 00b1e0fa855b7a..7a0f5ba8d1270b 100644
--- a/clang/include/clang/Basic/SourceLocation.h
+++ b/clang/include/clang/Basic/SourceLocation.h
@@ -90,6 +90,7 @@ class SourceLocation {
   friend class ASTWriter;
   friend class SourceManager;
   friend struct llvm::FoldingSetTrait;
+  friend class SourceLocationEncoding;
 
 public:
   using UIntTy = uint32_t;
diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 186c3b722ced16..94a3d24d47926b 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -23,6 +23,7 @@
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Serialization/SourceLocationEncoding.h"
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Bitstream/BitCodes.h"
 #include 
@@ -167,45 +168,38 @@ const unsigned int NUM_PREDEF_SUBMODULE_IDS = 1;
 
 /// Source range/offset of a preprocessed entity.
 struct PPEntityOffset {
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Raw source location of beginning of range.
-  SourceLocation::UIntTy Begin;
+  RawLocEncoding Begin;
 
   /// Raw source location of end of range.
-  SourceLocation::UIntTy End;
+  RawLocEncoding End;
 
   /// Offset in the AST file relative to ModuleFile::MacroOffsetsBase.
   uint32_t BitOffset;
 
-  PPEntityOffset(SourceRange R, uint32_t BitOffset)
-  : Begin(R.getBegin().getRawEncoding()), End(R.getEnd().getRawEncoding()),
-BitOffset(BitOffset) {}
-
-  SourceLocation getBegin() const {
-return SourceLocation::getFromRawEncoding(Begin);
-  }
+  PPEntityOffset(RawLocEncoding Begin, RawLocEncoding End, uint32_t BitOffset)
+  : Begin(Begin), End(End), BitOffset(BitOffset) {}
 
-  SourceLocation getEnd() const {
-return SourceLocation::getFromRawEncoding(End);
-  }
+  RawLocEncoding getBegin() const { return Begin; }
+  RawLocEncoding getEnd() const { return End; }
 };
 
 /// Source range of a skipped preprocessor region
 struct PPSkippedRange {
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Raw source location of beginning of range.
-  SourceLocation::UIntTy Begin;
+  RawLocEncoding Begin;
   /// Raw source location of end of range.
-  SourceLocation::UIntTy End;
+  RawLocEncoding End;
 
-  PPSkippedRange(SourceRange R)
-  : Begin(R.getBegin().getRawEncoding()), End(R.getEnd().getRawEncoding()) 
{
-  }
+  PPSkippedRange(RawLocEncoding Begin, RawLocEncoding End)
+  : Begin(Begin), End(End) {}
 
-  SourceLocation getBegin() const {
-return SourceLocation::getFromRawEncoding(Begin);
-  }
-  SourceLocation getEnd() const {
-return SourceLocation::getFromRawEncoding(End);
-  }
+  RawLocEncoding getBegin() const { return Begin; }
+  RawLocEncoding getEnd() const { return End; }
 };
 
 /// Offset in the AST file. Use splitted 64-bit integer into low/high
@@ -231,8 +225,10 @@ struct UnderalignedInt64 {
 
 /// Source location and bit offset of a declaration.
 struct DeclOffset {
+  using RawLocEncoding = SourceLocationEncoding::RawLocEncoding;
+
   /// Raw source location.
-  SourceLocation::UIntTy Loc = 0;
+  RawLocEncoding RawLoc = 0;
 
   /// Offset relative to the start of the DECLTYPES_BLOCK block. Keep
   /// structure alignment 32-bit and avoid padding gap because undefined
@@ -240,17 +236,15 @@ struct DeclOffset {
   UnderalignedInt64 BitOffset;
 
   DeclOffset() = default;
-  DeclOffset(SourceLocation Loc, uint64_t BitOffset,
- uint

[clang] [Modules] No transitive source location change (PR #86912)

2024-04-25 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> The changes LGTM, don't want to block this on my remaining nits.

Thanks for reviewing this.

> 
> I believe @Bigcheese wanted to test test impact on PCM size on our side 
> before this lands.

I've rebased this with main. I'll wait for the results from @Bigcheese 

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


[clang] [Serialization] Load Specializations Lazily (PR #76774)

2024-04-25 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Given we're pursuing https://github.com/llvm/llvm-project/pull/83237 series. 
I'll close this one.

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


[clang] [Serialization] Load Specializations Lazily (PR #76774)

2024-04-25 Thread Chuanqi Xu via cfe-commits

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


[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

2024-04-25 Thread Shengchen Kan via cfe-commits

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

LGTM. My understanding is that this flag is used for reducing compile time and 
debug only.

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


[clang] [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (PR #90032)

2024-04-25 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams created 
https://github.com/llvm/llvm-project/pull/90032

Workaround for issue #89774 until it can be properly fixed.

When `-gtemplate-alias` is specified Clang emits a DW_TAG_template_alias for 
template aliases. This patch avoids an assertion failure by falling back to the 
 `-gno-template-alias` (default) behaviour, emitting a DW_TAG_typedef, if the 
alias is instantiation dependent.



>From 075a3f662807d2605964bd20b17e9552c07098be Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams 
Date: Thu, 25 Apr 2024 09:30:05 +0100
Subject: [PATCH] [Clang] Fall back to DW_TAG_typedef for instantiation
 dependent template aliases

Workaround for issue #89774
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 21 ++-
 .../CodeGenCXX/dependent-template-alias.cpp   | 21 +++
 2 files changed, 41 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenCXX/dependent-template-alias.cpp

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 539ded5cca5e1b..787db350487417 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1372,7 +1372,26 @@ llvm::DIType *CGDebugInfo::CreateType(const 
TemplateSpecializationType *Ty,
 
   SourceLocation Loc = AliasDecl->getLocation();
 
-  if (CGM.getCodeGenOpts().DebugTemplateAlias) {
+  if (CGM.getCodeGenOpts().DebugTemplateAlias &&
+  // The TemplateSpecializationType doesn't contain any instantiation
+  // information; dependent template arguments can't be resolved. For now,
+  // fall back to DW_TAG_typedefs for template aliases that are
+  // instantiation dependent, e.g.:
+  // ```
+  // template 
+  // using A = int;
+  //
+  // template
+  // struct S {
+  //   using AA = A; // Instantiation dependent.
+  //   AA aa;
+  // };
+  //
+  // S<0> s;
+  // ```
+  // S::AA's underlying type A is dependent on I so will be emitted as a
+  // DW_TAG_typedef.
+  !Ty->isInstantiationDependentType()) {
 auto ArgVector = ::GetTemplateArgs(TD, Ty);
 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
 
diff --git a/clang/test/CodeGenCXX/dependent-template-alias.cpp 
b/clang/test/CodeGenCXX/dependent-template-alias.cpp
new file mode 100644
index 00..deb243f9fc88d0
--- /dev/null
+++ b/clang/test/CodeGenCXX/dependent-template-alias.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-unk-unk -o - -emit-llvm 
-debug-info-kind=standalone -gtemplate-alias %s -gsimple-template-names=simple \
+// RUN: | FileCheck %s
+
+ Check that -gtemplate-alias falls back to DW_TAG_typedef emission
+ for instantiation dependent type aliases.
+
+template 
+using A = int;
+
+template
+struct S {
+  using AA = A;
+  AA aa;
+};
+
+S<0> s;
+
+// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "aa", scope: ![[#]], file: 
![[#]], line: [[#]], baseType: ![[AA:[0-9]+]], size: 32)
+// CHECK: [[AA]] = !DIDerivedType(tag: DW_TAG_typedef, name: "AA", file: 
![[#]], line: [[#]], baseType: ![[A:[0-9]+]])
+// CHECK: [[A]] = !DIDerivedType(tag: DW_TAG_typedef, name: "A", file: 
![[#]], line: [[#]], baseType: ![[int:[0-9]+]])
+// CHECK: [[int]] = !DIBasicType(name: "int", size: 32, encoding: 
DW_ATE_signed)

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


[clang] [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (PR #90032)

2024-04-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Orlando Cazalet-Hyams (OCHyams)


Changes

Workaround for issue #89774 until it can be properly fixed.

When `-gtemplate-alias` is specified Clang emits a DW_TAG_template_alias for 
template aliases. This patch avoids an assertion failure by falling back to the 
 `-gno-template-alias` (default) behaviour, emitting a DW_TAG_typedef, if the 
alias is instantiation dependent.



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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+20-1) 
- (added) clang/test/CodeGenCXX/dependent-template-alias.cpp (+21) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 539ded5cca5e1b..787db350487417 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1372,7 +1372,26 @@ llvm::DIType *CGDebugInfo::CreateType(const 
TemplateSpecializationType *Ty,
 
   SourceLocation Loc = AliasDecl->getLocation();
 
-  if (CGM.getCodeGenOpts().DebugTemplateAlias) {
+  if (CGM.getCodeGenOpts().DebugTemplateAlias &&
+  // The TemplateSpecializationType doesn't contain any instantiation
+  // information; dependent template arguments can't be resolved. For now,
+  // fall back to DW_TAG_typedefs for template aliases that are
+  // instantiation dependent, e.g.:
+  // ```
+  // template 
+  // using A = int;
+  //
+  // template
+  // struct S {
+  //   using AA = A; // Instantiation dependent.
+  //   AA aa;
+  // };
+  //
+  // S<0> s;
+  // ```
+  // S::AA's underlying type A is dependent on I so will be emitted as a
+  // DW_TAG_typedef.
+  !Ty->isInstantiationDependentType()) {
 auto ArgVector = ::GetTemplateArgs(TD, Ty);
 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
 
diff --git a/clang/test/CodeGenCXX/dependent-template-alias.cpp 
b/clang/test/CodeGenCXX/dependent-template-alias.cpp
new file mode 100644
index 00..deb243f9fc88d0
--- /dev/null
+++ b/clang/test/CodeGenCXX/dependent-template-alias.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-unk-unk -o - -emit-llvm 
-debug-info-kind=standalone -gtemplate-alias %s -gsimple-template-names=simple \
+// RUN: | FileCheck %s
+
+ Check that -gtemplate-alias falls back to DW_TAG_typedef emission
+ for instantiation dependent type aliases.
+
+template 
+using A = int;
+
+template
+struct S {
+  using AA = A;
+  AA aa;
+};
+
+S<0> s;
+
+// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "aa", scope: ![[#]], file: 
![[#]], line: [[#]], baseType: ![[AA:[0-9]+]], size: 32)
+// CHECK: [[AA]] = !DIDerivedType(tag: DW_TAG_typedef, name: "AA", file: 
![[#]], line: [[#]], baseType: ![[A:[0-9]+]])
+// CHECK: [[A]] = !DIDerivedType(tag: DW_TAG_typedef, name: "A", file: 
![[#]], line: [[#]], baseType: ![[int:[0-9]+]])
+// CHECK: [[int]] = !DIBasicType(name: "int", size: 32, encoding: 
DW_ATE_signed)

``




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


[clang] [clang] pointer to member with qualified-id enclosed in parentheses in unevaluated context should be invalid (PR #89713)

2024-04-25 Thread via cfe-commits

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


[clang] [clang-repl] Fix the process return code if diagnostics occurred. (PR #89879)

2024-04-25 Thread Stefan Gränitz via cfe-commits

weliveindetail wrote:

> The Unix pre-merge seems okay, however the windows pre-merge check is doing 
> nothing for more than 12h.

Yeah same here. I recognized that Windows PR checks are running Flang 
regression tests now. I guess that adds a huge load on the builders and causes 
the delays. Mine was cancelled after 15h.. 
https://github.com/llvm/llvm-project/pull/89734

@philnik777 Brought it up in Discord on Wednesday 
https://discord.com/channels/636084430946959380/645949235295944724/1232232568196173846

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


[clang] [llvm] [PowerPC] Tune AIX shared library TLS model at function level (PR #84132)

2024-04-25 Thread Kai Luo via cfe-commits


@@ -80,6 +80,7 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
   bool IsISA3_0 = false;
   bool IsISA3_1 = false;
   bool HasQuadwordAtomics = false;
+  bool HasAIXShLibTLSModelHeuristic = false;

bzEq wrote:

The variable defined here is only visible to clang and clang doesn't use this 
flag further. What backend sees is the feature string and set corresponding 
variables in backend accordingly.

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


[clang] D41416: [modules] [pch] Do not deserialize all lazy template specializations when looking for one. (PR #83108)

2024-04-25 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/83108

>From be1c83fb885536c3e65657c6549bd20dd29d9649 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Sun, 7 Jan 2018 15:16:11 +0200
Subject: [PATCH 1/3] D41416: [modules] [pch] Do not deserialize all lazy
 template specializations when looking for one.

---
 clang/include/clang/AST/DeclTemplate.h|  36 +++-
 clang/lib/AST/DeclTemplate.cpp| 100 +-
 clang/lib/AST/ODRHash.cpp |  15 
 clang/lib/Serialization/ASTReader.cpp |  25 --
 clang/lib/Serialization/ASTReaderDecl.cpp |  46 ++
 clang/lib/Serialization/ASTWriter.cpp |  21 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  76 +---
 7 files changed, 249 insertions(+), 70 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 3ee03eebdb8ca4..24578cfdaa7c7c 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -256,6 +256,9 @@ class TemplateArgumentList final
   TemplateArgumentList(const TemplateArgumentList &) = delete;
   TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
 
+  /// Create hash for the given arguments.
+  static unsigned ComputeODRHash(ArrayRef Args);
+
   /// Create a new template argument list that copies the given set of
   /// template arguments.
   static TemplateArgumentList *CreateCopy(ASTContext &Context,
@@ -730,6 +733,26 @@ class RedeclarableTemplateDecl : public TemplateDecl,
   }
 
   void anchor() override;
+  struct LazySpecializationInfo {
+GlobalDeclID DeclID = GlobalDeclID();
+unsigned ODRHash = ~0U;
+bool IsPartial = false;
+LazySpecializationInfo(GlobalDeclID ID, unsigned Hash = ~0U,
+   bool Partial = false)
+  : DeclID(ID), ODRHash(Hash), IsPartial(Partial) { }
+LazySpecializationInfo() { }
+bool operator<(const LazySpecializationInfo &Other) const {
+  return DeclID < Other.DeclID;
+}
+bool operator==(const LazySpecializationInfo &Other) const {
+  assert((DeclID != Other.DeclID || ODRHash == Other.ODRHash) &&
+ "Hashes differ!");
+  assert((DeclID != Other.DeclID || IsPartial == Other.IsPartial) &&
+ "Both must be the same kinds!");
+  return DeclID == Other.DeclID;
+}
+  };
+
 protected:
   template  struct SpecEntryTraits {
 using DeclType = EntryType;
@@ -770,7 +793,12 @@ class RedeclarableTemplateDecl : public TemplateDecl,
 return SpecIterator(isEnd ? Specs.end() : Specs.begin());
   }
 
-  void loadLazySpecializationsImpl() const;
+  void loadLazySpecializationsImpl(bool OnlyPartial = false) const;
+
+  void loadLazySpecializationsImpl(llvm::ArrayRef Args,
+   TemplateParameterList *TPL = nullptr) const;
+
+  Decl *loadLazySpecializationImpl(LazySpecializationInfo &LazySpecInfo) const;
 
   template 
   typename SpecEntryTraits::DeclType*
@@ -797,7 +825,7 @@ class RedeclarableTemplateDecl : public TemplateDecl,
 ///
 /// The first value in the array is the number of specializations/partial
 /// specializations that follow.
-GlobalDeclID *LazySpecializations = nullptr;
+LazySpecializationInfo *LazySpecializations = nullptr;
 
 /// The set of "injected" template arguments used within this
 /// template.
@@ -2284,7 +2312,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl 
{
   friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
+  void LoadLazySpecializations(bool OnlyPartial = false) const;
 
   /// Get the underlying class declarations of the template.
   CXXRecordDecl *getTemplatedDecl() const {
@@ -3056,7 +3084,7 @@ class VarTemplateDecl : public RedeclarableTemplateDecl {
   friend class ASTDeclWriter;
 
   /// Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
+  void LoadLazySpecializations(bool OnlyPartial = false) const;
 
   /// Get the underlying variable declarations of the template.
   VarDecl *getTemplatedDecl() const {
diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp
index d27a30e0c5fce1..1afd7b4550c917 100644
--- a/clang/lib/AST/DeclTemplate.cpp
+++ b/clang/lib/AST/DeclTemplate.cpp
@@ -20,6 +20,8 @@
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/ODRHash.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/LLVM.h"
@@ -331,17 +333,46 @@ RedeclarableTemplateDecl::CommonBase 
*RedeclarableTemplateDecl::getCommonPtr() c
   return Common;
 }
 
-void RedeclarableTemplateDecl::loadLazySpecializationsImpl() const {
+void RedeclarableTemplateDecl::loadLazySpecializationsImpl(
+ 

[clang] D41416: [modules] [pch] Do not deserialize all lazy template specializations when looking for one. (PR #83108)

2024-04-25 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Rebased with main.

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


[clang] [llvm] [PowerPC] Tune AIX shared library TLS model at function level (PR #84132)

2024-04-25 Thread Kai Luo via cfe-commits


@@ -80,6 +80,7 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
   bool IsISA3_0 = false;
   bool IsISA3_1 = false;
   bool HasQuadwordAtomics = false;
+  bool HasAIXShLibTLSModelHeuristic = false;

bzEq wrote:

Code in `PPCTargetLowering::LowerGlobalTLSAddressAIX` like
```
Subtarget.hasAIXSmallLocalExecTLS()
```
which is generated in `PPCGenSubtargetInfo.inc`, whose value is initialized by 
feature string `aix-small-local-exec-tls` in LLVM IR rather than the variable 
defined in clang.

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


[clang] [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (PR #90032)

2024-04-25 Thread Michael Buch via cfe-commits

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


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


[clang] 87ec4ab - [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (#90032)

2024-04-25 Thread via cfe-commits

Author: Orlando Cazalet-Hyams
Date: 2024-04-25T10:34:32+01:00
New Revision: 87ec4ab72cb3ae27ac08d040b2825ee01214fe75

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

LOG: [Clang] Fall back to DW_TAG_typedef for instantiation dependent template 
aliases (#90032)

Workaround for issue #89774 until it can be properly fixed.

When `-gtemplate-alias` is specified Clang emits a DW_TAG_template_alias
for template aliases. This patch avoids an assertion failure by falling
back to the `-gno-template-alias` (default) behaviour, emitting a
DW_TAG_typedef, if the alias is instantiation dependent.

Added: 
clang/test/CodeGenCXX/dependent-template-alias.cpp

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 539ded5cca5e1b..787db350487417 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1372,7 +1372,26 @@ llvm::DIType *CGDebugInfo::CreateType(const 
TemplateSpecializationType *Ty,
 
   SourceLocation Loc = AliasDecl->getLocation();
 
-  if (CGM.getCodeGenOpts().DebugTemplateAlias) {
+  if (CGM.getCodeGenOpts().DebugTemplateAlias &&
+  // The TemplateSpecializationType doesn't contain any instantiation
+  // information; dependent template arguments can't be resolved. For now,
+  // fall back to DW_TAG_typedefs for template aliases that are
+  // instantiation dependent, e.g.:
+  // ```
+  // template 
+  // using A = int;
+  //
+  // template
+  // struct S {
+  //   using AA = A; // Instantiation dependent.
+  //   AA aa;
+  // };
+  //
+  // S<0> s;
+  // ```
+  // S::AA's underlying type A is dependent on I so will be emitted as a
+  // DW_TAG_typedef.
+  !Ty->isInstantiationDependentType()) {
 auto ArgVector = ::GetTemplateArgs(TD, Ty);
 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
 

diff  --git a/clang/test/CodeGenCXX/dependent-template-alias.cpp 
b/clang/test/CodeGenCXX/dependent-template-alias.cpp
new file mode 100644
index 00..deb243f9fc88d0
--- /dev/null
+++ b/clang/test/CodeGenCXX/dependent-template-alias.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-unk-unk -o - -emit-llvm 
-debug-info-kind=standalone -gtemplate-alias %s -gsimple-template-names=simple \
+// RUN: | FileCheck %s
+
+ Check that -gtemplate-alias falls back to DW_TAG_typedef emission
+ for instantiation dependent type aliases.
+
+template 
+using A = int;
+
+template
+struct S {
+  using AA = A;
+  AA aa;
+};
+
+S<0> s;
+
+// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "aa", scope: ![[#]], file: 
![[#]], line: [[#]], baseType: ![[AA:[0-9]+]], size: 32)
+// CHECK: [[AA]] = !DIDerivedType(tag: DW_TAG_typedef, name: "AA", file: 
![[#]], line: [[#]], baseType: ![[A:[0-9]+]])
+// CHECK: [[A]] = !DIDerivedType(tag: DW_TAG_typedef, name: "A", file: 
![[#]], line: [[#]], baseType: ![[int:[0-9]+]])
+// CHECK: [[int]] = !DIBasicType(name: "int", size: 32, encoding: 
DW_ATE_signed)



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


[clang] [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (PR #90032)

2024-04-25 Thread Orlando Cazalet-Hyams via cfe-commits

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


[clang] [llvm] [AArch64][SME] Add intrinsics for multi-vector BFCLAMP (PR #88251)

2024-04-25 Thread via cfe-commits

https://github.com/Lukacma updated 
https://github.com/llvm/llvm-project/pull/88251

>From fe692284cd248e372302671e094eb9950edb5ee5 Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Wed, 10 Apr 2024 10:20:03 +
Subject: [PATCH 1/3] [AArch64][SME] Add intrinsics for multi-vector BFCLAMP

---
 clang/include/clang/Basic/arm_sve.td  |  5 ++
 .../aarch64-sme2-intrinsics/acle_sme2_clamp.c | 72 +--
 llvm/include/llvm/IR/IntrinsicsAArch64.td |  2 +
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp|  6 ++
 .../AArch64/sve2p1-intrinsics-bfclamp.ll  | 26 ++-
 5 files changed, 106 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 6da30e08e7521e..63ca495a1bc9f1 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -2148,6 +2148,11 @@ let TargetGuard = "sme2" in {
   def SVSCLAMP_X4 : SInst<"svclamp[_single_{d}_x4]",  "44dd",   "csil", 
MergeNone, "aarch64_sve_sclamp_single_x4",  [IsStreaming], []>;
   def SVUCLAMP_X4 : SInst<"svclamp[_single_{d}_x4]",  "44dd",   "UcUsUiUl", 
MergeNone, "aarch64_sve_uclamp_single_x4",  [IsStreaming], []>;
   def SVFCLAMP_X4 : SInst<"svclamp[_single_{d}_x4]",  "44dd",   "hfd",  
MergeNone, "aarch64_sve_fclamp_single_x4",  [IsStreaming], []>;
+
+  let TargetGuard = "b16b16"in {
+def SVBFCLAMP_X2 : SInst<"svclamp[_single_{d}_x2]",  "22dd",   "b",  
MergeNone, "aarch64_sve_bfclamp_single_x2",  [IsStreaming], []>;
+def SVBFCLAMP_X4 : SInst<"svclamp[_single_{d}_x4]",  "44dd",   "b",  
MergeNone, "aarch64_sve_bfclamp_single_x4",  [IsStreaming], []>;
+  }
 }
 
 let TargetGuard = "sme2" in {
diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_clamp.c 
b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_clamp.c
index 257cb595250181..1dd5aeee35fe73 100644
--- a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_clamp.c
+++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_clamp.c
@@ -1,12 +1,12 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // REQUIRES: aarch64-registered-target
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 \
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 
-target-feature +b16b16 \
 // RUN:  -S -Werror -emit-llvm -disable-O0-optnone -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
-// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 \
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +b16b16 \
 // RUN:  -S -Werror -emit-llvm -disable-O0-optnone -o - %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 \
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 
-target-feature +b16b16 \
 // RUN:  -S -Werror -emit-llvm -disable-O0-optnone -o - -x c++ %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s -check-prefix=CPP-CHECK
-// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 \
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu 
-target-feature +sme2 -target-feature +b16b16 \
 // RUN:  -S -Werror -emit-llvm -disable-O0-optnone -o - -x c++ %s | opt -S -p 
mem2reg,instcombine,tailcallelim | FileCheck %s -check-prefix=CPP-CHECK
 // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sme2 \
 // RUN:  -S -disable-O0-optnone -Werror -Wall -o /dev/null %s
@@ -745,3 +745,67 @@ svfloat32x4_t test_svclamp_single_f32_x4(svfloat32x4_t 
op1, svfloat32_t op2, svf
 svfloat64x4_t test_svclamp_single_f64_x4(svfloat64x4_t op1, svfloat64_t op2, 
svfloat64_t op3) __arm_streaming {
   return SVE_ACLE_FUNC(svclamp, _single_f64_x4, , )(op1, op2, op3);
 }
+
+// CHECK-LABEL: @test_svclamp_single_bf16_x2(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.vector.extract.nxv8bf16.nxv16bf16( [[OP1:%.*]], i64 
0)
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.vector.extract.nxv8bf16.nxv16bf16( [[OP1]], i64 8)
+// CHECK-NEXT:[[TMP2:%.*]] = tail call { ,  } @llvm.aarch64.sve.bfclamp.single.x2.nxv8bf16( [[TMP0]],  [[TMP1]],  
[[OP2:%.*]],  [[OP3:%.*]])
+// CHECK-NEXT:[[TMP3:%.*]] = extractvalue { ,  } [[TMP2]], 0
+// CHECK-NEXT:[[TMP4:%.*]] = tail call  
@llvm.vector.insert.nxv16bf16.nxv8bf16( poison,  [[TMP3]], i64 0)
+// CHECK-NEXT:[[TMP5:%.*]] = extractvalue { ,  } [[TMP2]], 1
+// CHECK-NEXT:[[TMP6:%.*]] = tail call  
@llvm.vector.insert.nxv16bf16.nxv8bf16( [[TMP4]],  [[TMP5]], i64 8)
+// CHECK-NEXT:ret  [[TMP6]]
+//
+// CPP-CHECK-LABEL: 
@_Z27test_svclamp_single_bf16_x214svbfloat16x2_tu14__SVBfloat16_tS0_(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.vector.extract.nxv8bf16.nxv16bf16( [[OP1:%.*]], i64 
0)
+// CPP-CHE

[clang] [Clang][C++23] Core language changes from P1467R9 extended floating-point types and standard names. (PR #78503)

2024-04-25 Thread via cfe-commits

cor3ntin wrote:

@codemzs Any news? Thanks a lot for your work!

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


[clang] 2c5d7a8 - [clang-format] Remove YAML hack to emit a BasedOnStyle comment (#89228)

2024-04-25 Thread via cfe-commits

Author: Jannik Silvanus
Date: 2024-04-25T12:47:43+02:00
New Revision: 2c5d7a888589a608a4cd6adc34f19a65dc4551af

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

LOG: [clang-format] Remove YAML hack to emit a BasedOnStyle comment (#89228)

When serializing a formatting style to YAML, we were emitting a comment
`# BasedOnStyle: 

[clang] [clang-format] Remove YAML hack to emit a BasedOnStyle comment (PR #89228)

2024-04-25 Thread Jannik Silvanus via cfe-commits

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


[clang] [Clang][Sema] fix a bug on template partial specialization (PR #89862)

2024-04-25 Thread Qizhi Hu via cfe-commits


@@ -7706,7 +7706,7 @@ ExprResult 
Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
 // FIXME: The language rules don't say what happens in this case.
 // FIXME: We get an opaque dependent type out of decltype(auto) if the
 // expression is merely instantiation-dependent; is this enough?
-if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
+if (Arg->isTypeDependent()) {

jcsxky wrote:

After looking into the code a bit more, I think this won't happen since the 
type of `Arg` can't be dependent if the condition `CTAK == 
CTAK_DeducedFromArrayBound` holds. Because it has been deduced as a certain 
expression at the moment.

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


[clang] 03b1a0c - [Clang] Diagnose apply AST consume actions on LLVM IR (#88602)

2024-04-25 Thread via cfe-commits

Author: yronglin
Date: 2024-04-25T19:05:46+08:00
New Revision: 03b1a0c2a72dd24943642ef15e6c046d982643c2

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

LOG: [Clang] Diagnose apply AST consume actions on LLVM IR (#88602)

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

This PR introduce a new diagnostic to report apply AST consume actions
on LLVM IR.

-

Signed-off-by: yronglin 

Added: 
clang/test/Frontend/ast-dump-on-llvm.ll

Modified: 
clang/include/clang/Basic/DiagnosticFrontendKinds.td
clang/lib/Frontend/FrontendAction.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 14b08d4927ec5e..fcffadacc8e631 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -370,4 +370,7 @@ def warn_missing_symbol_graph_dir : Warning<
   "Missing symbol graph output directory, defaulting to working directory">,
   InGroup;
 
+def err_ast_action_on_llvm_ir : Error<
+  "cannot apply AST actions to LLVM IR file '%0'">,
+  DefaultFatal;
 }

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index a2af738a053e5b..9ae7664b4b49d4 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -757,8 +757,11 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
 
   // IR files bypass the rest of initialization.
   if (Input.getKind().getLanguage() == Language::LLVM_IR) {
-assert(hasIRSupport() &&
-   "This action does not have IR file support!");
+if (!hasIRSupport()) {
+  CI.getDiagnostics().Report(diag::err_ast_action_on_llvm_ir)
+  << Input.getFile();
+  return false;
+}
 
 // Inform the diagnostic client we are processing a source file.
 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);

diff  --git a/clang/test/Frontend/ast-dump-on-llvm.ll 
b/clang/test/Frontend/ast-dump-on-llvm.ll
new file mode 100644
index 00..cdacfde4ba848c
--- /dev/null
+++ b/clang/test/Frontend/ast-dump-on-llvm.ll
@@ -0,0 +1,29 @@
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-AST-DUMP
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=json %s -o - 
2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-JSON
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=default %s -o - 
2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-DEFAULT
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all %s -o - 
2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=json %s -o 
- 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-JSON
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=default %s 
-o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-DEFAULT
+
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-print %s -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-AST-PRINT
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-view %s -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-AST-VIEW
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-list %s -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-AST-LIST
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-lookups %s -o - 
2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-LOOKUP
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown 
-ast-dump-filter=FunctionDecl %s -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-AST-DUMP-FILTER-EQ
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-decl-types %s 
-o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-DECL-TYPES
+; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only %s -o - 
2>&1 | FileCheck %s --check-prefix=CHECK-SYNTAX-ONLY
+
+
+; CHECK-AST-DUMP: fatal error: cannot apply AST actions to LLVM IR file 
'{{.*}}'
+; CHECK-AST-DUMP-EQ-JSON: fatal error: cannot apply AST actions to LLVM IR 
file '{{.*}}'
+; CHECK-AST-DUMP-EQ-DEFAULT: fatal error: cannot apply AST actions to LLVM IR 
file '{{.*}}'
+; CHECK-AST-DUMP-ALL: fatal error: cannot apply AST actions to LLVM IR file 
'{{.*}}'
+; CHECK-AST-DUMP-ALL-EQ-JSON: fatal error: cannot apply AST actions to LLVM IR 
file '{{.*}}'
+; CHECK-AST-DUMP-ALL-EQ-DEFAULT: fatal error: cannot apply AST actions to LLVM 
IR file '{{.*}}'
+; CHECK-AST-PRINT: fatal error: cannot apply AST actions to LLVM IR file 
'{{.*}}'
+; CHECK-AST-VIEW: fatal error: cannot apply AST actions to LLVM IR file 
'{{.*}}'
+; CHECK-AST-LIST: fatal error: cannot apply AST actions to LLVM IR file 
'{{.*}}'
+; CHECK-AST-DUMP-LOOKUP: fatal

[clang] [Clang] Diagnose apply AST consume actions on LLVM IR (PR #88602)

2024-04-25 Thread via cfe-commits

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-25 Thread Tom Eccles via cfe-commits


@@ -6582,12 +6582,6 @@ def J : JoinedOrSeparate<["-"], "J">,
   Group,
   Alias;
 
-let Visibility = [FlangOption] in {
-def no_fortran_main : Flag<["-"], "fno-fortran-main">,

tblah wrote:

Will this break existing build systems configured to use this flag?

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-25 Thread Tom Eccles via cfe-commits

https://github.com/tblah commented:

Thanks for this. I'm sure it will give a big improvement to the experience of 
building applications with flang.

Code changes look good to me. I'm worried about how this could break existing 
builds using `-fno-fortran-main` and `-lFortran_main`. Do you have a transition 
plan for this?

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-25 Thread Tom Eccles via cfe-commits

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-25 Thread Tom Eccles via cfe-commits


@@ -1191,118 +1191,10 @@ bool tools::addOpenMPRuntime(const Compilation &C, 
ArgStringList &CmdArgs,
   return true;
 }
 
-/// Determines if --whole-archive is active in the list of arguments.
-static bool isWholeArchivePresent(const ArgList &Args) {
-  bool WholeArchiveActive = false;
-  for (auto *Arg : Args.filtered(options::OPT_Wl_COMMA)) {
-if (Arg) {
-  for (StringRef ArgValue : Arg->getValues()) {
-if (ArgValue == "--whole-archive")
-  WholeArchiveActive = true;
-if (ArgValue == "--no-whole-archive")
-  WholeArchiveActive = false;
-  }
-}
-  }
-
-  return WholeArchiveActive;
-}
-
-/// Determine if driver is invoked to create a shared object library (-static)
-static bool isSharedLinkage(const ArgList &Args) {
-  return Args.hasArg(options::OPT_shared);
-}
-
-/// Determine if driver is invoked to create a static object library (-shared)
-static bool isStaticLinkage(const ArgList &Args) {
-  return Args.hasArg(options::OPT_static);
-}
-
-/// Add Fortran runtime libs for MSVC
-static void addFortranRuntimeLibsMSVC(const ArgList &Args,
-  llvm::opt::ArgStringList &CmdArgs) {
-  unsigned RTOptionID = options::OPT__SLASH_MT;
-  if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
-RTOptionID = llvm::StringSwitch(rtl->getValue())
- .Case("static", options::OPT__SLASH_MT)
- .Case("static_dbg", options::OPT__SLASH_MTd)
- .Case("dll", options::OPT__SLASH_MD)
- .Case("dll_dbg", options::OPT__SLASH_MDd)
- .Default(options::OPT__SLASH_MT);
-  }
-  switch (RTOptionID) {
-  case options::OPT__SLASH_MT:
-CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static.lib");
-break;
-  case options::OPT__SLASH_MTd:
-CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static_dbg.lib");
-break;
-  case options::OPT__SLASH_MD:
-CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic.lib");
-break;
-  case options::OPT__SLASH_MDd:
-CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic_dbg.lib");
-break;
-  }
-}
-
-// Add FortranMain runtime lib
-static void addFortranMain(const ToolChain &TC, const ArgList &Args,
-   llvm::opt::ArgStringList &CmdArgs) {
-  // 0. Shared-library linkage
-  // If we are attempting to link a library, we should not add
-  // -lFortran_main.a to the link line, as the `main` symbol is not
-  // required for a library and should also be provided by one of
-  // the translation units of the code that this shared library
-  // will be linked against eventually.
-  if (isSharedLinkage(Args) || isStaticLinkage(Args)) {
-return;
-  }
-
-  // 1. MSVC
-  if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
-addFortranRuntimeLibsMSVC(Args, CmdArgs);
-return;
-  }
-
-  // 2. GNU and similar
-  const Driver &D = TC.getDriver();
-  const char *FortranMainLinkFlag = "-lFortran_main";
-
-  // Warn if the user added `-lFortran_main` - this library is an 
implementation
-  // detail of Flang and should be handled automaticaly by the driver.
-  for (const char *arg : CmdArgs) {
-if (strncmp(arg, FortranMainLinkFlag, strlen(FortranMainLinkFlag)) == 0)
-  D.Diag(diag::warn_drv_deprecated_custom)
-  << FortranMainLinkFlag
-  << "see the Flang driver documentation for correct usage";
-  }

tblah wrote:

Removing the Fortran_main library could also break existing builds, but I think 
it is more reasonable because it was deprecated since the last release.

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


[clang] [llvm] [LLVM][SVE] Seperate the int and floating-point variants of addqv. (PR #89762)

2024-04-25 Thread Dinar Temirbulatov via cfe-commits

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

LGTM.

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


[clang] Implementation of '#pragma STDC FENV_ROUND' (PR #89617)

2024-04-25 Thread Serge Pavlov via cfe-commits

https://github.com/spavloff updated 
https://github.com/llvm/llvm-project/pull/89617

>From 0fc5c57264ecf51f8b9fe8303520a51cb1fee40e Mon Sep 17 00:00:00 2001
From: Serge Pavlov 
Date: Thu, 14 Apr 2022 18:00:14 +0700
Subject: [PATCH 1/2] Implementation of '#pragma STDC FENV_ROUND'

This pragma is introduced by forthcoming C2x standard and can be used to
set particular rounding mode without need to call 'fesetmode' or accessing
control mode registers directly. Previously this pragma was implemented in
clang partially, only for the purpose of using in constant expressions and
making tests.

This change implements the pragma according to the standard draft. It sets
up dynamic rounding mode in the compound statement where the pragma acts.
This is inevitable for targets that set rounding mode by changing some
control register. Targets that support static rounding mode encoded in
instructions can have more efficient implementation, it is not
implemented in this change.

The implementation uses intrinsic functions 'get_rounding' and
'set_rounding' to save/restore dynamic rounding mode. In some cases
using functions that operate entire set of control modes or even FP
environment may give more efficient implementation. This optimization is
not a part of this change.
---
 clang/include/clang/AST/Stmt.h|   9 +
 .../clang/Basic/DiagnosticParseKinds.td   |   3 -
 clang/include/clang/Basic/LangOptions.h   |   6 +
 clang/lib/CodeGen/CGStmt.cpp  |  56 ++
 clang/lib/CodeGen/CodeGenFunction.h   |   3 +
 clang/lib/Parse/ParsePragma.cpp   |   3 -
 clang/test/CodeGen/complex-strictfp.c |  60 ---
 clang/test/CodeGen/math-errno.c   |   6 +-
 clang/test/CodeGen/pragma-fenv_access.c   |  45 -
 clang/test/CodeGen/pragma-fenv_round.c| 160 ++
 clang/test/Parser/pragma-fenv_round.c |   1 -
 11 files changed, 315 insertions(+), 37 deletions(-)
 create mode 100644 clang/test/CodeGen/pragma-fenv_round.c

diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index 9cd7a364cd3f1d..6eceecd93e59c2 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1658,6 +1658,15 @@ class CompoundStmt final
 return *getTrailingObjects();
   }
 
+  /// Get FPOptions inside this statement. They may differ from the outer
+  /// options due to pragmas.
+  /// \param CurFPOptions FPOptions outside this statement.
+  FPOptions getNewFPOptions(FPOptions CurFPOptions) const {
+return hasStoredFPFeatures()
+   ? getStoredFPFeatures().applyOverrides(CurFPOptions)
+   : CurFPOptions;
+  }
+
   using body_iterator = Stmt **;
   using body_range = llvm::iterator_range;
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 38174cf3549f14..329af794405998 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1257,9 +1257,6 @@ def ext_stdc_pragma_ignored : ExtWarn<"unknown pragma in 
STDC namespace">,
 // The C standard 7.6.1p2 says "The [FENV_ACCESS] pragma shall occur either
 // outside external declarations or preceding all explicit declarations and
 // statements inside a compound statement.
-def warn_stdc_fenv_round_not_supported :
-   Warning<"pragma STDC FENV_ROUND is not supported">,
-   InGroup;
 def warn_stdc_unknown_rounding_mode : Warning<
   "invalid or unsupported rounding mode in '#pragma STDC FENV_ROUND' - 
ignored">,
   InGroup;
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index ae4715921d1665..28164f564e907d 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -839,6 +839,12 @@ class FPOptions {
getAllowFEnvAccess();
   }
 
+  /// Checks if the rounding mode is unknown at compile-time.
+  bool isRoundingModeDynamic() const {
+return (getConstRoundingMode() == RoundingMode::Dynamic) &&
+   (getAllowFEnvAccess() || getRoundingMath());
+  }
+
   RoundingMode getRoundingMode() const {
 RoundingMode RM = getConstRoundingMode();
 if (RM == RoundingMode::Dynamic) {
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 576fe2f7a2d46f..4fbc906afaeed5 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -486,6 +486,56 @@ bool CodeGenFunction::EmitSimpleStmt(const Stmt *S,
   return true;
 }
 
+namespace {
+/// Cleanup action that restores floating-point control modes upon leaving
+/// a scope.
+struct FPControlModesCleanup final : EHScopeStack::Cleanup {
+  llvm::Value *PreviousModes;
+  FPControlModesCleanup(llvm::Value *M) : PreviousModes(M) {}
+  void Emit(CodeGenFunction &CGF, Flags flags) override {
+CGF.Builder.CreateIntrinsic(llvm::Intrinsic::set_rounding, {},
+{PreviousModes});
+  }
+};
+} // n

[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread Sebastian Wolf via cfe-commits

https://github.com/sebwolf-de created 
https://github.com/llvm/llvm-project/pull/90043

The string based test to find out whether the check is applicable on the class 
is not ideal, but I did not find a more elegant way, yet. If there is more 
clang-query magic available, that I'm not aware of, I'm happy to adapt that.

>From 8eb5863305e8f9a1311a540faf35f24fc6f55c6c Mon Sep 17 00:00:00 2001
From: Sebastian Wolf 
Date: Wed, 17 Apr 2024 16:16:35 +0200
Subject: [PATCH] Enforce SL.con.3: Add check to replace operator[] with at()
 on std containers

---
 .../AvoidBoundsErrorsCheck.cpp| 81 +++
 .../AvoidBoundsErrorsCheck.h  | 32 
 .../cppcoreguidelines/CMakeLists.txt  |  1 +
 .../CppCoreGuidelinesTidyModule.cpp   |  3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 ++
 .../cppcoreguidelines/avoid-bounds-errors.rst | 20 +
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../cppcoreguidelines/avoid-bounds-errors.cpp | 66 +++
 8 files changed, 209 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-bounds-errors.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-bounds-errors.cpp

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
new file mode 100644
index 00..524c21b5bdb818
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+bool isApplicable(const QualType &Type) {
+  const auto TypeStr = Type.getAsString();
+  bool Result = false;
+  // Only check for containers in the std namespace
+  if (TypeStr.find("std::vector") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::array") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::deque") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::unordered_map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::flat_map") != std::string::npos) {
+Result = true;
+  }
+  // TODO Add std::span with C++26
+  return Result;
+}
+
+void AvoidBoundsErrorsCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(callee(cxxMethodDecl(hasName("operator[]")).bind("f")))
+  .bind("x"),
+  this);
+}
+
+void AvoidBoundsErrorsCheck::check(const MatchFinder::MatchResult &Result) {
+  const ASTContext &Context = *Result.Context;
+  const SourceManager &Source = Context.getSourceManager();
+  const auto *MatchedExpr = Result.Nodes.getNodeAs("x");
+  const auto *MatchedFunction = Result.Nodes.getNodeAs("f");
+  const auto Type = MatchedFunction->getThisType();
+  if (!isApplicable(Type)) {
+return;
+  }
+
+  // Get original code.
+  const SourceLocation b(MatchedExpr->getBeginLoc());
+  const SourceLocation e(MatchedExpr->getEndLoc());
+  const std::string OriginalCode =
+  Lexer::getSourceText(CharSourceRange::getTokenRange(b, e), Source,
+   getLangOpts())
+  .str();
+  const auto Range = SourceRange(b, e);
+
+  // Build replacement.
+  std::string NewCode = OriginalCode;
+  const auto BeginOpen = NewCode.find("[");
+  NewCode.replace(BeginOpen, 1, ".at(");
+  const auto BeginClose = NewCode.find("]");
+  NewCode.replace(BeginClose, 1, ")");
+
+  diag(MatchedExpr->getBeginLoc(), "Do not use operator[], use at() instead.")
+  << FixItHint::CreateReplacement(Range, NewCode);
+}
+
+} // namespace clang::tidy::cppcoreguidelines
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
new file mode 100644
index 00..f915729cd7bbee
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
@@ -0,0 +1,32 @@
+//===--- AvoidBoundsErrorsCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LL

[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Sebastian Wolf (sebwolf-de)


Changes

The string based test to find out whether the check is applicable on the class 
is not ideal, but I did not find a more elegant way, yet. If there is more 
clang-query magic available, that I'm not aware of, I'm happy to adapt that.

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


8 Files Affected:

- (added) 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp (+81) 
- (added) 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h (+32) 
- (modified) clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt (+1) 
- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp 
(+3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) 
- (added) 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-bounds-errors.rst
 (+20) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-bounds-errors.cpp
 (+66) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
new file mode 100644
index 00..524c21b5bdb818
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+bool isApplicable(const QualType &Type) {
+  const auto TypeStr = Type.getAsString();
+  bool Result = false;
+  // Only check for containers in the std namespace
+  if (TypeStr.find("std::vector") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::array") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::deque") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::unordered_map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::flat_map") != std::string::npos) {
+Result = true;
+  }
+  // TODO Add std::span with C++26
+  return Result;
+}
+
+void AvoidBoundsErrorsCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(callee(cxxMethodDecl(hasName("operator[]")).bind("f")))
+  .bind("x"),
+  this);
+}
+
+void AvoidBoundsErrorsCheck::check(const MatchFinder::MatchResult &Result) {
+  const ASTContext &Context = *Result.Context;
+  const SourceManager &Source = Context.getSourceManager();
+  const auto *MatchedExpr = Result.Nodes.getNodeAs("x");
+  const auto *MatchedFunction = Result.Nodes.getNodeAs("f");
+  const auto Type = MatchedFunction->getThisType();
+  if (!isApplicable(Type)) {
+return;
+  }
+
+  // Get original code.
+  const SourceLocation b(MatchedExpr->getBeginLoc());
+  const SourceLocation e(MatchedExpr->getEndLoc());
+  const std::string OriginalCode =
+  Lexer::getSourceText(CharSourceRange::getTokenRange(b, e), Source,
+   getLangOpts())
+  .str();
+  const auto Range = SourceRange(b, e);
+
+  // Build replacement.
+  std::string NewCode = OriginalCode;
+  const auto BeginOpen = NewCode.find("[");
+  NewCode.replace(BeginOpen, 1, ".at(");
+  const auto BeginClose = NewCode.find("]");
+  NewCode.replace(BeginClose, 1, ")");
+
+  diag(MatchedExpr->getBeginLoc(), "Do not use operator[], use at() instead.")
+  << FixItHint::CreateReplacement(Range, NewCode);
+}
+
+} // namespace clang::tidy::cppcoreguidelines
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
new file mode 100644
index 00..f915729cd7bbee
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
@@ -0,0 +1,32 @@
+//===--- AvoidBoundsErrorsCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_AVOIDBOUNDSERRORSCHECK_H
+#define 

[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Sebastian Wolf (sebwolf-de)


Changes

The string based test to find out whether the check is applicable on the class 
is not ideal, but I did not find a more elegant way, yet. If there is more 
clang-query magic available, that I'm not aware of, I'm happy to adapt that.

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


8 Files Affected:

- (added) 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp (+81) 
- (added) 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h (+32) 
- (modified) clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt (+1) 
- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp 
(+3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) 
- (added) 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-bounds-errors.rst
 (+20) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-bounds-errors.cpp
 (+66) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
new file mode 100644
index 00..524c21b5bdb818
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.cpp
@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+bool isApplicable(const QualType &Type) {
+  const auto TypeStr = Type.getAsString();
+  bool Result = false;
+  // Only check for containers in the std namespace
+  if (TypeStr.find("std::vector") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::array") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::deque") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::unordered_map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::flat_map") != std::string::npos) {
+Result = true;
+  }
+  // TODO Add std::span with C++26
+  return Result;
+}
+
+void AvoidBoundsErrorsCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(callee(cxxMethodDecl(hasName("operator[]")).bind("f")))
+  .bind("x"),
+  this);
+}
+
+void AvoidBoundsErrorsCheck::check(const MatchFinder::MatchResult &Result) {
+  const ASTContext &Context = *Result.Context;
+  const SourceManager &Source = Context.getSourceManager();
+  const auto *MatchedExpr = Result.Nodes.getNodeAs("x");
+  const auto *MatchedFunction = Result.Nodes.getNodeAs("f");
+  const auto Type = MatchedFunction->getThisType();
+  if (!isApplicable(Type)) {
+return;
+  }
+
+  // Get original code.
+  const SourceLocation b(MatchedExpr->getBeginLoc());
+  const SourceLocation e(MatchedExpr->getEndLoc());
+  const std::string OriginalCode =
+  Lexer::getSourceText(CharSourceRange::getTokenRange(b, e), Source,
+   getLangOpts())
+  .str();
+  const auto Range = SourceRange(b, e);
+
+  // Build replacement.
+  std::string NewCode = OriginalCode;
+  const auto BeginOpen = NewCode.find("[");
+  NewCode.replace(BeginOpen, 1, ".at(");
+  const auto BeginClose = NewCode.find("]");
+  NewCode.replace(BeginClose, 1, ")");
+
+  diag(MatchedExpr->getBeginLoc(), "Do not use operator[], use at() instead.")
+  << FixItHint::CreateReplacement(Range, NewCode);
+}
+
+} // namespace clang::tidy::cppcoreguidelines
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
new file mode 100644
index 00..f915729cd7bbee
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidBoundsErrorsCheck.h
@@ -0,0 +1,32 @@
+//===--- AvoidBoundsErrorsCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_AVOIDBOUNDSERRORSCHECK_H
+#define 
LLVM_CL

[clang] [clang-tools-extra] [PAC][clang] Define `PointerAuthQualifier` and `PointerAuthenticationMode` (PR #84384)

2024-04-25 Thread Aaron Ballman via cfe-commits

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

LGTM, thank you for the improvement for performance!

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-25 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

@efriedma-quic Ping!

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


[clang] [clang] pointer to member with qualified-id enclosed in parentheses in unevaluated context should be invalid (PR #89713)

2024-04-25 Thread Brian Bi via cfe-commits

t3nsor wrote:

> @t3nsor Do you know the reason for the "not enclosed in parameters" in 
> https://eel.is/c++draft/expr.unary.op#4 ?

No I don't. If I had to guess, it might be because adding parentheses is 
intended to be used as a way to not create a pointer to member (and instead get 
an ordinary pointer to a member named by a qualified  name) sort of like how 
parentheses can be used to suppress ADL.

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


[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)

2024-04-25 Thread via cfe-commits

NagyDonat wrote:

@Troy-Butler
I initiated the merge, but it seems that github mangles the email metadata:
![image](https://github.com/llvm/llvm-project/assets/43410265/d783c97f-f5f7-469f-9f77-9689275ea429)
(Note that I obscured your email address in this screenshot, but it can be 
found within the commits that you published.)

- If you want to use your "real" email address as the Author of this commit, 
then you probably need to change your github account settings. (I don't know 
the exact details but IIRC you can toggle whether it will use your email 
address in your commits.)
- If you don't want to embed that email address into the LLVM git history, then 
I can merge the commit without the `Signed-off-by` and `Co-authored-by` lines 
that mention it. The address will remain on the internet (in this pull 
request), but it won't be part of the LLVM main branch.


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


[clang] [clang] deprecate frelaxed-template-template-args, make it on by default (PR #89807)

2024-04-25 Thread Yaxun Liu via cfe-commits

yxsamliu wrote:

> This patch will finally allow us to mark C++17 support in clang as complete.
> 
> This is a continuation of the review process from an [old PR in 
> phab](https://reviews.llvm.org/D109496).
> 
> Recap: The original patch from phab initially contained no workarounds / 
> provisional resolutions for core defects, Though testing by @yxsamliu 
> [here](https://reviews.llvm.org/D109496#3101839) showed problems with some 
> important libraries used in GPU applications, and we ended up reverting it.
> 
> In order to implement this as a DR and avoid breaking reasonable code that 
> worked before P0522, this patch implements a provisional resolution for 
> CWG2398: When deducing template template parameters against each other, and 
> the argument side names a template specialization, instead of just deducing 
> A, we deduce a synthesized template template parameter based on A, but with 
> it's parameters using the template specialization's arguments as defaults.
> 
> This does not fix all possible regressions introduced by P0522, but it does 
> seem to match in effect an undocumented workaround implemented by GCC. Though 
> it's unconfirmed how closely we match, as I have not received official word 
> regarding this yet. Fixing other regressions will require more extensive 
> changes, some of them would require possibly controversial wording changes, 
> and so is left for future work.
> 
> The driver flag is deprecated with a warning, and it will not have any effect.
> 
> @yxsamliu Can you confirm this version avoids any breakages in your setup?
> 
> CC: @yuanfang-chen @MaskRay @chandlerc @jicama @lichray @AaronBallman

I confirm this version avoids breakages in rocThrust which were reported 
before. Thanks.

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


[clang] [llvm] [mlir] Fix mismatches between function parameter definitions and declarations (PR #89512)

2024-04-25 Thread Troy Butler via cfe-commits

Troy-Butler wrote:

> @Troy-Butler I started to do the merge, but I cancelled it for now because it 
> seems that github mangles the email metadata: 
> ![image](https://private-user-images.githubusercontent.com/43410265/325606235-d783c97f-f5f7-469f-9f77-9689275ea429.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MTQwNDk5ODMsIm5iZiI6MTcxNDA0OTY4MywicGF0aCI6Ii80MzQxMDI2NS8zMjU2MDYyMzUtZDc4M2M5N2YtZjVmNy00NjlmLTlmNzctOTY4OTI3NWVhNDI5LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA0MjUlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNDI1VDEyNTQ0M1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTI4Zjk0YmRlNzhmM2U3YzhkMzdjOTYwMzRlNTkzNzFjNWFjMDY4NzNlNTU4MTQxOTIzMDBjMDNmNjk2NTRhMDEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.zJuB-MK7hKiN7DwagaI-3SEWA5q5MoVMJYY88Ss4ckU)
>  (Note that I obscured your email address in this screenshot, but it can be 
> found within the commits that you published.)
> 
> * I'd guess that want to use your "real" email address as the Author of this 
> commit -- that case you probably need to change your github account settings. 
> (I don't know the exact details but IIRC you can toggle whether it will use 
> your email address in your commits.) Ping me when you're ready and I'll check 
> the merge again.
> * If you don't want to embed that email address into the LLVM git history, 
> then I can merge the commit without the `Signed-off-by` and `Co-authored-by` 
> lines that mention it. The address will remain on the internet (in this pull 
> request), but it won't be part of the LLVM main branch.

Thank you for pointing that out. I don't have any issues with that email 
address being embedded in LLVM's git history - you can  go ahead and commit. 
Thanks!

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


[clang] [clang][NFC] Reformat suspicious condition (PR #89923)

2024-04-25 Thread Troy Butler via cfe-commits

Troy-Butler wrote:

I see that the build has failed - what do I need to do to fix this?

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


[clang] [OpenCL] Put constant initializer globals into constant addrspace (PR #90048)

2024-04-25 Thread Sven van Haastregt via cfe-commits

https://github.com/svenvh created 
https://github.com/llvm/llvm-project/pull/90048

Place constant initializer globals into the constant address space. Clang 
generates such globals for e.g. larger array member initializers of classes and 
then emits copy operations from the global to the object(s).  The globals are 
never written so they ought to be in the constant address space.

>From c5e7b2d5936a7317ebc33159b4cb72bf2aa66cf9 Mon Sep 17 00:00:00 2001
From: Sven van Haastregt 
Date: Thu, 25 Apr 2024 14:10:19 +0100
Subject: [PATCH] [OpenCL] Put constant initializer globals into constant
 addrspace

Place constant initializer globals into the constant address space.
Clang generates such globals for e.g. larger array member initializers
of classes and then emits copy operations from the global to the
object(s).  The globals are never written so they ought to be in the
constant address space.
---
 clang/lib/CodeGen/CGExprAgg.cpp| 2 ++
 clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp | 5 -
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 355fec42be4489..30cde245cc837c 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -536,6 +536,8 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
 CodeGen::CodeGenModule &CGM = CGF.CGM;
 ConstantEmitter Emitter(CGF);
 LangAS AS = ArrayQTy.getAddressSpace();
+if (CGF.getLangOpts().OpenCL)
+  AS = LangAS::opencl_constant;
 if (llvm::Constant *C =
 Emitter.tryEmitForInitializer(ExprToVisit, AS, ArrayQTy)) {
   auto GV = new llvm::GlobalVariable(
diff --git a/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp 
b/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
index 18d97a989a4364..a0ed03b25535c8 100644
--- a/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
+++ b/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
@@ -5,7 +5,7 @@
 // for constructors, member functions and destructors.
 // See also atexit.cl and global_init.cl for other specific tests.
 
-// CHECK: %struct.MyType = type { i32 }
+// CHECK: %struct.MyType = type { i32, [5 x i32] }
 struct MyType {
   MyType(int i) : i(i) {}
   MyType(int i) __constant : i(i) {}
@@ -14,6 +14,7 @@ struct MyType {
   int bar() { return i + 2; }
   int bar() __constant { return i + 1; }
   int i;
+  int a[5] = {42, 43, 44, 45, 46};
 };
 
 // CHECK: @const1 ={{.*}} addrspace(2) global %struct.MyType zeroinitializer
@@ -23,6 +24,8 @@ __constant MyType const2(2);
 // CHECK: @glob ={{.*}} addrspace(1) global %struct.MyType zeroinitializer
 MyType glob(1);
 
+// CHECK: @constinit ={{.*}} addrspace(2) constant [5 x i32] [i32 42, i32 43, 
i32 44, i32 45, i32 46]
+
 // CHECK: call spir_func void @_ZNU3AS26MyTypeC1Ei(ptr addrspace(2) {{[^,]*}} 
@const1, i32 noundef 1)
 // CHECK: call spir_func void @_ZNU3AS26MyTypeC1Ei(ptr addrspace(2) {{[^,]*}} 
@const2, i32 noundef 2)
 // CHECK: call spir_func void @_ZNU3AS46MyTypeC1Ei(ptr addrspace(4) {{[^,]*}} 
addrspacecast (ptr addrspace(1) @glob to ptr addrspace(4)), i32 noundef 1)

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


[clang] [OpenCL] Put constant initializer globals into constant addrspace (PR #90048)

2024-04-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Sven van Haastregt (svenvh)


Changes

Place constant initializer globals into the constant address space. Clang 
generates such globals for e.g. larger array member initializers of classes and 
then emits copy operations from the global to the object(s).  The globals are 
never written so they ought to be in the constant address space.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGExprAgg.cpp (+2) 
- (modified) clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp (+4-1) 


``diff
diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 355fec42be4489..30cde245cc837c 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -536,6 +536,8 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
 CodeGen::CodeGenModule &CGM = CGF.CGM;
 ConstantEmitter Emitter(CGF);
 LangAS AS = ArrayQTy.getAddressSpace();
+if (CGF.getLangOpts().OpenCL)
+  AS = LangAS::opencl_constant;
 if (llvm::Constant *C =
 Emitter.tryEmitForInitializer(ExprToVisit, AS, ArrayQTy)) {
   auto GV = new llvm::GlobalVariable(
diff --git a/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp 
b/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
index 18d97a989a4364..a0ed03b25535c8 100644
--- a/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
+++ b/clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
@@ -5,7 +5,7 @@
 // for constructors, member functions and destructors.
 // See also atexit.cl and global_init.cl for other specific tests.
 
-// CHECK: %struct.MyType = type { i32 }
+// CHECK: %struct.MyType = type { i32, [5 x i32] }
 struct MyType {
   MyType(int i) : i(i) {}
   MyType(int i) __constant : i(i) {}
@@ -14,6 +14,7 @@ struct MyType {
   int bar() { return i + 2; }
   int bar() __constant { return i + 1; }
   int i;
+  int a[5] = {42, 43, 44, 45, 46};
 };
 
 // CHECK: @const1 ={{.*}} addrspace(2) global %struct.MyType zeroinitializer
@@ -23,6 +24,8 @@ __constant MyType const2(2);
 // CHECK: @glob ={{.*}} addrspace(1) global %struct.MyType zeroinitializer
 MyType glob(1);
 
+// CHECK: @constinit ={{.*}} addrspace(2) constant [5 x i32] [i32 42, i32 43, 
i32 44, i32 45, i32 46]
+
 // CHECK: call spir_func void @_ZNU3AS26MyTypeC1Ei(ptr addrspace(2) {{[^,]*}} 
@const1, i32 noundef 1)
 // CHECK: call spir_func void @_ZNU3AS26MyTypeC1Ei(ptr addrspace(2) {{[^,]*}} 
@const2, i32 noundef 2)
 // CHECK: call spir_func void @_ZNU3AS46MyTypeC1Ei(ptr addrspace(4) {{[^,]*}} 
addrspacecast (ptr addrspace(1) @glob to ptr addrspace(4)), i32 noundef 1)

``




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


[clang] [NFC] Factor out common parts of ArraySections into its own class (PR #89639)

2024-04-25 Thread Erich Keane via cfe-commits

erichkeane wrote:

I think I've got everything done you were concerned about.  Let me know if you 
see anything else!

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


[clang] [clang][NFC] Reformat suspicious condition (PR #89923)

2024-04-25 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> I see that the build has failed - what do I need to do to fix this?

That build failure looks unrelated to your changes, I think it just got caught 
in a bad state. You can try pushing no changes to the branch to kick off a new 
build just to be sure, though.

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


[clang] [Driver] Don't default to -mrelax-all for non-RISCV -O0 (PR #90013)

2024-04-25 Thread Peter Smith via cfe-commits

smithp35 wrote:

No objections from me. I would prefer there not to be a difference for assembly 
at different optimisation levels.

I can't find any evidence that this affects Arm (Thumb to be precise) assembly 
at all. For example:
```
.text
b dest// b.n 2-byte branch
b dest2  // b.w 4-byte branch
nop
dest:
nop
.space 2048
dest2:
nop
```
Regardless of what -mrelax-all is (or the llvm-mc equivalent) the first `b 
dest` is always the smaller branch.

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


[clang] [NFC] Factor out common parts of ArraySections into its own class (PR #89639)

2024-04-25 Thread Alexey Bataev via cfe-commits

https://github.com/alexey-bataev approved this pull request.

LG

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


[clang] [CMake][Release] Refactor cache file and use two stages for non-PGO builds (PR #89812)

2024-04-25 Thread Tom Stellard via cfe-commits

tstellar wrote:

I've been testing this with #89521.

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


[clang] [CMake][Release] Refactor cache file and use two stages for non-PGO builds (PR #89812)

2024-04-25 Thread Tom Stellard via cfe-commits

https://github.com/tstellar updated 
https://github.com/llvm/llvm-project/pull/89812

>From 275979816a1de8b16a6c45b5ee2ef4e73c8828ba Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Tue, 23 Apr 2024 19:29:04 +
Subject: [PATCH] [CMake][Release] Refactor cache file and use two stages for
 non-PGO builds

Completely refactor the cache file to simplify it and remove unnecessary
variables.  The main functional change here is that the non-PGO builds now
use two stages, so `ninja -C build stage2-package` can be used with both
PGO and non-PGO builds.
---
 clang/cmake/caches/Release.cmake | 134 +++
 1 file changed, 67 insertions(+), 67 deletions(-)

diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake
index bd1f688d61a7ea..c164d5497275f3 100644
--- a/clang/cmake/caches/Release.cmake
+++ b/clang/cmake/caches/Release.cmake
@@ -1,93 +1,93 @@
 # Plain options configure the first build.
 # BOOTSTRAP_* options configure the second build.
 # BOOTSTRAP_BOOTSTRAP_* options configure the third build.
+# PGO Builds have 3 stages (stage1, stage2-instrumented, stage2)
+# non-PGO Builds have 2 stages (stage1, stage2)
 
-# General Options
+
+function (set_final_stage_var name value type)
+  if (LLVM_RELEASE_ENABLE_PGO)
+set(BOOTSTRAP_BOOTSTRAP_${name} ${value} CACHE ${type} "")
+  else()
+set(BOOTSTRAP_${name} ${value} CACHE ${type} "")
+  endif()
+endfunction()
+
+function (set_instrument_and_final_stage_var name value type)
+  # This sets the varaible for the final stage in non-PGO builds and in
+  # the stage2-instrumented stage for PGO builds.
+  set(BOOTSTRAP_${name} ${value} CACHE ${type} "")
+  if (LLVM_RELEASE_ENABLE_PGO)
+# Set the variable in the final stage for PGO builds.
+set(BOOTSTRAP_BOOTSTRAP_${name} ${value} CACHE ${type} "")
+  endif()
+endfunction()
+
+# General Options:
+# If you want to override any of the LLVM_RELEASE_* variables you can set them
+# on the command line via -D, but you need to do this before you pass this
+# cache file to CMake via -C. e.g.
+#
+# cmake -D LLVM_RELEASE_ENABLE_PGO=ON -C Release.cmake
 set(LLVM_RELEASE_ENABLE_LTO THIN CACHE STRING "")
 set(LLVM_RELEASE_ENABLE_PGO OFF CACHE BOOL "")
-
+set(LLVM_RELEASE_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" 
CACHE STRING "")
+set(LLVM_RELEASE_ENABLE_PROJECTS 
"clang;lld;lldb;clang-tools-extra;bolt;polly;mlir;flang" CACHE STRING "")
+# Note we don't need to add install here, since it is one of the pre-defined
+# steps.
+set(LLVM_RELEASE_FINAL_STAGE_TARGETS 
"clang;package;check-all;check-llvm;check-clang" CACHE STRING "")
 set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 
-# Stage 1 Bootstrap Setup
+# Stage 1 Options
+set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
+
+set(STAGE1_PROJECTS "clang")
+set(STAGE1_RUNTIMES "")
+
 if (LLVM_RELEASE_ENABLE_PGO)
+  list(APPEND STAGE1_PROJECTS "lld")
+  list(APPEND STAGE1_RUNTIMES "compiler-rt")
   set(CLANG_BOOTSTRAP_TARGETS
 generate-profdata
-stage2
+stage2-package
 stage2-clang
-stage2-distribution
 stage2-install
-stage2-install-distribution
-stage2-install-distribution-toolchain
 stage2-check-all
 stage2-check-llvm
-stage2-check-clang
-stage2-test-suite CACHE STRING "")
-else()
-  set(CLANG_BOOTSTRAP_TARGETS
-clang
-check-all
-check-llvm
-check-clang
-test-suite
-stage3
-stage3-clang
-stage3-check-all
-stage3-check-llvm
-stage3-check-clang
-stage3-install
-stage3-test-suite CACHE STRING "")
-endif()
+stage2-check-clang CACHE STRING "")
 
-# Stage 1 Options
-set(STAGE1_PROJECTS "clang")
-set(STAGE1_RUNTIMES "")
+  # Configuration for stage2-instrumented
+  set(BOOTSTRAP_CLANG_ENABLE_BOOTSTRAP ON CACHE STRING "")
+  # This enables the build targets for the final stage which is called stage2.
+  set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS ${LLVM_RELEASE_FINAL_STAGE_TARGETS} 
CACHE STRING "")
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED IR CACHE STRING "")
+  set(BOOTSTRAP_LLVM_ENABLE_RUNTIMES "compiler-rt" CACHE STRING "")
+  set(BOOTSTRAP_LLVM_ENABLE_PROJECTS "clang;lld" CACHE STRING "")
 
-if (LLVM_RELEASE_ENABLE_PGO)
-  list(APPEND STAGE1_PROJECTS "lld")
-  list(APPEND STAGE1_RUNTIMES "compiler-rt")
+else()
+  if (LLVM_RELEASE_ENABLE_LTO)
+list(APPEND STAGE1_PROJECTS "lld")
+  endif()
+  # Any targets added here will be given the target name stage2-${target}, so
+  # if you want to run them you can just use:
+  # ninja -C $BUILDDIR stage2-${target}
+  set(CLANG_BOOTSTRAP_TARGETS ${LLVM_RELEASE_FINAL_STAGE_TARGETS} CACHE STRING 
"")
 endif()
 
+# Stage 1 Common Config
 set(LLVM_ENABLE_RUNTIMES ${STAGE1_RUNTIMES} CACHE STRING "")
 set(LLVM_ENABLE_PROJECTS ${STAGE1_PROJECTS} CACHE STRING "")
 
-set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
-
-# Stage 2 Bootstrap Setup
-set(BOOTSTRAP_CLANG_ENABLE_BOOTSTRAP ON CACHE STRING "")
-set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS
-  cl

[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -std=c++26 -fsyntax-only -verify %s
+
+auto&& f1() {
+  return 42; // expected-error{{returning reference to local temporary object}}
+}
+const double& f2() {
+  static int x = 42;
+  return x; // expected-error{{returning reference to local temporary object}}
+}
+auto&& id(auto&& r) {
+  return static_cast(r);
+}
+auto&& f3() {
+  return id(42);// OK, but probably a bug
+}
+
+static_assert(__is_convertible(int, const int &));
+static_assert(__is_nothrow_convertible(int, const int &));

yronglin wrote:

Agree to keep these 2 lines and I'll add more test in type-traits.cpp

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread via cfe-commits

yronglin wrote:

> DR changes look good. @erichkeane mind giving CWG650 test a quick look?

Thanks for your review!

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread via cfe-commits


@@ -8340,8 +8340,17 @@ void Sema::checkInitializerLifetime(const 
InitializedEntity &Entity,
 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 
2
 << DiagRange;
   } else {
-Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
- << Entity.getType()->isReferenceType() << DiagRange;
+// P2748R5: Disallow Binding a Returned Glvalue to a Temporary.
+// [stmt.return]/p6: In a function whose return type is a reference,
+// other than an invented function for std::is_convertible 
([meta.rel]),
+// a return statement that binds the returned reference to a temporary
+// expression ([class.temporary]) is ill-formed.

yronglin wrote:

Great, this example makes things much more clearer! 

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


[clang] [Clang][Sema] fix a bug on template partial specialization (PR #89862)

2024-04-25 Thread Erich Keane via cfe-commits

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


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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread Erich Keane via cfe-commits

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread Erich Keane via cfe-commits

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

1 Nit, else LGTM, the CWG issue change seems sensible, as does the rest.

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


[clang] [Clang] Implement C++26 P2748R5 "Disallow Binding a Returned Glvalue to a Temporary" (PR #89942)

2024-04-25 Thread Erich Keane via cfe-commits


@@ -9950,6 +9950,8 @@ def warn_ret_stack_addr_ref : Warning<
 def warn_ret_local_temp_addr_ref : Warning<
   "returning %select{address of|reference to}0 local temporary object">,
   InGroup;
+def err_ret_local_temp_addr_ref : Error<
+  "returning %select{address of|reference to}0 local temporary object">;

erichkeane wrote:

```suggestion
  warn_ret_local_temp_addr_ref.Text>;
```

(or something like that?  Either way, the messages are intentionally the same, 
would be nice to just share the text).

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


[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-25 Thread Erich Keane via cfe-commits

erichkeane wrote:

> > Thank you working on this. I'm really like this feature! I've a question, 
> > do we have any further plans to support GNU extension attributes(e.g. 
> > **attribute**((aligned)))? Although it is not included in the paper.
> 
> No, sorry!
> 
> My goal here is to increase conformance, not to invent new extensions. If 
> someone wants to do that work, they would have to motivate the change, do the 
> design leg work and synchronize with GCC. More generally, supporting GNU 
> syntax in relatively new, C++ specific constructs is probably of limited use. 
> If there were attributes useful in structured binding that don't yet have a 
> `[[]]` spelling, we should probably would want to fix that instead.

Agreed 100%.

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


[clang] [flang] [lld] [flang] Generate main only when a Fortran program statement is present (PR #89938)

2024-04-25 Thread Kelvin Li via cfe-commits

kkwli wrote:

This change will also break backward compatibility that the old object file 
that contain `main` can no longer use the new compiler to link with other 
objects. I think we can put a warning in the release note or something like 
that to warn users.

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


[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-25 Thread Erich Keane via cfe-commits


@@ -102,11 +102,21 @@ namespace PR33839 {
 for (auto [x] : a) { // expected-warning {{unused variable '[x]'}}
 }
   }
-  void use() { 
+  void use() {
 f(); // expected-note {{instantiation of}}
 g();
 g();
 h(); // expected-note {{instantiation of}}
   }
 }
+
+namespace maybe_unused_binding {
+
+void test() {
+  struct X { int a, b; } x;
+  auto [a [[maybe_unused]], b] = x; // expected-warning {{an attribute 
specifier sequence attached to a structured binding declaration is a C++2c 
extension}}

erichkeane wrote:

Are there any standard attributes other than this that make sense on SB's?  If 
not, I'd like all of the standards ones tested to show what the behavior is 
(and 'not valid here' type errors are totally acceptable).

`[[indeterminate]]` seems useful, but  the rest should likely result in a 
rejection.

Additionally, we should do an audit of ALL our "C++" spelling attributes to see 
which make sense here and to make sure they are treated reasonably.  I'm not 
asking to do that HERE, but a bug in our bug tracker (perhaps with a 'good 
starter bug' tag, particularly if we list ALL our attributes that need 
auditing) would be acceptable.

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


[clang-tools-extra] [clang-tidy] Enable C23 support in modernize-use-nullptr (PR #89990)

2024-04-25 Thread via cfe-commits


@@ -269,6 +269,10 @@ Changes in existing checks
   don't remove parentheses used in ``sizeof`` calls when they have array index
   accesses as arguments.
 
+- Improved :doc:`modernize-use-nullptr
+  ` check to include support for
+  ``C23``, which also has introduced the ``nullptr`` keyword.

EugeneZelenko wrote:

```suggestion
  C23, which also has introduced the ``nullptr`` keyword.
```

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+bool isApplicable(const QualType &Type) {
+  const auto TypeStr = Type.getAsString();
+  bool Result = false;
+  // Only check for containers in the std namespace
+  if (TypeStr.find("std::vector") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::array") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::deque") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::unordered_map") != std::string::npos) {
+Result = true;
+  }
+  if (TypeStr.find("std::flat_map") != std::string::npos) {
+Result = true;
+  }
+  // TODO Add std::span with C++26
+  return Result;
+}
+
+void AvoidBoundsErrorsCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(callee(cxxMethodDecl(hasName("operator[]")).bind("f")))
+  .bind("x"),
+  this);
+}
+
+void AvoidBoundsErrorsCheck::check(const MatchFinder::MatchResult &Result) {
+  const ASTContext &Context = *Result.Context;
+  const SourceManager &Source = Context.getSourceManager();
+  const auto *MatchedExpr = Result.Nodes.getNodeAs("x");
+  const auto *MatchedFunction = Result.Nodes.getNodeAs("f");
+  const auto Type = MatchedFunction->getThisType();

EugeneZelenko wrote:

Please do not use `auto` - type is not spelled explicitly.

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+

EugeneZelenko wrote:

Excessive newline.

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;

EugeneZelenko wrote:

Please separate with newline.

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,32 @@
+//===--- AvoidBoundsErrorsCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_AVOIDBOUNDSERRORSCHECK_H
+#define 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_AVOIDBOUNDSERRORSCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::cppcoreguidelines {
+
+/// Enforce CPP core guidelines SL.con.3
+///
+/// See
+/// 
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#slcon3-avoid-bounds-errors
+/// For the user-facing documentation see:
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/avoid-bounds-errors.html
+class AvoidBoundsErrorsCheck : public ClangTidyCheck {
+public:
+  AvoidBoundsErrorsCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};

EugeneZelenko wrote:

Please add `isLanguageVersionSupported`.

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,81 @@
+//===--- AvoidBoundsErrorsCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "AvoidBoundsErrorsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+#include 
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+bool isApplicable(const QualType &Type) {

EugeneZelenko wrote:

`static`?

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -131,6 +131,11 @@ New checks
   to reading out-of-bounds data due to inadequate or incorrect string null
   termination.
 
+- New :doc:`cppcoreguidelines-avoid-bounds-errors
+  ` check.
+
+  Flags the unsafe `operator[]` and replaces it with `at()`.

EugeneZelenko wrote:

Please use double back-ticks for language constructs. Same in documentation.

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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() (PR #90043)

2024-04-25 Thread via cfe-commits


@@ -0,0 +1,20 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-bounds-errors
+
+cppcoreguidelines-avoid-bounds-errors
+=
+
+This check enforces the `SL.con.3 
`
 guideline.

EugeneZelenko wrote:

This usually placed at the end of documentation.

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


[clang] [clang-tools-extra] [libcxx] [C++17] Support __GCC_[CON|DE]STRUCTIVE_SIZE (PR #89446)

2024-04-25 Thread Louis Dionne via cfe-commits

ldionne wrote:

> > I'd rather keep the libc++ tests green while landing this PR. I tried 
> > something out, let's see if that works.
> 
> It looks like some further adjustments may be needed as some stage1 builders 
> are failing:
> 
> ```
> [...]
> ```

Ah, yes, we're using the nightly clang which is labeled as clang-19 but doesn't 
contain the change yet. I'll mark the test as `UNSUPPORTED` on all Clang 
flavors for now (which is how the test should have been marked), and we will 
fix that in the patch that implements the library feature.


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


[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-25 Thread via cfe-commits


@@ -102,11 +102,21 @@ namespace PR33839 {
 for (auto [x] : a) { // expected-warning {{unused variable '[x]'}}
 }
   }
-  void use() { 
+  void use() {
 f(); // expected-note {{instantiation of}}
 g();
 g();
 h(); // expected-note {{instantiation of}}
   }
 }
+
+namespace maybe_unused_binding {
+
+void test() {
+  struct X { int a, b; } x;
+  auto [a [[maybe_unused]], b] = x; // expected-warning {{an attribute 
specifier sequence attached to a structured binding declaration is a C++2c 
extension}}

yronglin wrote:

Should we add a test to check the `[[maybe_unused]]` takes effect. 
e.g. checks whether there has `warning: unused variable '[a, b]' 
[-Wunused-variable]`.

I've a question about this test case. We only add `[[maybe_unused]]` to `a` , 
IIUC, should we also emit a warning that `unused variable 'b'`?

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan created 
https://github.com/llvm/llvm-project/pull/90064

Certain C++ types, such as `std::chrono::tzdb` in libstdc++, are non-copyable, 
but don't explicitly delete their copy constructor. Instead, they trigger 
template instantiation errors when trying to call their implicit copy 
constructor. The Swift compiler inserts implicit copies of value types in some 
cases, which trigger compiler errors for such types.

This adds a Clang API Notes attribute that allows annotating C++ types as 
non-copyable in Swift. This lets the Swift compiler know that it should not try 
to instantiate the implicit copy constructor for a C++ struct.

rdar://127049438

>From a3ea8c954f3446330314f4b5d1ea42d87761b1c4 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Thu, 25 Apr 2024 15:19:09 +0100
Subject: [PATCH] [APINotes] Allow annotating a C++ type as non-copyable in
 Swift

Certain C++ types, such as `std::chrono::tzdb` in libstdc++, are non-copyable, 
but don't explicitly delete their copy constructor. Instead, they trigger 
template instantiation errors when trying to call their implicit copy 
constructor. The Swift compiler inserts implicit copies of value types in some 
cases, which trigger compiler errors for such types.

This adds a Clang API Notes attribute that allows annotating C++ types as 
non-copyable in Swift. This lets the Swift compiler know that it should not try 
to instantiate the implicit copy constructor for a C++ struct.

rdar://127049438
---
 clang/include/clang/APINotes/Types.h  | 22 ++-
 clang/lib/APINotes/APINotesReader.cpp |  7 ++
 clang/lib/APINotes/APINotesWriter.cpp |  8 ++-
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   |  5 +
 clang/lib/Sema/SemaAPINotes.cpp   |  5 +
 .../Inputs/Headers/SwiftImportAs.apinotes |  4 
 .../APINotes/Inputs/Headers/SwiftImportAs.h   |  3 +++
 clang/test/APINotes/swift-import-as.cpp   | 10 +
 8 files changed, 62 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index 93bb045d6a6670..026a4a431e7349 100644
--- a/clang/include/clang/APINotes/Types.h
+++ b/clang/include/clang/APINotes/Types.h
@@ -675,6 +675,11 @@ class TagInfo : public CommonTypeInfo {
   LLVM_PREFERRED_TYPE(bool)
   unsigned IsFlagEnum : 1;
 
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyableSpecified : 1;
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyable : 1;
+
 public:
   std::optional SwiftImportAs;
   std::optional SwiftRetainOp;
@@ -682,7 +687,9 @@ class TagInfo : public CommonTypeInfo {
 
   std::optional EnumExtensibility;
 
-  TagInfo() : HasFlagEnum(0), IsFlagEnum(0) {}
+  TagInfo()
+  : HasFlagEnum(0), IsFlagEnum(0), SwiftCopyableSpecified(false),
+SwiftCopyable(false) {}
 
   std::optional isFlagEnum() const {
 if (HasFlagEnum)
@@ -694,6 +701,15 @@ class TagInfo : public CommonTypeInfo {
 IsFlagEnum = Value.value_or(false);
   }
 
+  std::optional isSwiftCopyable() const {
+return SwiftCopyableSpecified ? std::optional(SwiftCopyable)
+  : std::nullopt;
+  }
+  void setSwiftCopyable(std::optional Value) {
+SwiftCopyableSpecified = Value.has_value();
+SwiftCopyable = Value.value_or(false);
+  }
+
   TagInfo &operator|=(const TagInfo &RHS) {
 static_cast(*this) |= RHS;
 
@@ -710,6 +726,9 @@ class TagInfo : public CommonTypeInfo {
 if (!EnumExtensibility)
   EnumExtensibility = RHS.EnumExtensibility;
 
+if (!SwiftCopyableSpecified)
+  setSwiftCopyable(RHS.isSwiftCopyable());
+
 return *this;
   }
 
@@ -724,6 +743,7 @@ inline bool operator==(const TagInfo &LHS, const TagInfo 
&RHS) {
  LHS.SwiftRetainOp == RHS.SwiftRetainOp &&
  LHS.SwiftReleaseOp == RHS.SwiftReleaseOp &&
  LHS.isFlagEnum() == RHS.isFlagEnum() &&
+ LHS.isSwiftCopyable() == RHS.isSwiftCopyable() &&
  LHS.EnumExtensibility == RHS.EnumExtensibility;
 }
 
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index dfc3beb6fa13ee..7eaab36a85d00b 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -527,6 +527,13 @@ class TagTableInfo
   Info.EnumExtensibility =
   static_cast((Payload & 0x3) - 1);
 
+uint8_t Copyable =
+endian::readNext(Data);
+if (Copyable == 1)
+  Info.setSwiftCopyable(std::optional(false));
+else if (Copyable == 2)
+  Info.setSwiftCopyable(std::optional(true));
+
 unsigned ImportAsLength =
 endian::readNext(Data);
 if (ImportAsLength > 0) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index e3f5d102fcd07f..c9584ff8345d2f 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -1128,7 +1128,7 @@ class TagTableInfo : public 
CommonTypeTableInfo {
 return 2 + (TI.SwiftImpo

[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 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 697fcd009855a579f756dfe34498a815ed9dc3fd 
a3ea8c954f3446330314f4b5d1ea42d87761b1c4 -- 
clang/include/clang/APINotes/Types.h clang/lib/APINotes/APINotesReader.cpp 
clang/lib/APINotes/APINotesWriter.cpp 
clang/lib/APINotes/APINotesYAMLCompiler.cpp clang/lib/Sema/SemaAPINotes.cpp 
clang/test/APINotes/Inputs/Headers/SwiftImportAs.h 
clang/test/APINotes/swift-import-as.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index c9584ff834..e18108a757 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -1125,10 +1125,10 @@ public:
 class TagTableInfo : public CommonTypeTableInfo {
 public:
   unsigned getUnversionedInfoSize(const TagInfo &TI) {
-return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) +
-   2 + (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) +
-   2 + (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) +
-   2 + getCommonTypeInfoSize(TI);
+return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) + 2 +
+   (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) + 2 +
+   (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) + 2 +
+   getCommonTypeInfoSize(TI);
   }
 
   void emitUnversionedInfo(raw_ostream &OS, const TagInfo &TI) {

``




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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/90064

>From 9eac3a34aa9c48e1ddc715ca04c4380f1d78a876 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Thu, 25 Apr 2024 15:19:09 +0100
Subject: [PATCH] [APINotes] Allow annotating a C++ type as non-copyable in
 Swift

Certain C++ types, such as `std::chrono::tzdb` in libstdc++, are non-copyable, 
but don't explicitly delete their copy constructor. Instead, they trigger 
template instantiation errors when trying to call their implicit copy 
constructor. The Swift compiler inserts implicit copies of value types in some 
cases, which trigger compiler errors for such types.

This adds a Clang API Notes attribute that allows annotating C++ types as 
non-copyable in Swift. This lets the Swift compiler know that it should not try 
to instantiate the implicit copy constructor for a C++ struct.

rdar://127049438
---
 clang/include/clang/APINotes/Types.h  | 22 ++-
 clang/lib/APINotes/APINotesReader.cpp |  7 ++
 clang/lib/APINotes/APINotesWriter.cpp | 14 
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   |  5 +
 clang/lib/Sema/SemaAPINotes.cpp   |  5 +
 .../Inputs/Headers/SwiftImportAs.apinotes |  4 
 .../APINotes/Inputs/Headers/SwiftImportAs.h   |  3 +++
 clang/test/APINotes/swift-import-as.cpp   | 10 +
 8 files changed, 65 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index 93bb045d6a6670..026a4a431e7349 100644
--- a/clang/include/clang/APINotes/Types.h
+++ b/clang/include/clang/APINotes/Types.h
@@ -675,6 +675,11 @@ class TagInfo : public CommonTypeInfo {
   LLVM_PREFERRED_TYPE(bool)
   unsigned IsFlagEnum : 1;
 
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyableSpecified : 1;
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyable : 1;
+
 public:
   std::optional SwiftImportAs;
   std::optional SwiftRetainOp;
@@ -682,7 +687,9 @@ class TagInfo : public CommonTypeInfo {
 
   std::optional EnumExtensibility;
 
-  TagInfo() : HasFlagEnum(0), IsFlagEnum(0) {}
+  TagInfo()
+  : HasFlagEnum(0), IsFlagEnum(0), SwiftCopyableSpecified(false),
+SwiftCopyable(false) {}
 
   std::optional isFlagEnum() const {
 if (HasFlagEnum)
@@ -694,6 +701,15 @@ class TagInfo : public CommonTypeInfo {
 IsFlagEnum = Value.value_or(false);
   }
 
+  std::optional isSwiftCopyable() const {
+return SwiftCopyableSpecified ? std::optional(SwiftCopyable)
+  : std::nullopt;
+  }
+  void setSwiftCopyable(std::optional Value) {
+SwiftCopyableSpecified = Value.has_value();
+SwiftCopyable = Value.value_or(false);
+  }
+
   TagInfo &operator|=(const TagInfo &RHS) {
 static_cast(*this) |= RHS;
 
@@ -710,6 +726,9 @@ class TagInfo : public CommonTypeInfo {
 if (!EnumExtensibility)
   EnumExtensibility = RHS.EnumExtensibility;
 
+if (!SwiftCopyableSpecified)
+  setSwiftCopyable(RHS.isSwiftCopyable());
+
 return *this;
   }
 
@@ -724,6 +743,7 @@ inline bool operator==(const TagInfo &LHS, const TagInfo 
&RHS) {
  LHS.SwiftRetainOp == RHS.SwiftRetainOp &&
  LHS.SwiftReleaseOp == RHS.SwiftReleaseOp &&
  LHS.isFlagEnum() == RHS.isFlagEnum() &&
+ LHS.isSwiftCopyable() == RHS.isSwiftCopyable() &&
  LHS.EnumExtensibility == RHS.EnumExtensibility;
 }
 
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index dfc3beb6fa13ee..7eaab36a85d00b 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -527,6 +527,13 @@ class TagTableInfo
   Info.EnumExtensibility =
   static_cast((Payload & 0x3) - 1);
 
+uint8_t Copyable =
+endian::readNext(Data);
+if (Copyable == 1)
+  Info.setSwiftCopyable(std::optional(false));
+else if (Copyable == 2)
+  Info.setSwiftCopyable(std::optional(true));
+
 unsigned ImportAsLength =
 endian::readNext(Data);
 if (ImportAsLength > 0) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index e3f5d102fcd07f..e18108a7573eae 100644
--- a/clang/lib/APINotes/APINotesWriter.cpp
+++ b/clang/lib/APINotes/APINotesWriter.cpp
@@ -1125,10 +1125,10 @@ class CommonTypeTableInfo
 class TagTableInfo : public CommonTypeTableInfo {
 public:
   unsigned getUnversionedInfoSize(const TagInfo &TI) {
-return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) +
-   2 + (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) +
-   2 + (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) +
-   1 + getCommonTypeInfoSize(TI);
+return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) + 2 +
+   (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) + 2 +
+   (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) + 2 +
+   getCommonTypeInfoSize(TI);
   }
 
   void emitUnversionedI

[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Saleem Abdulrasool via cfe-commits

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Saleem Abdulrasool via cfe-commits


@@ -527,6 +527,13 @@ class TagTableInfo
   Info.EnumExtensibility =
   static_cast((Payload & 0x3) - 1);
 
+uint8_t Copyable =
+endian::readNext(Data);
+if (Copyable == 1)
+  Info.setSwiftCopyable(std::optional(false));
+else if (Copyable == 2)
+  Info.setSwiftCopyable(std::optional(true));

compnerd wrote:

Can we use named constants for the non-traditional boolean values? Perhaps 
`kSwiftNonCopyable` and `kSwiftCopyable`? This should ensure that we do not 
drift.

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Saleem Abdulrasool via cfe-commits


@@ -1125,10 +1125,10 @@ class CommonTypeTableInfo
 class TagTableInfo : public CommonTypeTableInfo {
 public:
   unsigned getUnversionedInfoSize(const TagInfo &TI) {
-return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) +
-   2 + (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) +
-   2 + (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) +
-   1 + getCommonTypeInfoSize(TI);
+return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) + 2 +
+   (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) + 2 +
+   (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) + 2 +
+   getCommonTypeInfoSize(TI);

compnerd wrote:

This feels less readable :(

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Saleem Abdulrasool via cfe-commits

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


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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Saleem Abdulrasool via cfe-commits


@@ -1146,6 +1146,12 @@ class TagTableInfo : public 
CommonTypeTableInfo {
 
 writer.write(Flags);
 
+if (auto Copyable = TI.isSwiftCopyable()) {

compnerd wrote:

Unnecessary braces and we should be able to use the named constants here.

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


[clang] 39ed3c6 - [clang-scan-deps] Fix contention when updating `TrackingStatistic`s in hot code paths in `FileManager`. (#88427)

2024-04-25 Thread via cfe-commits

Author: Alexandre Ganea
Date: 2024-04-25T10:31:45-04:00
New Revision: 39ed3c68e51f1b04fe2890db9006ae1b176b1582

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

LOG: [clang-scan-deps] Fix contention when updating `TrackingStatistic`s in hot 
code paths in `FileManager`. (#88427)

`FileManager::getDirectoryRef()` and `FileManager::getFileRef()` are hot code 
paths in `clang-scan-deps`. These functions are updating on every call a few 
atomics related to printing statistics, which causes contention on high core 
count machines.

![Screenshot 2024-04-10
214123](https://github.com/llvm/llvm-project/assets/37383324/5756b1bc-cab5-4612-8769-ee7e03a66479)

![Screenshot 2024-04-10
214246](https://github.com/llvm/llvm-project/assets/37383324/3d560e89-61c7-4fb9-9330-f9e660e8fc8b)

![Screenshot 2024-04-10
214315](https://github.com/llvm/llvm-project/assets/37383324/006341fc-49d4-4720-a348-7af435c21b17)

After this patch we make the variables local to the `FileManager`.

In our test case, this saves about 49 sec over 1 min 47 sec of 
`clang-scan-deps` run time (1 min 47 sec before, 58 sec after). These figures 
are after applying my suggestion in 
https://github.com/llvm/llvm-project/pull/88152#issuecomment-2049803229, that 
is:
```
static bool shouldCacheStatFailures(StringRef Filename) {
  return true;
}
```
Without the above, there's just too much OS noise from the high volume of 
`status()` calls with regular non-modules C++ code. Tested on Windows with 
clang-cl.

Added: 


Modified: 
clang/include/clang/Basic/FileManager.h
clang/lib/Basic/FileManager.cpp
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/FileManager.h 
b/clang/include/clang/Basic/FileManager.h
index 2245fd78bfc9f0..8b4206e52cd482 100644
--- a/clang/include/clang/Basic/FileManager.h
+++ b/clang/include/clang/Basic/FileManager.h
@@ -114,6 +114,12 @@ class FileManager : public RefCountedBase {
   ///
   unsigned NextFileUID;
 
+  /// Statistics gathered during the lifetime of the FileManager.
+  unsigned NumDirLookups = 0;
+  unsigned NumFileLookups = 0;
+  unsigned NumDirCacheMisses = 0;
+  unsigned NumFileCacheMisses = 0;
+
   // Caching.
   std::unique_ptr StatCache;
 
@@ -341,6 +347,10 @@ class FileManager : public RefCountedBase {
 
 public:
   void PrintStats() const;
+
+  /// Import statistics from a child FileManager and add them to this current
+  /// FileManager.
+  void AddStats(const FileManager &Other);
 };
 
 } // end namespace clang

diff  --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp
index cd520a6375e07e..143c04309d0753 100644
--- a/clang/lib/Basic/FileManager.cpp
+++ b/clang/lib/Basic/FileManager.cpp
@@ -39,12 +39,6 @@ using namespace clang;
 
 #define DEBUG_TYPE "file-search"
 
-ALWAYS_ENABLED_STATISTIC(NumDirLookups, "Number of directory lookups.");
-ALWAYS_ENABLED_STATISTIC(NumFileLookups, "Number of file lookups.");
-ALWAYS_ENABLED_STATISTIC(NumDirCacheMisses,
- "Number of directory cache misses.");
-ALWAYS_ENABLED_STATISTIC(NumFileCacheMisses, "Number of file cache misses.");
-
 
//===--===//
 // Common logic.
 
//===--===//
@@ -656,6 +650,14 @@ StringRef FileManager::getCanonicalName(const void *Entry, 
StringRef Name) {
   return CanonicalName;
 }
 
+void FileManager::AddStats(const FileManager &Other) {
+  assert(&Other != this && "Collecting stats into the same FileManager");
+  NumDirLookups += Other.NumDirLookups;
+  NumFileLookups += Other.NumFileLookups;
+  NumDirCacheMisses += Other.NumDirCacheMisses;
+  NumFileCacheMisses += Other.NumFileCacheMisses;
+}
+
 void FileManager::PrintStats() const {
   llvm::errs() << "\n*** File Manager Stats:\n";
   llvm::errs() << UniqueRealFiles.size() << " real files found, "

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 6e3baf83864415..66a45b888f15cc 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1293,6 +1293,10 @@ compileModuleImpl(CompilerInstance &ImportingInstance, 
SourceLocation ImportLoc,
 diag::remark_module_build_done)
 << ModuleName;
 
+  // Propagate the statistics to the parent FileManager.
+  if (!FrontendOpts.ModulesShareFileManager)
+ImportingInstance.getFileManager().AddStats(Instance.getFileManager());
+
   if (Crashed) {
 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
 // that must be closed before clearing output files.

diff  --git 

[clang] [clang-scan-deps] Fix contention when updating `TrackingStatistic`s in hot code paths in `FileManager`. (PR #88427)

2024-04-25 Thread Alexandre Ganea via cfe-commits

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


[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-25 Thread via cfe-commits


@@ -102,11 +102,21 @@ namespace PR33839 {
 for (auto [x] : a) { // expected-warning {{unused variable '[x]'}}
 }
   }
-  void use() { 
+  void use() {
 f(); // expected-note {{instantiation of}}
 g();
 g();
 h(); // expected-note {{instantiation of}}
   }
 }
+
+namespace maybe_unused_binding {
+
+void test() {
+  struct X { int a, b; } x;
+  auto [a [[maybe_unused]], b] = x; // expected-warning {{an attribute 
specifier sequence attached to a structured binding declaration is a C++2c 
extension}}

cor3ntin wrote:

This is that test.
By marking one of the member unused, we don't warn on any of the member.
This perhaps not perfect but the standard already specified that if one of the 
member is used, we should not warn on any of the biding

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Egor Zhdan via cfe-commits


@@ -1125,10 +1125,10 @@ class CommonTypeTableInfo
 class TagTableInfo : public CommonTypeTableInfo {
 public:
   unsigned getUnversionedInfoSize(const TagInfo &TI) {
-return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) +
-   2 + (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) +
-   2 + (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) +
-   1 + getCommonTypeInfoSize(TI);
+return 2 + (TI.SwiftImportAs ? TI.SwiftImportAs->size() : 0) + 2 +
+   (TI.SwiftRetainOp ? TI.SwiftRetainOp->size() : 0) + 2 +
+   (TI.SwiftReleaseOp ? TI.SwiftReleaseOp->size() : 0) + 2 +
+   getCommonTypeInfoSize(TI);

egorzhdan wrote:

Yeah, it's unfortunate that clang-format is overly strict about this. I can 
revert this and try to merge despite clang-format complaining, if you think 
that's better.

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


[clang] [Clang] Implement C++26 Attributes for Structured Bindings (P0609R3) (PR #89906)

2024-04-25 Thread via cfe-commits


@@ -102,11 +102,21 @@ namespace PR33839 {
 for (auto [x] : a) { // expected-warning {{unused variable '[x]'}}
 }
   }
-  void use() { 
+  void use() {
 f(); // expected-note {{instantiation of}}
 g();
 g();
 h(); // expected-note {{instantiation of}}
   }
 }
+
+namespace maybe_unused_binding {
+
+void test() {
+  struct X { int a, b; } x;
+  auto [a [[maybe_unused]], b] = x; // expected-warning {{an attribute 
specifier sequence attached to a structured binding declaration is a C++2c 
extension}}

cor3ntin wrote:

> Are there any standard attributes other than this that make sense on SB's? If 
> not, I'd like all of the standards ones tested to show what the behavior is 
> (and 'not valid here' type errors are totally acceptable).

No, I can add tests

> 
> `[[indeterminate]]` seems useful, but the rest should likely result in a 
> rejection.

We do not have this one
> 
> Additionally, we should do an audit of ALL our "C++" spelling attributes to 
> see which make sense here and to make sure they are treated reasonably. I'm 
> not asking to do that HERE, but a bug in our bug tracker (perhaps with a 
> 'good starter bug' tag, particularly if we list ALL our attributes that need 
> auditing) would be acceptable.

Yes, I can create an issue once we land that

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


[clang] [APINotes] Allow annotating a C++ type as non-copyable in Swift (PR #90064)

2024-04-25 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/90064

>From f0394cfaf4df3881809fdce7882bda3006951805 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Thu, 25 Apr 2024 15:19:09 +0100
Subject: [PATCH] [APINotes] Allow annotating a C++ type as non-copyable in
 Swift

Certain C++ types, such as `std::chrono::tzdb` in libstdc++, are non-copyable, 
but don't explicitly delete their copy constructor. Instead, they trigger 
template instantiation errors when trying to call their implicit copy 
constructor. The Swift compiler inserts implicit copies of value types in some 
cases, which trigger compiler errors for such types.

This adds a Clang API Notes attribute that allows annotating C++ types as 
non-copyable in Swift. This lets the Swift compiler know that it should not try 
to instantiate the implicit copy constructor for a C++ struct.

rdar://127049438
---
 clang/include/clang/APINotes/Types.h  | 22 ++-
 clang/lib/APINotes/APINotesFormat.h   |  5 -
 clang/lib/APINotes/APINotesReader.cpp |  7 ++
 clang/lib/APINotes/APINotesWriter.cpp | 13 +++
 clang/lib/APINotes/APINotesYAMLCompiler.cpp   |  5 +
 clang/lib/Sema/SemaAPINotes.cpp   |  5 +
 .../Inputs/Headers/SwiftImportAs.apinotes |  4 
 .../APINotes/Inputs/Headers/SwiftImportAs.h   |  3 +++
 clang/test/APINotes/swift-import-as.cpp   | 10 +
 9 files changed, 68 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index 93bb045d6a6670..026a4a431e7349 100644
--- a/clang/include/clang/APINotes/Types.h
+++ b/clang/include/clang/APINotes/Types.h
@@ -675,6 +675,11 @@ class TagInfo : public CommonTypeInfo {
   LLVM_PREFERRED_TYPE(bool)
   unsigned IsFlagEnum : 1;
 
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyableSpecified : 1;
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned SwiftCopyable : 1;
+
 public:
   std::optional SwiftImportAs;
   std::optional SwiftRetainOp;
@@ -682,7 +687,9 @@ class TagInfo : public CommonTypeInfo {
 
   std::optional EnumExtensibility;
 
-  TagInfo() : HasFlagEnum(0), IsFlagEnum(0) {}
+  TagInfo()
+  : HasFlagEnum(0), IsFlagEnum(0), SwiftCopyableSpecified(false),
+SwiftCopyable(false) {}
 
   std::optional isFlagEnum() const {
 if (HasFlagEnum)
@@ -694,6 +701,15 @@ class TagInfo : public CommonTypeInfo {
 IsFlagEnum = Value.value_or(false);
   }
 
+  std::optional isSwiftCopyable() const {
+return SwiftCopyableSpecified ? std::optional(SwiftCopyable)
+  : std::nullopt;
+  }
+  void setSwiftCopyable(std::optional Value) {
+SwiftCopyableSpecified = Value.has_value();
+SwiftCopyable = Value.value_or(false);
+  }
+
   TagInfo &operator|=(const TagInfo &RHS) {
 static_cast(*this) |= RHS;
 
@@ -710,6 +726,9 @@ class TagInfo : public CommonTypeInfo {
 if (!EnumExtensibility)
   EnumExtensibility = RHS.EnumExtensibility;
 
+if (!SwiftCopyableSpecified)
+  setSwiftCopyable(RHS.isSwiftCopyable());
+
 return *this;
   }
 
@@ -724,6 +743,7 @@ inline bool operator==(const TagInfo &LHS, const TagInfo 
&RHS) {
  LHS.SwiftRetainOp == RHS.SwiftRetainOp &&
  LHS.SwiftReleaseOp == RHS.SwiftReleaseOp &&
  LHS.isFlagEnum() == RHS.isFlagEnum() &&
+ LHS.isSwiftCopyable() == RHS.isSwiftCopyable() &&
  LHS.EnumExtensibility == RHS.EnumExtensibility;
 }
 
diff --git a/clang/lib/APINotes/APINotesFormat.h 
b/clang/lib/APINotes/APINotesFormat.h
index 615314c46f09ca..97e630e97fdcc2 100644
--- a/clang/lib/APINotes/APINotesFormat.h
+++ b/clang/lib/APINotes/APINotesFormat.h
@@ -24,7 +24,10 @@ const uint16_t VERSION_MAJOR = 0;
 /// API notes file minor version number.
 ///
 /// When the format changes IN ANY WAY, this number should be incremented.
-const uint16_t VERSION_MINOR = 25; // SwiftImportAs
+const uint16_t VERSION_MINOR = 26; // SwiftCopyable
+
+const uint8_t kSwiftCopyable = 1;
+const uint8_t kSwiftNonCopyable = 2;
 
 using IdentifierID = llvm::PointerEmbeddedInt;
 using IdentifierIDField = llvm::BCVBR<16>;
diff --git a/clang/lib/APINotes/APINotesReader.cpp 
b/clang/lib/APINotes/APINotesReader.cpp
index dfc3beb6fa13ee..b60ca685f62c98 100644
--- a/clang/lib/APINotes/APINotesReader.cpp
+++ b/clang/lib/APINotes/APINotesReader.cpp
@@ -527,6 +527,13 @@ class TagTableInfo
   Info.EnumExtensibility =
   static_cast((Payload & 0x3) - 1);
 
+uint8_t Copyable =
+endian::readNext(Data);
+if (Copyable == kSwiftNonCopyable)
+  Info.setSwiftCopyable(std::optional(false));
+else if (Copyable == kSwiftCopyable)
+  Info.setSwiftCopyable(std::optional(true));
+
 unsigned ImportAsLength =
 endian::readNext(Data);
 if (ImportAsLength > 0) {
diff --git a/clang/lib/APINotes/APINotesWriter.cpp 
b/clang/lib/APINotes/APINotesWriter.cpp
index e3f5d102fcd07f..6bd96c0b813cf7 100644
--- a/clang/lib/APINotes/APINo

  1   2   3   4   >