[clang] [llvm] [InstCombine] Infer nusw + nneg -> nuw for getelementptr (PR #111144)

2024-10-05 Thread Yingwei Zheng via cfe-commits


@@ -3096,6 +3096,15 @@ Instruction 
*InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
 }
   }
 
+  // nusw + nneg -> nuw
+  if (GEP.hasNoUnsignedSignedWrap() && !GEP.hasNoUnsignedWrap() &&
+  all_of(GEP.indices(), [&](Value *Idx) {
+return isKnownNonNegative(Idx, SQ.getWithInstruction(&GEP));
+  })) {
+GEP.setNoWrapFlags(GEP.getNoWrapFlags() | 
GEPNoWrapFlags::noUnsignedWrap());

dtcxzyw wrote:

Should drop duplicate logic in other places:
```
SelectionDAGBuilder::visitGetElementPtr
InstCombinerImpl::visitPtrToInt
llvm/lib/Transforms/Scalar/LICM.cpp:hoistGEP
SeparateConstOffsetFromGEP::reorderGEP
```


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


[clang-tools-extra] [clang-tidy] Avoid capturing a local variable in a static lambda in UseRangesCheck (PR #111282)

2024-10-05 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/111282

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

>From d7ec29dc8852c4ae8b239daff11acc42caf4d544 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 6 Oct 2024 01:45:35 -0400
Subject: [PATCH] [clang-tidy] Avoid capturing a local variable in a static
 lambda in UseRangesCheck

Fixes https://github.com/llvm/llvm-project/issues/109367
---
 .../clang-tidy/boost/UseRangesCheck.cpp| 18 +-
 .../clangd/unittests/ClangdLSPServerTests.cpp  | 16 
 2 files changed, 25 insertions(+), 9 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
index 4022ea0cdaf5ee..e45687fde6d9f6 100644
--- a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
@@ -204,7 +204,7 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
   ReplacerMap Results;
   static const Signature SingleSig = {{0}};
   static const Signature TwoSig = {{0}, {2}};
-  static const auto AddFrom =
+  const auto AddFrom =
   [&Results](llvm::IntrusiveRefCntPtr Replacer,
  std::initializer_list Names, StringRef Prefix) {
 llvm::SmallString<64> Buffer;
@@ -214,17 +214,17 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
 }
   };
 
-  static const auto AddFromStd =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list Names) {
+  const auto AddFromStd =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list Names) {
 AddFrom(Replacer, Names, "std");
   };
 
-  static const auto AddFromBoost =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list<
- std::pair>>
- NamespaceAndNames) {
+  const auto AddFromBoost =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list<
+  std::pair>>
+  NamespaceAndNames) {
 for (auto [Namespace, Names] : NamespaceAndNames)
   AddFrom(Replacer, Names,
   SmallString<64>{"boost", (Namespace.empty() ? "" : "::"),
diff --git a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp 
b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
index 75a140767035b2..49a94045ea4878 100644
--- a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
@@ -262,6 +262,22 @@ TEST_F(LSPTest, ClangTidyRename) {
   EXPECT_EQ(Params, std::vector{llvm::json::Value(std::move(ExpectedEdit))});
 }
 
+TEST_F(LSPTest, ClangTidyCrash_Issue109367) {
+  // This test requires clang-tidy checks to be linked in.
+  if (!CLANGD_TIDY_CHECKS)
+return;
+  Opts.ClangTidyProvider = [](tidy::ClangTidyOptions &ClangTidyOpts,
+  llvm::StringRef) {
+ClangTidyOpts.Checks = {"-*,boost-use-ranges"};
+  };
+  // Check that registering the boost-use-ranges checker's matchers
+  // on two different threads does not cause a crash.
+  auto &Client = start();
+  Client.didOpen("a.cpp", "");
+  Client.didOpen("b.cpp", "");
+  Client.sync();
+}
+
 TEST_F(LSPTest, IncomingCalls) {
   Annotations Code(R"cpp(
 void calle^e(int);

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


[clang-tools-extra] [clang-tidy] Avoid capturing a local variable in a static lambda in UseRangesCheck (PR #111282)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Nathan Ridge (HighCommander4)


Changes

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

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp (+9-9) 
- (modified) clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp (+16) 


``diff
diff --git a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
index 4022ea0cdaf5ee..e45687fde6d9f6 100644
--- a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
@@ -204,7 +204,7 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
   ReplacerMap Results;
   static const Signature SingleSig = {{0}};
   static const Signature TwoSig = {{0}, {2}};
-  static const auto AddFrom =
+  const auto AddFrom =
   [&Results](llvm::IntrusiveRefCntPtr Replacer,
  std::initializer_list Names, StringRef Prefix) {
 llvm::SmallString<64> Buffer;
@@ -214,17 +214,17 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
 }
   };
 
-  static const auto AddFromStd =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list Names) {
+  const auto AddFromStd =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list Names) {
 AddFrom(Replacer, Names, "std");
   };
 
-  static const auto AddFromBoost =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list<
- std::pair>>
- NamespaceAndNames) {
+  const auto AddFromBoost =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list<
+  std::pair>>
+  NamespaceAndNames) {
 for (auto [Namespace, Names] : NamespaceAndNames)
   AddFrom(Replacer, Names,
   SmallString<64>{"boost", (Namespace.empty() ? "" : "::"),
diff --git a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp 
b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
index 75a140767035b2..49a94045ea4878 100644
--- a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
@@ -262,6 +262,22 @@ TEST_F(LSPTest, ClangTidyRename) {
   EXPECT_EQ(Params, std::vector{llvm::json::Value(std::move(ExpectedEdit))});
 }
 
+TEST_F(LSPTest, ClangTidyCrash_Issue109367) {
+  // This test requires clang-tidy checks to be linked in.
+  if (!CLANGD_TIDY_CHECKS)
+return;
+  Opts.ClangTidyProvider = [](tidy::ClangTidyOptions &ClangTidyOpts,
+  llvm::StringRef) {
+ClangTidyOpts.Checks = {"-*,boost-use-ranges"};
+  };
+  // Check that registering the boost-use-ranges checker's matchers
+  // on two different threads does not cause a crash.
+  auto &Client = start();
+  Client.didOpen("a.cpp", "");
+  Client.didOpen("b.cpp", "");
+  Client.sync();
+}
+
 TEST_F(LSPTest, IncomingCalls) {
   Annotations Code(R"cpp(
 void calle^e(int);

``




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


[clang-tools-extra] [clang-tidy] Avoid capturing a local variable in a static lambda in UseRangesCheck (PR #111282)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Nathan Ridge (HighCommander4)


Changes

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

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp (+9-9) 
- (modified) clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp (+16) 


``diff
diff --git a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp 
b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
index 4022ea0cdaf5ee..e45687fde6d9f6 100644
--- a/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp
@@ -204,7 +204,7 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
   ReplacerMap Results;
   static const Signature SingleSig = {{0}};
   static const Signature TwoSig = {{0}, {2}};
-  static const auto AddFrom =
+  const auto AddFrom =
   [&Results](llvm::IntrusiveRefCntPtr Replacer,
  std::initializer_list Names, StringRef Prefix) {
 llvm::SmallString<64> Buffer;
@@ -214,17 +214,17 @@ utils::UseRangesCheck::ReplacerMap 
UseRangesCheck::getReplacerMap() const {
 }
   };
 
-  static const auto AddFromStd =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list Names) {
+  const auto AddFromStd =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list Names) {
 AddFrom(Replacer, Names, "std");
   };
 
-  static const auto AddFromBoost =
-  [](llvm::IntrusiveRefCntPtr Replacer,
- std::initializer_list<
- std::pair>>
- NamespaceAndNames) {
+  const auto AddFromBoost =
+  [&](llvm::IntrusiveRefCntPtr Replacer,
+  std::initializer_list<
+  std::pair>>
+  NamespaceAndNames) {
 for (auto [Namespace, Names] : NamespaceAndNames)
   AddFrom(Replacer, Names,
   SmallString<64>{"boost", (Namespace.empty() ? "" : "::"),
diff --git a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp 
b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
index 75a140767035b2..49a94045ea4878 100644
--- a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
@@ -262,6 +262,22 @@ TEST_F(LSPTest, ClangTidyRename) {
   EXPECT_EQ(Params, std::vector{llvm::json::Value(std::move(ExpectedEdit))});
 }
 
+TEST_F(LSPTest, ClangTidyCrash_Issue109367) {
+  // This test requires clang-tidy checks to be linked in.
+  if (!CLANGD_TIDY_CHECKS)
+return;
+  Opts.ClangTidyProvider = [](tidy::ClangTidyOptions &ClangTidyOpts,
+  llvm::StringRef) {
+ClangTidyOpts.Checks = {"-*,boost-use-ranges"};
+  };
+  // Check that registering the boost-use-ranges checker's matchers
+  // on two different threads does not cause a crash.
+  auto &Client = start();
+  Client.didOpen("a.cpp", "");
+  Client.didOpen("b.cpp", "");
+  Client.sync();
+}
+
 TEST_F(LSPTest, IncomingCalls) {
   Annotations Code(R"cpp(
 void calle^e(int);

``




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


[clang-tools-extra] Add checks to convert std library iterator algorithms into c++20 or boost ranges (PR #97764)

2024-10-05 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> It crashes most likely because a local variable is captured in the static 
> lambda.
> 
> https://github.com/llvm/llvm-project/blob/bf895c714e1f8a51c1e565a75acf60bf7197be51/clang-tools-extra/clang-tidy/boost/UseRangesCheck.cpp#L208

Nice find! That does seem to be the problem. I've put up a fix at 
https://github.com/llvm/llvm-project/pull/111282.

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Younan Zhang via cfe-commits


@@ -4206,18 +4206,14 @@ Sema::InstantiateClassMembers(SourceLocation 
PointOfInstantiation,
 if (Function->hasAttr())
   continue;
 
-MemberSpecializationInfo *MSInfo =
-Function->getMemberSpecializationInfo();
-assert(MSInfo && "No member specialization information?");
-if (MSInfo->getTemplateSpecializationKind()
- == TSK_ExplicitSpecialization)
+TemplateSpecializationKind PrevTSK =
+Function->getTemplateSpecializationKind();
+if (PrevTSK == TSK_ExplicitSpecialization)
   continue;

zyn0217 wrote:

Yeah, I thought the bug was that somewhere we failed to handle 
`DependentFunctionTemplateSpecializationInfo`s, but after stepping into the 
codes, I realized that it is due to the latest TSK stored in 
`FunctionTemplateSpecializationInfo` rather than in the MSInfo. (We didn't 
update the TSK in MSInfo in CheckFunctionTemplateSpecialization)

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


[clang] [Clang] Remove the special-casing for RequiresExprBodyDecl in BuildResolvedCallExpr() after fd87d765c0 (PR #111277)

2024-10-05 Thread Younan Zhang via cfe-commits

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


[clang] [Clang] Remove the special-casing for RequiresExprBodyDecl in BuildResolvedCallExpr() after fd87d765c0 (PR #111277)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

The special-casing for RequiresExprBodyDecl caused a regression, as reported in 
#110785.

This also merged the test for #84020 together with that of #110785 into clang/test/SemaTemplate/instantiate-requires-expr.cpp.

No release note because I think this merits a backport.

Fixes #110785

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


4 Files Affected:

- (modified) clang/lib/Sema/SemaExpr.cpp (+1-2) 
- (modified) clang/lib/Sema/TreeTransform.h (+1-1) 
- (removed) clang/test/SemaCXX/PR84020.cpp (-23) 
- (modified) clang/test/SemaTemplate/instantiate-requires-expr.cpp (+31) 


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ae7bcedfb28c73..959f0739f03fb9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6963,8 +6963,7 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, 
NamedDecl *NDecl,
   }
 
   if (CXXMethodDecl *Method = dyn_cast_or_null(FDecl))
-if (!isa(CurContext) &&
-Method->isImplicitObjectMemberFunction())
+if (Method->isImplicitObjectMemberFunction())
   return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
<< Fn->getSourceRange() << 0);
 
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 76efc9fe831854..ed9412c93c62b3 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13907,7 +13907,7 @@ bool 
TreeTransform::TransformOverloadExprDecls(OverloadExpr *Old,
 }
 
 AllEmptyPacks &= Decls.empty();
-  };
+  }
 
   // C++ [temp.res]/8.4.2:
   //   The program is ill-formed, no diagnostic required, if [...] lookup for
diff --git a/clang/test/SemaCXX/PR84020.cpp b/clang/test/SemaCXX/PR84020.cpp
deleted file mode 100644
index 8ea5dcc4527ae7..00
--- a/clang/test/SemaCXX/PR84020.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-// RUN: %clang_cc1 -std=c++20 -verify %s
-// RUN: %clang_cc1 -std=c++23 -verify %s
-// expected-no-diagnostics
-
-struct B {
-template 
-void foo();
-
-void bar();
-};
-
-template 
-struct A : T {
-auto foo() {
-static_assert(requires { T::template foo(); });
-static_assert(requires { T::bar(); });
-}
-};
-
-int main() {
-A a;
-a.foo();
-}
diff --git a/clang/test/SemaTemplate/instantiate-requires-expr.cpp 
b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
index 20a19d731ae169..a1f5456156a06f 100644
--- a/clang/test/SemaTemplate/instantiate-requires-expr.cpp
+++ b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
@@ -237,3 +237,34 @@ constexpr bool e_v = true;
 static_assert(e_v);
 
 } // namespace GH73885
+
+namespace GH84020 {
+
+struct B {
+  template  void foo();
+  void bar();
+};
+
+template  struct A : T {
+  void foo() {
+static_assert(requires { T::template foo(); });
+static_assert(requires { T::bar(); });
+  }
+};
+
+template class A;
+
+} // namespace GH84020
+
+namespace GH110785 {
+
+struct Foo {
+  static void f(auto) requires(false) {}
+  void f(int) {}
+
+  static_assert([](auto v) {
+return requires { f(v); };
+  } (0) == false);
+};
+
+} // namespace GH110785

``




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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Matheus Izvekov via cfe-commits

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

>From e6d3e6f1df5db1618c7302adac4b45b7aa451a34 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 28 Sep 2024 14:28:58 -0300
Subject: [PATCH] [clang] Track function template instantiation from definition

This fixes instantiation of definition for fend function templates,
when the declaration found and the one containing the definition
have different template contexts.

In these cases, the the function declaration corresponding to the
definition is not available; it may not even be instantiated at all.

So this patch adds a bit which tracks which function template was
instantiated from the definition. It's used to find which primary
template serves as a context for the purpose of obtainining the
template arguments needed to instantiate the definition.

Fixes #55509
---
 clang/docs/ReleaseNotes.rst   |   1 +
 clang/include/clang/AST/Decl.h|   7 ++
 clang/include/clang/AST/DeclBase.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h|   7 ++
 clang/lib/AST/Decl.cpp|   1 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  17 +--
 clang/lib/Sema/SemaTemplateInstantiate.cpp|   9 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  28 -
 clang/lib/Serialization/ASTReaderDecl.cpp |   1 +
 clang/lib/Serialization/ASTWriterDecl.cpp |   3 +-
 clang/test/SemaTemplate/GH55509.cpp   | 101 ++
 11 files changed, 156 insertions(+), 29 deletions(-)
 create mode 100644 clang/test/SemaTemplate/GH55509.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 44d5f348ed2d54..552c9f524a7ae6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -468,6 +468,7 @@ Bug Fixes to C++ Support
 - Fixed an assertion failure in debug mode, and potential crashes in release 
mode, when
   diagnosing a failed cast caused indirectly by a failed implicit conversion 
to the type of the constructor parameter.
 - Fixed an assertion failure by adjusting integral to boolean vector 
conversions (#GH108326)
+- Clang is now better at keeping track of friend function template instance 
contexts. (#GH55509)
 - Fixed an issue deducing non-type template arguments of reference type. 
(#GH73460)
 - Fixed an issue in constraint evaluation, where type constraints on the 
lambda expression
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 7ff35d73df5997..35784ad1690775 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -2299,6 +2299,13 @@ class FunctionDecl : public DeclaratorDecl,
 FunctionDeclBits.IsLateTemplateParsed = ILT;
   }
 
+  bool isInstantiatedFromDefinition() const {
+return FunctionDeclBits.IsInstantiatedFromDefinition;
+  }
+  void setInstantiatedFromDefinition(bool Val = true) {
+FunctionDeclBits.IsInstantiatedFromDefinition = Val;
+  }
+
   /// Whether this function is "trivial" in some specialized C++ senses.
   /// Can only be true for default constructors, copy constructors,
   /// copy assignment operators, and destructors.  Not meaningful until
diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index ee662ed73d7e0e..6efd516b7d83a1 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -1763,6 +1763,8 @@ class DeclContext {
 uint64_t HasImplicitReturnZero : 1;
 LLVM_PREFERRED_TYPE(bool)
 uint64_t IsLateTemplateParsed : 1;
+LLVM_PREFERRED_TYPE(bool)
+uint64_t IsInstantiatedFromDefinition : 1;
 
 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
 LLVM_PREFERRED_TYPE(ConstexprSpecKind)
@@ -1813,7 +1815,7 @@ class DeclContext {
   };
 
   /// Number of inherited and non-inherited bits in FunctionDeclBitfields.
-  enum { NumFunctionDeclBits = NumDeclContextBits + 31 };
+  enum { NumFunctionDeclBits = NumDeclContextBits + 32 };
 
   /// Stores the bits used by CXXConstructorDecl. If modified
   /// NumCXXConstructorDeclBits and the accessor
@@ -1824,12 +1826,12 @@ class DeclContext {
 LLVM_PREFERRED_TYPE(FunctionDeclBitfields)
 uint64_t : NumFunctionDeclBits;
 
-/// 20 bits to fit in the remaining available space.
+/// 19 bits to fit in the remaining available space.
 /// Note that this makes CXXConstructorDeclBitfields take
 /// exactly 64 bits and thus the width of NumCtorInitializers
 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
-uint64_t NumCtorInitializers : 17;
+uint64_t NumCtorInitializers : 16;
 LLVM_PREFERRED_TYPE(bool)
 uint64_t IsInheritingConstructor : 1;
 
@@ -1843,7 +1845,7 @@ class DeclContext {
   };
 
   /// Number of inherited and non-inherited bits in 
CXXConstruct

[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Younan Zhang via cfe-commits


@@ -1994,8 +1995,10 @@ 
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   // Link the instantiation back to the pattern *unless* this is a
   // non-definition friend declaration.
   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
-  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
+  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) {
+InstTemplate->setInstantiatedFromDefinition();

zyn0217 wrote:

> That's true, but the only problematic cases are the friends.

I was thinking if we can move it to a separate if branch then, for example it 
might not be conditioned on `isFriend`

```cpp
if (D->getTemplatedDecl()->isThisDeclarationADefinition())
  InstTemplate->setInstantiatedFromDefinition();
```

(I presume a new if won't impact anything other than friends, as you said the 
friends are the only problematic ones.)

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Younan Zhang via cfe-commits

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


[clang] [Clang] prevent recovery call expression from proceeding with explicit attributes and undeclared templates (PR #107786)

2024-10-05 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/107786

>From e9948a1004cc2b486a0422d83e88392754e9f7e9 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Mon, 23 Sep 2024 17:17:30 +0300
Subject: [PATCH 1/2] [Clang] prevent recovery call expression from proceeding
 with explicit attributes and undeclared templates

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/Sema/Sema.h   |  4 ++-
 clang/lib/Sema/SemaExpr.cpp   | 12 +--
 clang/lib/Sema/SemaOverload.cpp   |  2 +-
 .../SemaTemplate/recovery-crash-cxx20.cpp | 32 +++
 5 files changed, 48 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/SemaTemplate/recovery-crash-cxx20.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b47e06cb0c5d68..110f75d739c072 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -424,6 +424,8 @@ Bug Fixes to C++ Support
 - Fixed an assertion failure in debug mode, and potential crashes in release 
mode, when
   diagnosing a failed cast caused indirectly by a failed implicit conversion 
to the type of the constructor parameter.
 - Fixed an assertion failure by adjusting integral to boolean vector 
conversions (#GH108326)
+- Fixed an assertion failure when invoking recovery call expressions with 
explicit attributes
+  and undeclared templates. (#GH107047, #GH49093)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e1c3a99cfa167e..b2eefdbd1c56d1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6753,7 +6753,9 @@ class Sema final : public SemaBase {
   ///
   /// Return \c true if the error is unrecoverable, or \c false if the caller
   /// should attempt to recover using these lookup results.
-  bool DiagnoseDependentMemberLookup(const LookupResult &R);
+  bool DiagnoseDependentMemberLookup(
+  const LookupResult &R,
+  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
 
   /// Diagnose an empty lookup.
   ///
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 66df9c969256a2..a5770ae8848517 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -2385,7 +2385,15 @@ static void emitEmptyLookupTypoDiagnostic(
  SemaRef.PDiag(NoteID));
 }
 
-bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
+bool Sema::DiagnoseDependentMemberLookup(
+const LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs) {
+  auto IsTemplated = [](NamedDecl *D) { return D->isTemplated(); };
+  if (ExplicitTemplateArgs && !llvm::all_of(R, IsTemplated)) {
+Diag(R.getNameLoc(), diag::err_non_template_in_template_id)
+<< R.getLookupName();
+return true;
+  }
+
   // During a default argument instantiation the CurContext points
   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
   // function parameter list, hence add an explicit check.
@@ -2487,7 +2495,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec 
&SS, LookupResult &R,
   R.resolveKind();
 }
 
-return DiagnoseDependentMemberLookup(R);
+return DiagnoseDependentMemberLookup(R, ExplicitTemplateArgs);
   }
 
   R.clear();
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d304f322aced64..fe9b16e1890c16 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13860,7 +13860,7 @@ BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
 // enclosing class.
 // FIXME: We should also explain why the candidates found by name lookup
 // were not viable.
-if (SemaRef.DiagnoseDependentMemberLookup(R))
+if (SemaRef.DiagnoseDependentMemberLookup(R, ExplicitTemplateArgs))
   return ExprError();
   } else {
 // We had viable candidates and couldn't recover; let the caller diagnose
diff --git a/clang/test/SemaTemplate/recovery-crash-cxx20.cpp 
b/clang/test/SemaTemplate/recovery-crash-cxx20.cpp
new file mode 100644
index 00..3651b986dfd989
--- /dev/null
+++ b/clang/test/SemaTemplate/recovery-crash-cxx20.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+
+namespace GH49093 {
+  class B {
+  public:
+static int a() { return 0; }
+decltype(a< 0 >(0)) test; // expected-error {{'a' does not name a template 
but is followed by template arguments}}
+  };
+
+  struct C {
+  static int a() { return 0; }
+  decltype(a < 0 > (0)) test; // expected-error {{'a' does not name a 
template but is followed by template arguments}}
+  };
+
+  void test_is_bool(bool t) {}
+  void test_is_bool(int t) {}
+
+  int main() {
+B b;
+test_is_bool(b.test);
+
+C c;
+test_is_bool(c.test);
+  }
+}
+
+namespace GH107047 {
+  struct A {
+static constexpr auto test() { return 1; }
+   

[clang-tools-extra] [clang-tidy] Make `P +- BS / sizeof(*P)` opt-outable in `bugprone-sizeof-expression` (PR #111178)

2024-10-05 Thread Nicolas van Kempen via cfe-commits

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

LGTM, nits. Maybe give a bit of time for others to take a look.

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


[clang-tools-extra] [clang-tidy] Make `P +- BS / sizeof(*P)` opt-outable in `bugprone-sizeof-expression` (PR #111178)

2024-10-05 Thread Nicolas van Kempen via cfe-commits


@@ -0,0 +1,12 @@
+// RUN: %check_clang_tidy %s bugprone-sizeof-expression %t -- \
+// RUN:   -config="{CheckOptions: [{key: 
bugprone-sizeof-expression.WarnOnSizeOfPointerArithmeticWithDivisionScaled, 
value: 0}]}"

nicovank wrote:

```suggestion
// RUN: %check_clang_tidy %s bugprone-sizeof-expression %t -- \
// RUN:   -config="{CheckOptions: \
// RUN: 
{bugprone-sizeof-expression.WarnOnSizeOfPointerArithmeticWithDivisionScaled: \
// RUN:false}}"
```

I didn't even know this `[{key: ..., value: ...}, ...]` notation existed, TIL.

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


[clang-tools-extra] [clang-tidy] Make `P +- BS / sizeof(*P)` opt-outable in `bugprone-sizeof-expression` (PR #111178)

2024-10-05 Thread Nicolas van Kempen via cfe-commits

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


[clang-tools-extra] [clang-tidy] Make `P +- BS / sizeof(*P)` opt-outable in `bugprone-sizeof-expression` (PR #111178)

2024-10-05 Thread Nicolas van Kempen via cfe-commits


@@ -306,8 +310,13 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
  unaryExprOrTypeTraitExpr(ofKind(UETT_AlignOf)),
  offsetOfExpr()))
   .bind("sizeof-in-ptr-arithmetic-scale-expr");
+  const auto PtrArithmeticIntegerScaleExprInterestingOperatorNames = [this] {
+if (WarnOnSizeOfPointerArithmeticWithDivisionScaled)
+  return binaryOperator(hasAnyOperatorName("*", "/"));
+return binaryOperator(hasOperatorName("*"));
+  };

nicovank wrote:

```suggestion
  const auto HasSoughtIntegerScaleExprOperatorName =
  WarnOnSizeOfPointerArithmeticWithDivisionScaled
  ? binaryOperator(hasAnyOperatorName("*", "/"))
  : binaryOperator(hasOperatorName("*"));
```

Ternary should be OK, and I find name a little long but nit.

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


[clang-tools-extra] [clang-tidy] Make `P +- BS / sizeof(*P)` opt-outable in `bugprone-sizeof-expression` (PR #111178)

2024-10-05 Thread Nicolas van Kempen via cfe-commits


@@ -31,6 +31,7 @@ class SizeofExpressionCheck : public ClangTidyCheck {
   const bool WarnOnSizeOfCompareToConstant;
   const bool WarnOnSizeOfPointerToAggregate;
   const bool WarnOnSizeOfPointer;
+  const bool WarnOnSizeOfPointerArithmeticWithDivisionScaled;

nicovank wrote:

I find this a little long. `WarnOnArithmeticWithDivisionBySizeOf` maybe?

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


[clang] [clang] CWG2398: improve overload resolution backwards compat (PR #107350)

2024-10-05 Thread Matheus Izvekov via cfe-commits

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

>From 9b12c0b5a0b701984a83308273385c53ced29e41 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 5 Sep 2024 00:25:40 -0300
Subject: [PATCH] [clang] CWG2398: improve overload resolution backwards compat

With this change, we discriminate if the primary template and which partial
specializations would have participated in overload resolution prior to
P0522 changes.

We collect those in an initial set. If this set is not empty, or the
primary template would have matched, we proceed with this set as the
candidates for overload resolution.

Otherwise, we build a new overload set with everything else, and proceed
as usual.
---
 clang/docs/ReleaseNotes.rst  |  3 +-
 clang/include/clang/Sema/Sema.h  | 14 ---
 clang/include/clang/Sema/TemplateDeduction.h | 13 ++
 clang/lib/Sema/SemaLookup.cpp|  3 +-
 clang/lib/Sema/SemaTemplate.cpp  | 44 
 clang/lib/Sema/SemaTemplateDeduction.cpp | 43 +--
 clang/lib/Sema/SemaTemplateInstantiate.cpp   | 24 ++-
 clang/test/SemaTemplate/cwg2398.cpp  |  6 +--
 8 files changed, 97 insertions(+), 53 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 44d5f348ed2d54..48784f2adcf38b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,7 +204,8 @@ Resolutions to C++ Defect Reports
   (`CWG2351: void{} `_).
 
 - Clang now has improved resolution to CWG2398, allowing class templates to 
have
-  default arguments deduced when partial ordering.
+  default arguments deduced when partial ordering, and better backwards 
compatibility
+  in overload resolution.
 
 - Clang now allows comparing unequal object pointers that have been cast to 
``void *``
   in constant expressions. These comparisons always worked in non-constant 
expressions.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index bede971ce0191b..5d38862ce59f0c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11636,7 +11636,8 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK);
+CheckTemplateArgumentKind CTAK,
+bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
   /// the given template, converting the arguments along the way.
@@ -11683,7 +11684,8 @@ class Sema final : public SemaBase {
   SmallVectorImpl &SugaredConverted,
   SmallVectorImpl &CanonicalConverted,
   bool UpdateArgsWithConversions = true,
-  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = 
false);
+  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = false,
+  bool *MatchedPackOnParmToNonPackOnArg = nullptr);
 
   bool CheckTemplateTypeArgument(
   TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
@@ -11717,7 +11719,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced);
+ TemplateArgumentLoc &Arg, bool IsDeduced,
+ bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplateLocation(const NamedDecl &Decl,
 std::optional ParamRange = {});
@@ -12418,7 +12421,7 @@ class Sema final : public SemaBase {
   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
   TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
   const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
-  bool IsDeduced);
+  bool IsDeduced, bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Mark which template parameters are used in a given expression.
   ///
@@ -13417,7 +13420,8 @@ class Sema final : public SemaBase {
   bool InstantiateClassTemplateSpecialization(
   SourceLocation PointOfInstantiation,
   ClassTemplateSpecializationDecl *ClassTemplateSpec,
-  TemplateSpecializationKind TSK, bool Complain = true);
+  TemplateSpecializationKind TSK, bool Complain = true,
+  bool PrimaryHasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Instantiates the definitions of all of the member
   /// of the given class, which is an instantiation of a class template
diff --git a/clang/include/clang/Sema/TemplateDeduction.h 
b/clang/include/clang/Sema/TemplateDeduction.h
index 28b0

[clang] [ByteCode] Avoid repeated hash lookups (NFC) (PR #111273)

2024-10-05 Thread Kazu Hirata via cfe-commits

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

None

>From 48c833ccac40522a563f6c1610eef409628a45d9 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 5 Oct 2024 10:22:58 -0700
Subject: [PATCH] [ByteCode] Avoid repeated hash lookups (NFC)

---
 clang/lib/AST/ByteCode/Program.cpp | 12 +---
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Program.cpp 
b/clang/lib/AST/ByteCode/Program.cpp
index 969f523db51dfe..23245a66b578ae 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -284,15 +284,13 @@ Record *Program::getOrCreateRecord(const RecordDecl *RD) {
   if (!RD->isCompleteDefinition())
 return nullptr;
 
-  // Deduplicate records.
-  if (auto It = Records.find(RD); It != Records.end())
+  // Return an existing record if available.  Otherwise, we insert nullptr now
+  // and replace that later, so recursive calls to this function with the same
+  // RecordDecl don't run into infinite recursion.
+  auto [It, Inserted] = Records.try_emplace(RD);
+  if (!Inserted)
 return It->second;
 
-  // We insert nullptr now and replace that later, so recursive calls
-  // to this function with the same RecordDecl don't run into
-  // infinite recursion.
-  Records.insert({RD, nullptr});
-
   // Number of bytes required by fields and base classes.
   unsigned BaseSize = 0;
   // Number of bytes required by virtual base.

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


[clang] [Clang] Remove the special-casing for RequiresExprBodyDecl in BuildResolvedCallExpr() after fd87d765c0 (PR #111277)

2024-10-05 Thread Younan Zhang via cfe-commits

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

>From 995603864598bcb826db8477406ee5f17bbe0548 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 6 Oct 2024 12:46:21 +0800
Subject: [PATCH] [Clang] Remove the special-casing for RequiresExprBodyDecl in
 BuildResolvedCallExpr() after fd87d765c0

---
 clang/lib/Sema/SemaExpr.cpp   |  3 +-
 clang/lib/Sema/TreeTransform.h|  2 +-
 clang/test/SemaCXX/PR84020.cpp| 23 --
 .../instantiate-requires-expr.cpp | 31 +++
 4 files changed, 33 insertions(+), 26 deletions(-)
 delete mode 100644 clang/test/SemaCXX/PR84020.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ae7bcedfb28c73..959f0739f03fb9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6963,8 +6963,7 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, 
NamedDecl *NDecl,
   }
 
   if (CXXMethodDecl *Method = dyn_cast_or_null(FDecl))
-if (!isa(CurContext) &&
-Method->isImplicitObjectMemberFunction())
+if (Method->isImplicitObjectMemberFunction())
   return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
<< Fn->getSourceRange() << 0);
 
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 76efc9fe831854..ed9412c93c62b3 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13907,7 +13907,7 @@ bool 
TreeTransform::TransformOverloadExprDecls(OverloadExpr *Old,
 }
 
 AllEmptyPacks &= Decls.empty();
-  };
+  }
 
   // C++ [temp.res]/8.4.2:
   //   The program is ill-formed, no diagnostic required, if [...] lookup for
diff --git a/clang/test/SemaCXX/PR84020.cpp b/clang/test/SemaCXX/PR84020.cpp
deleted file mode 100644
index 8ea5dcc4527ae7..00
--- a/clang/test/SemaCXX/PR84020.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-// RUN: %clang_cc1 -std=c++20 -verify %s
-// RUN: %clang_cc1 -std=c++23 -verify %s
-// expected-no-diagnostics
-
-struct B {
-template 
-void foo();
-
-void bar();
-};
-
-template 
-struct A : T {
-auto foo() {
-static_assert(requires { T::template foo(); });
-static_assert(requires { T::bar(); });
-}
-};
-
-int main() {
-A a;
-a.foo();
-}
diff --git a/clang/test/SemaTemplate/instantiate-requires-expr.cpp 
b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
index 20a19d731ae169..a1f5456156a06f 100644
--- a/clang/test/SemaTemplate/instantiate-requires-expr.cpp
+++ b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
@@ -237,3 +237,34 @@ constexpr bool e_v = true;
 static_assert(e_v);
 
 } // namespace GH73885
+
+namespace GH84020 {
+
+struct B {
+  template  void foo();
+  void bar();
+};
+
+template  struct A : T {
+  void foo() {
+static_assert(requires { T::template foo(); });
+static_assert(requires { T::bar(); });
+  }
+};
+
+template class A;
+
+} // namespace GH84020
+
+namespace GH110785 {
+
+struct Foo {
+  static void f(auto) requires(false) {}
+  void f(int) {}
+
+  static_assert([](auto v) {
+return requires { f(v); };
+  } (0) == false);
+};
+
+} // namespace GH110785

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


[clang] [llvm] Adding splitdouble HLSL function (PR #109331)

2024-10-05 Thread Farzon Lotfi via cfe-commits

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


[clang] [Clang] Remove the special-casing for RequiresExprBodyDecl in BuildResolvedCallExpr() after fd87d765c0 (PR #111277)

2024-10-05 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/111277

The special-casing for RequiresExprBodyDecl caused a regression, as reported in 
#110785.

This also merged the test for #84020 together with that of #110785 into 
clang/test/SemaTemplate/instantiate-requires-expr.cpp.

No release note because I think this merits a backport.

Fixes #110785

>From d48512e86a4ac1b7c1e3afc706fbdbbc8905b425 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 6 Oct 2024 12:46:21 +0800
Subject: [PATCH] [Clang] Remove the special-casing for RequiresExprBodyDecl in
 BuildResolvedCallExpr() after fd87d765c0

---
 clang/lib/Sema/SemaExpr.cpp   |  3 +-
 clang/lib/Sema/TreeTransform.h|  2 +-
 clang/test/SemaCXX/PR84020.cpp| 23 ---
 .../instantiate-requires-expr.cpp | 29 +++
 4 files changed, 31 insertions(+), 26 deletions(-)
 delete mode 100644 clang/test/SemaCXX/PR84020.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ae7bcedfb28c73..959f0739f03fb9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6963,8 +6963,7 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, 
NamedDecl *NDecl,
   }
 
   if (CXXMethodDecl *Method = dyn_cast_or_null(FDecl))
-if (!isa(CurContext) &&
-Method->isImplicitObjectMemberFunction())
+if (Method->isImplicitObjectMemberFunction())
   return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
<< Fn->getSourceRange() << 0);
 
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 76efc9fe831854..ed9412c93c62b3 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13907,7 +13907,7 @@ bool 
TreeTransform::TransformOverloadExprDecls(OverloadExpr *Old,
 }
 
 AllEmptyPacks &= Decls.empty();
-  };
+  }
 
   // C++ [temp.res]/8.4.2:
   //   The program is ill-formed, no diagnostic required, if [...] lookup for
diff --git a/clang/test/SemaCXX/PR84020.cpp b/clang/test/SemaCXX/PR84020.cpp
deleted file mode 100644
index 8ea5dcc4527ae7..00
--- a/clang/test/SemaCXX/PR84020.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-// RUN: %clang_cc1 -std=c++20 -verify %s
-// RUN: %clang_cc1 -std=c++23 -verify %s
-// expected-no-diagnostics
-
-struct B {
-template 
-void foo();
-
-void bar();
-};
-
-template 
-struct A : T {
-auto foo() {
-static_assert(requires { T::template foo(); });
-static_assert(requires { T::bar(); });
-}
-};
-
-int main() {
-A a;
-a.foo();
-}
diff --git a/clang/test/SemaTemplate/instantiate-requires-expr.cpp 
b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
index 20a19d731ae169..4418ef6c861b60 100644
--- a/clang/test/SemaTemplate/instantiate-requires-expr.cpp
+++ b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
@@ -237,3 +237,32 @@ constexpr bool e_v = true;
 static_assert(e_v);
 
 } // namespace GH73885
+
+namespace GH84020 {
+
+struct B {
+  template  void foo();
+  void bar();
+};
+
+template  struct A : T {
+  static_assert(requires { T::template foo(); });
+  static_assert(requires { T::bar(); });
+};
+
+template class A;
+
+} // namespace GH84020
+
+namespace GH110785 {
+
+struct Foo {
+  static void f(auto) requires(false) {}
+  void f(int) {}
+
+  static_assert([](auto v) {
+return requires { f(v); };
+  } (0) == false);
+};
+
+} // namespace GH110785

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Younan Zhang via cfe-commits

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


[clang] [ByteCode] Avoid repeated hash lookups (NFC) (PR #111273)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes



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


1 Files Affected:

- (modified) clang/lib/AST/ByteCode/Program.cpp (+5-7) 


``diff
diff --git a/clang/lib/AST/ByteCode/Program.cpp 
b/clang/lib/AST/ByteCode/Program.cpp
index 969f523db51dfe..23245a66b578ae 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -284,15 +284,13 @@ Record *Program::getOrCreateRecord(const RecordDecl *RD) {
   if (!RD->isCompleteDefinition())
 return nullptr;
 
-  // Deduplicate records.
-  if (auto It = Records.find(RD); It != Records.end())
+  // Return an existing record if available.  Otherwise, we insert nullptr now
+  // and replace that later, so recursive calls to this function with the same
+  // RecordDecl don't run into infinite recursion.
+  auto [It, Inserted] = Records.try_emplace(RD);
+  if (!Inserted)
 return It->second;
 
-  // We insert nullptr now and replace that later, so recursive calls
-  // to this function with the same RecordDecl don't run into
-  // infinite recursion.
-  Records.insert({RD, nullptr});
-
   // Number of bytes required by fields and base classes.
   unsigned BaseSize = 0;
   // Number of bytes required by virtual base.

``




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


[clang] [StaticAnalyzer] Avoid repeated hash lookups (NFC) (PR #111272)

2024-10-05 Thread Kazu Hirata via cfe-commits

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

None

>From 9a5ad987040ed16478cd119814dc99ebc3d9d177 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 5 Oct 2024 10:24:52 -0700
Subject: [PATCH] [StaticAnalyzer] Avoid repeated hash lookups (NFC)

---
 .../StaticAnalyzer/Core/CheckerManager.cpp| 26 ---
 1 file changed, 11 insertions(+), 15 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
index ef617f5715c370..9f7a0fcc2edb36 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
@@ -66,13 +66,10 @@ void CheckerManager::runCheckersOnASTDecl(const Decl *D, 
AnalysisManager& mgr,
   assert(D);
 
   unsigned DeclKind = D->getKind();
-  CachedDeclCheckers *checkers = nullptr;
-  CachedDeclCheckersMapTy::iterator CCI = CachedDeclCheckersMap.find(DeclKind);
-  if (CCI != CachedDeclCheckersMap.end()) {
-checkers = &(CCI->second);
-  } else {
+  auto [CCI, Inserted] = CachedDeclCheckersMap.try_emplace(DeclKind);
+  CachedDeclCheckers *checkers = &(CCI->second);
+  if (Inserted) {
 // Find the checkers that should run for this Decl and cache them.
-checkers = &CachedDeclCheckersMap[DeclKind];
 for (const auto &info : DeclCheckers)
   if (info.IsForDeclFn(D))
 checkers->push_back(info.CheckFn);
@@ -896,14 +893,13 @@ CheckerManager::getCachedStmtCheckersFor(const Stmt *S, 
bool isPreVisit) {
   assert(S);
 
   unsigned Key = (S->getStmtClass() << 1) | unsigned(isPreVisit);
-  CachedStmtCheckersMapTy::iterator CCI = CachedStmtCheckersMap.find(Key);
-  if (CCI != CachedStmtCheckersMap.end())
-return CCI->second;
-
-  // Find the checkers that should run for this Stmt and cache them.
-  CachedStmtCheckers &Checkers = CachedStmtCheckersMap[Key];
-  for (const auto &Info : StmtCheckers)
-if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
-  Checkers.push_back(Info.CheckFn);
+  auto [CCI, Inserted] = CachedStmtCheckersMap.try_emplace(Key);
+  CachedStmtCheckers &Checkers = CCI->second;
+  if (Inserted) {
+// Find the checkers that should run for this Stmt and cache them.
+for (const auto &Info : StmtCheckers)
+  if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
+Checkers.push_back(Info.CheckFn);
+  }
   return Checkers;
 }

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


[clang] [StaticAnalyzer] Avoid repeated hash lookups (NFC) (PR #111272)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes



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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/CheckerManager.cpp (+11-15) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
index ef617f5715c370..9f7a0fcc2edb36 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp
@@ -66,13 +66,10 @@ void CheckerManager::runCheckersOnASTDecl(const Decl *D, 
AnalysisManager& mgr,
   assert(D);
 
   unsigned DeclKind = D->getKind();
-  CachedDeclCheckers *checkers = nullptr;
-  CachedDeclCheckersMapTy::iterator CCI = CachedDeclCheckersMap.find(DeclKind);
-  if (CCI != CachedDeclCheckersMap.end()) {
-checkers = &(CCI->second);
-  } else {
+  auto [CCI, Inserted] = CachedDeclCheckersMap.try_emplace(DeclKind);
+  CachedDeclCheckers *checkers = &(CCI->second);
+  if (Inserted) {
 // Find the checkers that should run for this Decl and cache them.
-checkers = &CachedDeclCheckersMap[DeclKind];
 for (const auto &info : DeclCheckers)
   if (info.IsForDeclFn(D))
 checkers->push_back(info.CheckFn);
@@ -896,14 +893,13 @@ CheckerManager::getCachedStmtCheckersFor(const Stmt *S, 
bool isPreVisit) {
   assert(S);
 
   unsigned Key = (S->getStmtClass() << 1) | unsigned(isPreVisit);
-  CachedStmtCheckersMapTy::iterator CCI = CachedStmtCheckersMap.find(Key);
-  if (CCI != CachedStmtCheckersMap.end())
-return CCI->second;
-
-  // Find the checkers that should run for this Stmt and cache them.
-  CachedStmtCheckers &Checkers = CachedStmtCheckersMap[Key];
-  for (const auto &Info : StmtCheckers)
-if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
-  Checkers.push_back(Info.CheckFn);
+  auto [CCI, Inserted] = CachedStmtCheckersMap.try_emplace(Key);
+  CachedStmtCheckers &Checkers = CCI->second;
+  if (Inserted) {
+// Find the checkers that should run for this Stmt and cache them.
+for (const auto &Info : StmtCheckers)
+  if (Info.IsPreVisit == isPreVisit && Info.IsForStmtFn(S))
+Checkers.push_back(Info.CheckFn);
+  }
   return Checkers;
 }

``




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


[clang] [clang][bytecode] Handle UETT_OpenMPRequiredSimdAlign (PR #111259)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-aarch64-linux-bootstrap-hwasan` running on `sanitizer-buildbot12` 
while building `clang` at step 2 "annotate".

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


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

```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 900 seconds was requested on the command line. Forcing 
timeout to be 900 seconds.
-- Testing: 82638 tests, 48 workers --
Testing: 
FAIL: Clang :: AST/ByteCode/builtins.cpp (78 of 82638)
 TEST 'Clang :: AST/ByteCode/builtins.cpp' FAILED 

Exit Code: 1

Command Output (stderr):
--
RUN: at line 1: 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/clang
 -cc1 -internal-isystem 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/lib/clang/20/include
 -nostdsysteminc -fexperimental-new-constant-interpreter 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
+ 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/bin/clang
 -cc1 -internal-isystem 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm_build_hwasan/lib/clang/20/include
 -nostdsysteminc -fexperimental-new-constant-interpreter 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
error: 'expected-error' diagnostics seen but not expected: 
  File 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 Line 40: static assertion failed due to requirement 
'__builtin_omp_required_simd_align(int) != 0'
error: 'expected-note' diagnostics seen but not expected: 
  File 
/home/b/sanitizer-aarch64-linux-bootstrap-hwasan/build/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 Line 40: expression evaluates to '0 != 0'
2 errors generated.

--


Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. 
Slowest Tests:
--
94.99s: Clang :: CodeGen/aarch64-sve-intrinsics/acle_sve_reinterpret.c
87.08s: Clang :: CodeGen/aarch64-sve-intrinsics/acle_sve_reinterpret-bfloat.c
77.33s: Clang :: CodeGen/X86/rot-intrinsics.c
74.61s: Clang :: CodeGen/X86/sse2-builtins.c
74.33s: LLVM :: CodeGen/AMDGPU/sched-group-barrier-pipeline-solver.mir
70.80s: Clang :: Driver/fsanitize.c
57.70s: Clang :: CodeGen/X86/x86_64-xsave.c
55.04s: Clang :: Driver/arm-cortex-cpus-2.c
54.18s: Clang :: Driver/arm-cortex-cpus-1.c
52.77s: Clang :: CodeGen/X86/sse41-builtins.c
52.68s: Clang :: CodeGen/X86/sse42-builtins.c
52.61s: Clang :: Headers/arm-neon-header.c
51.91s: Clang :: CodeGen/X86/sse-builtins-constrained.c
46.87s: Clang :: CodeGen/PowerPC/ppc-smmintrin.c
44.55s: Clang :: Analysis/a_flaky_crash.cpp
42.53s: Clang :: CodeGen/X86/x86_32-xsave.c
41.97s: Clang :: 
CodeGen/aarch64_neon_sve_bri

[clang] 73683cc - [Basic] Avoid repeated hash lookups (NFC) (#111228)

2024-10-05 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-10-05T12:11:01-07:00
New Revision: 73683cc1ab0fe79a4b02b956cf3c033250537bff

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

LOG: [Basic] Avoid repeated hash lookups (NFC) (#111228)

Added: 


Modified: 
clang/lib/Basic/TargetID.cpp

Removed: 




diff  --git a/clang/lib/Basic/TargetID.cpp b/clang/lib/Basic/TargetID.cpp
index fa1bfec2aacb9c..b42d1f07013c26 100644
--- a/clang/lib/Basic/TargetID.cpp
+++ b/clang/lib/Basic/TargetID.cpp
@@ -92,11 +92,9 @@ parseTargetIDWithFormatCheckingOnly(llvm::StringRef TargetID,
 if (Sign != '+' && Sign != '-')
   return std::nullopt;
 bool IsOn = Sign == '+';
-auto Loc = FeatureMap->find(Feature);
 // Each feature can only show up at most once in target ID.
-if (Loc != FeatureMap->end())
+if (!FeatureMap->try_emplace(Feature, IsOn).second)
   return std::nullopt;
-(*FeatureMap)[Feature] = IsOn;
 Features = Splits.second;
   }
   return Processor;
@@ -147,15 +145,15 @@ getConflictTargetIDCombination(const 
std::set &TargetIDs) {
   struct Info {
 llvm::StringRef TargetID;
 llvm::StringMap Features;
+Info(llvm::StringRef TargetID, const llvm::StringMap &Features)
+: TargetID(TargetID), Features(Features) {}
   };
   llvm::StringMap FeatureMap;
   for (auto &&ID : TargetIDs) {
 llvm::StringMap Features;
 llvm::StringRef Proc = *parseTargetIDWithFormatCheckingOnly(ID, &Features);
-auto Loc = FeatureMap.find(Proc);
-if (Loc == FeatureMap.end())
-  FeatureMap[Proc] = Info{ID, Features};
-else {
+auto [Loc, Inserted] = FeatureMap.try_emplace(Proc, ID, Features);
+if (!Inserted) {
   auto &ExistingFeatures = Loc->second.Features;
   if (llvm::any_of(Features, [&](auto &F) {
 return ExistingFeatures.count(F.first()) == 0;



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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Kazu Hirata via cfe-commits

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


[clang] [clang] Allow `pragma float_control(precise, *)` to... (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

https://github.com/echesakov updated 
https://github.com/llvm/llvm-project/pull/105912

>From 1231a5658bf7dde633e2d84967c6e540b3259e4b Mon Sep 17 00:00:00 2001
From: Egor Chesakov <5292656+echesa...@users.noreply.github.com>
Date: Sat, 5 Oct 2024 12:22:27 -0700
Subject: [PATCH] [clang] Allow `ConditionalOperator` fast-math flags to be
 overridden by `pragma float_control`

Currently, the fast-math flags set on `select` or `phi` instruction
emitted by CodeGen when visiting `ConditionalOperator` take into account
only global `FPOptions` and ignore `pragma float_control`.

This involves storing `FPOptionsOverride` in trailing storage of
`ConditionalOperator` and storing `CurFPOptionsOverride` when creating
an AST node.

Fixes #84648
---
 clang/include/clang/AST/Expr.h| 67 +--
 clang/include/clang/AST/Stmt.h| 11 +++
 clang/include/clang/AST/TextNodeDumper.h  |  1 +
 clang/lib/AST/ASTImporter.cpp |  6 +-
 clang/lib/AST/Expr.cpp| 22 ++
 clang/lib/AST/TextNodeDumper.cpp  |  5 ++
 clang/lib/CodeGen/CGExprScalar.cpp|  2 +
 .../Frontend/Rewrite/RewriteModernObjC.cpp|  7 +-
 clang/lib/Frontend/Rewrite/RewriteObjC.cpp| 13 ++--
 clang/lib/Sema/SemaExpr.cpp   |  6 +-
 clang/lib/Sema/SemaOpenMP.cpp | 12 ++--
 clang/lib/Serialization/ASTReaderStmt.cpp |  8 ++-
 clang/lib/Serialization/ASTWriterStmt.cpp |  3 +
 clang/test/AST/conditional-operator.c | 21 ++
 clang/test/CodeGen/conditional-operator.c | 36 ++
 15 files changed, 193 insertions(+), 27 deletions(-)
 create mode 100644 clang/test/AST/conditional-operator.c
 create mode 100644 clang/test/CodeGen/conditional-operator.c

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 7bacf028192c65..848c9676d5f11e 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4210,26 +4210,45 @@ class AbstractConditionalOperator : public Expr {
 
 /// ConditionalOperator - The ?: ternary operator.  The GNU "missing
 /// middle" extension is a BinaryConditionalOperator.
-class ConditionalOperator : public AbstractConditionalOperator {
+class ConditionalOperator final
+: public AbstractConditionalOperator,
+  private llvm::TrailingObjects {
   enum { COND, LHS, RHS, END_EXPR };
   Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
 
   friend class ASTStmtReader;
-public:
+
   ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
   SourceLocation CLoc, Expr *rhs, QualType t,
-  ExprValueKind VK, ExprObjectKind OK)
+  ExprValueKind VK, ExprObjectKind OK,
+  FPOptionsOverride FPFeatures)
   : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
 CLoc) {
 SubExprs[COND] = cond;
 SubExprs[LHS] = lhs;
 SubExprs[RHS] = rhs;
+ConditionalOperatorBits.HasFPFeatures =
+FPFeatures.requiresTrailingStorage();
+if (hasStoredFPFeatures())
+  setStoredFPFeatures(FPFeatures);
 setDependence(computeDependence(this));
   }
 
   /// Build an empty conditional operator.
-  explicit ConditionalOperator(EmptyShell Empty)
-: AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
+  ConditionalOperator(EmptyShell Empty, bool HasFPFeatures)
+  : AbstractConditionalOperator(ConditionalOperatorClass, Empty) {
+ConditionalOperatorBits.HasFPFeatures = HasFPFeatures;
+  }
+
+public:
+  static ConditionalOperator *CreateEmpty(const ASTContext &C, EmptyShell 
Empty,
+  bool HasFPFeatures);
+
+  static ConditionalOperator *Create(const ASTContext &C, Expr *cond,
+ SourceLocation QLoc, Expr *lhs,
+ SourceLocation CLoc, Expr *rhs, QualType 
t,
+ ExprValueKind VK, ExprObjectKind OK,
+ FPOptionsOverride FPFeatures);
 
   /// getCond - Return the expression representing the condition for
   ///   the ?: operator.
@@ -4265,6 +4284,44 @@ class ConditionalOperator : public 
AbstractConditionalOperator {
   const_child_range children() const {
 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
   }
+
+  /// Is FPFeatures in trailing storage?
+  bool hasStoredFPFeatures() const {
+return ConditionalOperatorBits.HasFPFeatures;
+  }
+  /// Get FPFeatures from trailing storage.
+  FPOptionsOverride getStoredFPFeatures() const {
+return *getTrailingFPFeatures();
+  }
+
+  // Get the FP features status of this operator. Only meaningful for
+  // operations on floating point types.
+  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
+if (hasStoredFPFeatures())
+  return getStoredFPFeatures().applyOverrides(LO);
+return FPOptions::defaul

[clang] [clang] Allow `ConditionalOperator` fast-math flags to be overridden by `pragma float_control` (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

echesakov wrote:

> Can you reword the description to have less wrapping

@arsenm @zahiraam Updated the commit/PR and added more details on the issue.

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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-arm-ubuntu` running 
on `linaro-lldb-arm-ubuntu` while building `clang` at step 6 "test".

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


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

```
Step 6 (test) failure: build (failure)
...
PASS: lldb-api :: lang/cpp/default-template-args/TestDefaultTemplateArgs.py 
(764 of 2809)
PASS: lldb-api :: 
lang/cpp/dereferencing_references/TestCPPDereferencingReferences.py (765 of 
2809)
PASS: lldb-api :: 
lang/cpp/dynamic-value-same-basename/TestDynamicValueSameBase.py (766 of 2809)
PASS: lldb-api :: lang/cpp/diamond/TestCppDiamond.py (767 of 2809)
PASS: lldb-api :: 
lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py (768 of 
2809)
PASS: lldb-api :: lang/cpp/elaborated-types/TestElaboratedTypes.py (769 of 2809)
PASS: lldb-api :: lang/cpp/dynamic-value/TestCppValueCast.py (770 of 2809)
PASS: lldb-api :: lang/cpp/enum_types/TestCPP11EnumTypes.py (771 of 2809)
PASS: lldb-api :: lang/cpp/exceptions/TestCPPExceptionBreakpoints.py (772 of 
2809)
PASS: lldb-api :: lang/cpp/extern_c/TestExternCSymbols.py (773 of 2809)
FAIL: lldb-api :: 
lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py (774 of 2809)
 TEST 'lldb-api :: 
lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py' FAILED 

Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/dotest.py 
-u CXXFLAGS -u CFLAGS --env ARCHIVER=/usr/local/bin/llvm-ar --env 
OBJCOPY=/usr/bin/llvm-objcopy --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/include --env 
LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --arch 
armv8l --build-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/dsymutil 
--llvm-tools-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin 
--lldb-obj-root /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/tools/lldb 
--lldb-libs-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/lang/c/shared_lib_stripped_symbols
 -p TestSharedLibStrippedSymbols.py
--
Exit Code: 1

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
73683cc1ab0fe79a4b02b956cf3c033250537bff)
  clang revision 73683cc1ab0fe79a4b02b956cf3c033250537bff
  llvm revision 73683cc1ab0fe79a4b02b956cf3c033250537bff
Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 
'debugserver', 'objc']

--
Command Output (stderr):
--
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dsym (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase) (test 
case does not fall in any category of interest for this run) 
FAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dwarf (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
PASS: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dwo (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dsym 
(TestSharedLibStrippedSymbols.SharedLibStrippedTestCase) (test case does not 
fall in any category of interest for this run) 
XFAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dwarf 
(TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
XFAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dwo (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
==
FAIL: test_expr_dwarf (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
   Test that types work when defined in a shared library and forwa/d-declared 
in the main executable
--
Traceback (most recent call last):
  File 
"/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/packages/Python/lldbsuite/test/lldbtest.py",
 line 1769, in test_method
return attrvalue(self)
  File 
"/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/lang/c/shared_lib_stripped_symbols/TestSharedLibStr

[clang] [clang] Allow `ConditionalOperator` fast-math flags to be overridden by `pragma float_control` (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

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


[clang] [clang] Allow `ConditionalOperator` fast-math flags to be overridden by `pragma float_control` (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

I pushed a new implementation for this fix.

I have updated the implementation of InstantiateFunctionDefinition so that it 
doesn't depend anymore on having the exact function declaration instantiation 
which has the same template context as the definition.

This avoids the more expensive aspect of the previous approach.
While keeping track of separate function declaration instantiations per primary 
template redeclaration increases source representation accuracy, It would be 
better to, in the future, go that way across that board for all templates, not 
just function templates, so that the impact can be better represented.

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


[clang] [llvm] [HLSL] implement elementwise firstbithigh hlsl builtin (PR #111082)

2024-10-05 Thread Farzon Lotfi via cfe-commits


@@ -1874,6 +1874,26 @@ bool SemaHLSL::CheckBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
   return true;
 break;
   }
+  case Builtin::BI__builtin_hlsl_elementwise_firstbithigh: {
+if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
+  return true;
+
+const Expr *Arg = TheCall->getArg(0);
+QualType ArgTy = Arg->getType();
+QualType EltTy = ArgTy;
+
+if (auto *VecTy = EltTy->getAs())
+  EltTy = VecTy->getElementType();
+
+if (!EltTy->isIntegerType() || getASTContext().getTypeSize(EltTy) != 32) {
+  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
+  << 1 << /* integer ty */ 6 << ArgTy;
+  return true;
+}
+
+TheCall->setType(ArgTy);

farzonl wrote:

If @bogner is right  this line is a bit more complicated. We will have to 
construct the call type  as a scalar or vector of the same size as ArgTy but 
with the element type of int32.

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


[clang] [Clang] omit parentheses in fold expressions with a single expansion (PR #110761)

2024-10-05 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/110761

>From 9c69d6584d6b71554aec55f0de52abb4baa9435f Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 2 Oct 2024 02:13:51 +0300
Subject: [PATCH 1/8] [Clang] omit parentheses in fold expressions with a
 single expansion

---
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/lib/Sema/TreeTransform.h   |  3 +++
 clang/test/SemaCXX/warn-assignment-condition.cpp | 12 +++-
 .../test/SemaTemplate/instantiate-requires-expr.cpp  |  2 +-
 4 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bf128e370b076e..254779dc734dea 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -460,6 +460,7 @@ Bug Fixes to C++ Support
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
+- Fixed warnings for extra parentheses in fold expressions by eliminating them 
in single expansion cases. (#GH101863)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 6fdb18d51acef9..1a963858d0a3e4 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -15598,6 +15598,9 @@ 
TreeTransform::TransformCXXFoldExpr(CXXFoldExpr *E) {
 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
 E->getOperator());
 
+  if (*NumExpansions == 1)
+Result = Result.get()->IgnoreParens();
+
   return Result;
 }
 
diff --git a/clang/test/SemaCXX/warn-assignment-condition.cpp 
b/clang/test/SemaCXX/warn-assignment-condition.cpp
index 09084e36bb4916..1b644260aa61d5 100644
--- a/clang/test/SemaCXX/warn-assignment-condition.cpp
+++ b/clang/test/SemaCXX/warn-assignment-condition.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wparentheses -verify %s
+// RUN: %clang_cc1 -fsyntax-only -Wparentheses -std=c++2a -verify %s
 
 struct A {
   int foo();
@@ -144,3 +144,13 @@ void test() {
   f(S()); // expected-note {{in instantiation}}
 }
 }
+
+namespace GH101863 {
+void foo(auto... args) {
+  if (((args == 0) or ...)) {} // ok
+}
+
+void bar() {
+  foo(3);
+}
+}
diff --git a/clang/test/SemaTemplate/instantiate-requires-expr.cpp 
b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
index 20a19d731ae169..ce2c060a176045 100644
--- a/clang/test/SemaTemplate/instantiate-requires-expr.cpp
+++ b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
@@ -36,7 +36,7 @@ using r1i2 = r1; // expected-error {{constraints not 
satisfied for class t
 template requires
 false_v
 // expected-note@-1 {{because 'false_v'}}
-// expected-note@-2 {{because 'false_v' evaluated to false}}
+// expected-note@-2 {{because 'false_v' evaluated to false}}
 struct r2 {};
 
 using r2i1 = r2; // expected-error {{constraints not 
satisfied for class template 'r2' [with Ts = ]}}

>From 22f98718d499b60836cccb5cbfcfa2098cddeb10 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 2 Oct 2024 15:59:26 +0300
Subject: [PATCH 2/8] move changelog message to diagnostics

---
 clang/docs/ReleaseNotes.rst | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d71de13b093daf..e927b305ef1281 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -375,6 +375,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when a ``requires`` expression has a local parameter of 
void type, aligning with the function parameter (#GH109831).
 
+- Clang now omits warnings for extra parentheses in fold expressions with 
single expansion. (#GH101863)
+
 Improvements to Clang's time-trace
 --
 
@@ -471,7 +473,6 @@ Bug Fixes to C++ Support
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
-- Fixed warnings for extra parentheses in fold expressions by eliminating them 
in single expansion cases. (#GH101863)
 
 Bug Fixes to AST Handling
 ^

>From b9305e649a5dbf2101d2528c1eaabc6fb039483f Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Thu, 3 Oct 2024 02:25:43 +0300
Subject: [PATCH 3/8] adjust pattern to omit parentheses

---
 clang/lib/Sema/TreeTransform.h| 12 --
 .../SemaCXX/warn-assignment-condition.cpp | 41 +--
 2 files changed, 28 insertions(+), 25 deletions(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1a963858d0a3e4..72b50245f16a7d 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/Tree

[clang] [Clang] omit parentheses in fold expressions with a single expansion (PR #110761)

2024-10-05 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/110761

>From 9c69d6584d6b71554aec55f0de52abb4baa9435f Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 2 Oct 2024 02:13:51 +0300
Subject: [PATCH 1/8] [Clang] omit parentheses in fold expressions with a
 single expansion

---
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/lib/Sema/TreeTransform.h   |  3 +++
 clang/test/SemaCXX/warn-assignment-condition.cpp | 12 +++-
 .../test/SemaTemplate/instantiate-requires-expr.cpp  |  2 +-
 4 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bf128e370b076e..254779dc734dea 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -460,6 +460,7 @@ Bug Fixes to C++ Support
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
+- Fixed warnings for extra parentheses in fold expressions by eliminating them 
in single expansion cases. (#GH101863)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 6fdb18d51acef9..1a963858d0a3e4 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -15598,6 +15598,9 @@ 
TreeTransform::TransformCXXFoldExpr(CXXFoldExpr *E) {
 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
 E->getOperator());
 
+  if (*NumExpansions == 1)
+Result = Result.get()->IgnoreParens();
+
   return Result;
 }
 
diff --git a/clang/test/SemaCXX/warn-assignment-condition.cpp 
b/clang/test/SemaCXX/warn-assignment-condition.cpp
index 09084e36bb4916..1b644260aa61d5 100644
--- a/clang/test/SemaCXX/warn-assignment-condition.cpp
+++ b/clang/test/SemaCXX/warn-assignment-condition.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wparentheses -verify %s
+// RUN: %clang_cc1 -fsyntax-only -Wparentheses -std=c++2a -verify %s
 
 struct A {
   int foo();
@@ -144,3 +144,13 @@ void test() {
   f(S()); // expected-note {{in instantiation}}
 }
 }
+
+namespace GH101863 {
+void foo(auto... args) {
+  if (((args == 0) or ...)) {} // ok
+}
+
+void bar() {
+  foo(3);
+}
+}
diff --git a/clang/test/SemaTemplate/instantiate-requires-expr.cpp 
b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
index 20a19d731ae169..ce2c060a176045 100644
--- a/clang/test/SemaTemplate/instantiate-requires-expr.cpp
+++ b/clang/test/SemaTemplate/instantiate-requires-expr.cpp
@@ -36,7 +36,7 @@ using r1i2 = r1; // expected-error {{constraints not 
satisfied for class t
 template requires
 false_v
 // expected-note@-1 {{because 'false_v'}}
-// expected-note@-2 {{because 'false_v' evaluated to false}}
+// expected-note@-2 {{because 'false_v' evaluated to false}}
 struct r2 {};
 
 using r2i1 = r2; // expected-error {{constraints not 
satisfied for class template 'r2' [with Ts = ]}}

>From 22f98718d499b60836cccb5cbfcfa2098cddeb10 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 2 Oct 2024 15:59:26 +0300
Subject: [PATCH 2/8] move changelog message to diagnostics

---
 clang/docs/ReleaseNotes.rst | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d71de13b093daf..e927b305ef1281 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -375,6 +375,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when a ``requires`` expression has a local parameter of 
void type, aligning with the function parameter (#GH109831).
 
+- Clang now omits warnings for extra parentheses in fold expressions with 
single expansion. (#GH101863)
+
 Improvements to Clang's time-trace
 --
 
@@ -471,7 +473,6 @@ Bug Fixes to C++ Support
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
-- Fixed warnings for extra parentheses in fold expressions by eliminating them 
in single expansion cases. (#GH101863)
 
 Bug Fixes to AST Handling
 ^

>From b9305e649a5dbf2101d2528c1eaabc6fb039483f Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Thu, 3 Oct 2024 02:25:43 +0300
Subject: [PATCH 3/8] adjust pattern to omit parentheses

---
 clang/lib/Sema/TreeTransform.h| 12 --
 .../SemaCXX/warn-assignment-condition.cpp | 41 +--
 2 files changed, 28 insertions(+), 25 deletions(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1a963858d0a3e4..72b50245f16a7d 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/Tree

[clang] [clang][bytecode] Save a per-Block IsWeak bit (PR #111248)

2024-10-05 Thread Timm Baeder via cfe-commits

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

Checking the decl for every load is rather expensive.

>From 7011cb6a67c154f2d93036dfcaa381f83e070f59 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 5 Oct 2024 12:56:31 +0200
Subject: [PATCH] [clang][bytecode] Save a per-Block IsWeak bit

Checking the decl for every load is rather expensive.
---
 clang/lib/AST/ByteCode/InterpBlock.cpp |  4 ++--
 clang/lib/AST/ByteCode/InterpBlock.h   | 15 +--
 clang/lib/AST/ByteCode/Pointer.h   |  4 +---
 clang/lib/AST/ByteCode/Program.cpp | 16 ++--
 clang/lib/AST/ByteCode/Program.h   |  2 +-
 5 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/clang/lib/AST/ByteCode/InterpBlock.cpp 
b/clang/lib/AST/ByteCode/InterpBlock.cpp
index 0ce88ca7e52365..9ef44cd29ff875 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.cpp
+++ b/clang/lib/AST/ByteCode/InterpBlock.cpp
@@ -100,8 +100,8 @@ bool Block::hasPointer(const Pointer *P) const {
 #endif
 
 DeadBlock::DeadBlock(DeadBlock *&Root, Block *Blk)
-: Root(Root),
-  B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, /*isDead=*/true) {
+: Root(Root), B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, Blk->IsWeak,
+/*isDead=*/true) {
   // Add the block to the chain of dead blocks.
   if (Root)
 Root->Prev = this;
diff --git a/clang/lib/AST/ByteCode/InterpBlock.h 
b/clang/lib/AST/ByteCode/InterpBlock.h
index a5cd58e3a655a0..985e4c152191c6 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.h
+++ b/clang/lib/AST/ByteCode/InterpBlock.h
@@ -50,16 +50,17 @@ class Block final {
 public:
   /// Creates a new block.
   Block(unsigned EvalID, const std::optional &DeclID,
-const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false)
+const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false,
+bool IsWeak = false)
   : EvalID(EvalID), DeclID(DeclID), IsStatic(IsStatic), IsExtern(IsExtern),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsStatic = false,
-bool IsExtern = false)
+bool IsExtern = false, bool IsWeak = false)
   : EvalID(EvalID), DeclID((unsigned)-1), IsStatic(IsStatic),
-IsExtern(IsExtern), IsDynamic(false), Desc(Desc) {
+IsExtern(IsExtern), IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -73,6 +74,7 @@ class Block final {
   bool isStatic() const { return IsStatic; }
   /// Checks if the block is temporary.
   bool isTemporary() const { return Desc->IsTemporary; }
+  bool isWeak() const { return IsWeak; }
   bool isDynamic() const { return IsDynamic; }
   /// Returns the size of the block.
   unsigned getSize() const { return Desc->getAllocSize(); }
@@ -135,9 +137,9 @@ class Block final {
   friend class DynamicAllocator;
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsExtern, bool IsStatic,
-bool IsDead)
+bool IsWeak, bool IsDead)
   : EvalID(EvalID), IsStatic(IsStatic), IsExtern(IsExtern), IsDead(true),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -170,6 +172,7 @@ class Block final {
   /// Flag indicating if this block has been allocated via dynamic
   /// memory allocation (e.g. malloc).
   bool IsDynamic = false;
+  bool IsWeak = false;
   /// Pointer to the stack slot descriptor.
   const Descriptor *Desc;
 };
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index 08bc4b7e40b636..72e255dba13f6b 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -524,9 +524,7 @@ class Pointer {
   return false;
 
 assert(isBlockPointer());
-if (const ValueDecl *VD = getDeclDesc()->asValueDecl())
-  return VD->isWeak();
-return false;
+return asBlockPointer().Pointee->isWeak();
   }
   /// Checks if an object was initialized.
   bool isInitialized() const;
diff --git a/clang/lib/AST/ByteCode/Program.cpp 
b/clang/lib/AST/ByteCode/Program.cpp
index 79c645257306e0..969f523db51dfe 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -152,10 +152,12 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 return It->second;
 
   QualType QT;
+  bool IsWeak = false;
   if (const auto *E = D.dyn_cast()) {
 QT = E->getType();
   } else {
 const ValueDecl *VD = cast(D.get());
+IsWeak = VD->isWeak();
 QT = VD->getType();
 if (const auto *RT = QT->getAs())
   QT = RT->getPointeeType();
@@ -182,7 +184,7 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 
   auto *G = new (Allocator, Desc->getAllocSize())
   Global(Ctx.getEvalID(), getCurrentDecl(), Desc, /*IsStatic=*/true,
- /*IsExtern=*/false);
+ /*IsExtern=*/false, IsWeak)

[clang] [clang][bytecode] Save a per-Block IsWeak bit (PR #111248)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Checking the decl for every load is rather expensive.

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


5 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBlock.cpp (+2-2) 
- (modified) clang/lib/AST/ByteCode/InterpBlock.h (+9-6) 
- (modified) clang/lib/AST/ByteCode/Pointer.h (+1-3) 
- (modified) clang/lib/AST/ByteCode/Program.cpp (+10-6) 
- (modified) clang/lib/AST/ByteCode/Program.h (+1-1) 


``diff
diff --git a/clang/lib/AST/ByteCode/InterpBlock.cpp 
b/clang/lib/AST/ByteCode/InterpBlock.cpp
index 0ce88ca7e52365..9ef44cd29ff875 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.cpp
+++ b/clang/lib/AST/ByteCode/InterpBlock.cpp
@@ -100,8 +100,8 @@ bool Block::hasPointer(const Pointer *P) const {
 #endif
 
 DeadBlock::DeadBlock(DeadBlock *&Root, Block *Blk)
-: Root(Root),
-  B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, /*isDead=*/true) {
+: Root(Root), B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, Blk->IsWeak,
+/*isDead=*/true) {
   // Add the block to the chain of dead blocks.
   if (Root)
 Root->Prev = this;
diff --git a/clang/lib/AST/ByteCode/InterpBlock.h 
b/clang/lib/AST/ByteCode/InterpBlock.h
index a5cd58e3a655a0..985e4c152191c6 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.h
+++ b/clang/lib/AST/ByteCode/InterpBlock.h
@@ -50,16 +50,17 @@ class Block final {
 public:
   /// Creates a new block.
   Block(unsigned EvalID, const std::optional &DeclID,
-const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false)
+const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false,
+bool IsWeak = false)
   : EvalID(EvalID), DeclID(DeclID), IsStatic(IsStatic), IsExtern(IsExtern),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsStatic = false,
-bool IsExtern = false)
+bool IsExtern = false, bool IsWeak = false)
   : EvalID(EvalID), DeclID((unsigned)-1), IsStatic(IsStatic),
-IsExtern(IsExtern), IsDynamic(false), Desc(Desc) {
+IsExtern(IsExtern), IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -73,6 +74,7 @@ class Block final {
   bool isStatic() const { return IsStatic; }
   /// Checks if the block is temporary.
   bool isTemporary() const { return Desc->IsTemporary; }
+  bool isWeak() const { return IsWeak; }
   bool isDynamic() const { return IsDynamic; }
   /// Returns the size of the block.
   unsigned getSize() const { return Desc->getAllocSize(); }
@@ -135,9 +137,9 @@ class Block final {
   friend class DynamicAllocator;
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsExtern, bool IsStatic,
-bool IsDead)
+bool IsWeak, bool IsDead)
   : EvalID(EvalID), IsStatic(IsStatic), IsExtern(IsExtern), IsDead(true),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -170,6 +172,7 @@ class Block final {
   /// Flag indicating if this block has been allocated via dynamic
   /// memory allocation (e.g. malloc).
   bool IsDynamic = false;
+  bool IsWeak = false;
   /// Pointer to the stack slot descriptor.
   const Descriptor *Desc;
 };
diff --git a/clang/lib/AST/ByteCode/Pointer.h b/clang/lib/AST/ByteCode/Pointer.h
index 08bc4b7e40b636..72e255dba13f6b 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -524,9 +524,7 @@ class Pointer {
   return false;
 
 assert(isBlockPointer());
-if (const ValueDecl *VD = getDeclDesc()->asValueDecl())
-  return VD->isWeak();
-return false;
+return asBlockPointer().Pointee->isWeak();
   }
   /// Checks if an object was initialized.
   bool isInitialized() const;
diff --git a/clang/lib/AST/ByteCode/Program.cpp 
b/clang/lib/AST/ByteCode/Program.cpp
index 79c645257306e0..969f523db51dfe 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -152,10 +152,12 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 return It->second;
 
   QualType QT;
+  bool IsWeak = false;
   if (const auto *E = D.dyn_cast()) {
 QT = E->getType();
   } else {
 const ValueDecl *VD = cast(D.get());
+IsWeak = VD->isWeak();
 QT = VD->getType();
 if (const auto *RT = QT->getAs())
   QT = RT->getPointeeType();
@@ -182,7 +184,7 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 
   auto *G = new (Allocator, Desc->getAllocSize())
   Global(Ctx.getEvalID(), getCurrentDecl(), Desc, /*IsStatic=*/true,
- /*IsExtern=*/false);
+ /*IsExtern=*/false, IsWeak);
   G->block()->invokeCtor();
 
   Globals.push_back(G);
@@ -193,6 +195,7 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 std::optional Program::createGlobal(const ValueDecl *VD,

[clang] Effect analysis: correctly detect `(x ? a : b)` as nonblocking when a and b are (PR #111224)

2024-10-05 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos updated 
https://github.com/llvm/llvm-project/pull/111224

>From 02398e6398892dac5d151a6e425bf107213e12a8 Mon Sep 17 00:00:00 2001
From: Doug Wyatt 
Date: Fri, 4 Oct 2024 18:28:37 -0700
Subject: [PATCH 1/3] Effect analysis: correctly detect `(f ? a : b)` as
 nonblocking when a and b are.

---
 clang/lib/Sema/SemaFunctionEffects.cpp   | 11 +--
 clang/test/Sema/attr-nonblocking-constraints.cpp | 10 ++
 2 files changed, 15 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Sema/SemaFunctionEffects.cpp 
b/clang/lib/Sema/SemaFunctionEffects.cpp
index 0fb18d207a50ba..0ac5de29f66aa7 100644
--- a/clang/lib/Sema/SemaFunctionEffects.cpp
+++ b/clang/lib/Sema/SemaFunctionEffects.cpp
@@ -1048,15 +1048,14 @@ class Analyzer {
 }
 
 void checkIndirectCall(CallExpr *Call, QualType CalleeType) {
-  auto *FPT =
-  CalleeType->getAs(); // Null if FunctionType.
   FunctionEffectKindSet CalleeEffects;
-  if (FPT)
-CalleeEffects.insert(FPT->getFunctionEffects());
+  if (FunctionEffectsRef Effects = FunctionEffectsRef::get(CalleeType);
+  !Effects.empty())
+CalleeEffects.insert(Effects);
 
   auto Check1Effect = [&](FunctionEffect Effect, bool Inferring) {
-if (FPT == nullptr || Effect.shouldDiagnoseFunctionCall(
-  /*direct=*/false, CalleeEffects))
+if (Effect.shouldDiagnoseFunctionCall(
+/*direct=*/false, CalleeEffects))
   addViolation(Inferring, Effect, ViolationID::CallsExprWithoutEffect,
Call->getBeginLoc());
   };
diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp 
b/clang/test/Sema/attr-nonblocking-constraints.cpp
index c694860069c960..ff8caf0e573403 100644
--- a/clang/test/Sema/attr-nonblocking-constraints.cpp
+++ b/clang/test/Sema/attr-nonblocking-constraints.cpp
@@ -156,6 +156,16 @@ void nb10(
static_cast(fp1)(); // expected-warning {{function with 
'nonblocking' attribute must not call non-'nonblocking' expression}}
 }
 
+// Expression involving indirection
+int nb10a() [[clang::nonblocking]];
+int nb10b() [[clang::nonblocking]];
+
+int nb10c(bool x) [[clang::nonblocking]]
+{
+   // Warns that the expression is not nonblocking.
+   return (x ? nb10a : nb10b)();
+}
+
 // Interactions with nonblocking(false)
 void nb11_no_inference_1() [[clang::nonblocking(false)]] // expected-note 
{{function does not permit inference of 'nonblocking'}}
 {

>From 1dece8572d01d86a8d42c0985ca4058ec4838064 Mon Sep 17 00:00:00 2001
From: Doug Wyatt 
Date: Fri, 4 Oct 2024 18:40:01 -0700
Subject: [PATCH 2/3] Fix comment in test.

---
 clang/test/Sema/attr-nonblocking-constraints.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp 
b/clang/test/Sema/attr-nonblocking-constraints.cpp
index ff8caf0e573403..59061dffa372b4 100644
--- a/clang/test/Sema/attr-nonblocking-constraints.cpp
+++ b/clang/test/Sema/attr-nonblocking-constraints.cpp
@@ -162,8 +162,7 @@ int nb10b() [[clang::nonblocking]];
 
 int nb10c(bool x) [[clang::nonblocking]]
 {
-   // Warns that the expression is not nonblocking.
-   return (x ? nb10a : nb10b)();
+   return (x ? nb10a : nb10b)(); // No diagnostic.
 }
 
 // Interactions with nonblocking(false)

>From 30c453ec77dbd3a2b01dae032506e808cf26470c Mon Sep 17 00:00:00 2001
From: Doug Wyatt 
Date: Sat, 5 Oct 2024 09:34:27 -0700
Subject: [PATCH 3/3] add another test

---
 clang/test/Sema/attr-nonblocking-constraints.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp 
b/clang/test/Sema/attr-nonblocking-constraints.cpp
index 59061dffa372b4..f23093d4dc8a96 100644
--- a/clang/test/Sema/attr-nonblocking-constraints.cpp
+++ b/clang/test/Sema/attr-nonblocking-constraints.cpp
@@ -159,9 +159,11 @@ void nb10(
 // Expression involving indirection
 int nb10a() [[clang::nonblocking]];
 int nb10b() [[clang::nonblocking]];
+int blocking();
 
 int nb10c(bool x) [[clang::nonblocking]]
 {
+   int y = (x ? nb10a : blocking)(); // expected-warning {{attribute 
'nonblocking' should not be added via type conversion}}
return (x ? nb10a : nb10b)(); // No diagnostic.
 }
 

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


[clang] [clang][bytecode] Handle UETT_OpenMPRequiredSimdAlign (PR #111259)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-clang-aarch64-darwin` 
running on `doug-worker-4` while building `clang` at step 6 
"test-build-unified-tree-check-all".

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


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

```
Step 6 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'Clang :: AST/ByteCode/builtins.cpp' FAILED 

Exit Code: 1

Command Output (stderr):
--
RUN: at line 1: /Users/buildbot/buildbot-root/aarch64-darwin/build/bin/clang 
-cc1 -internal-isystem 
/Users/buildbot/buildbot-root/aarch64-darwin/build/lib/clang/20/include 
-nostdsysteminc -fexperimental-new-constant-interpreter 
/Users/buildbot/buildbot-root/aarch64-darwin/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
+ /Users/buildbot/buildbot-root/aarch64-darwin/build/bin/clang -cc1 
-internal-isystem 
/Users/buildbot/buildbot-root/aarch64-darwin/build/lib/clang/20/include 
-nostdsysteminc -fexperimental-new-constant-interpreter 
/Users/buildbot/buildbot-root/aarch64-darwin/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
error: 'expected-error' diagnostics seen but not expected: 
  File 
/Users/buildbot/buildbot-root/aarch64-darwin/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 Line 40: static assertion failed due to requirement 
'__builtin_omp_required_simd_align(int) != 0'
error: 'expected-note' diagnostics seen but not expected: 
  File 
/Users/buildbot/buildbot-root/aarch64-darwin/llvm-project/clang/test/AST/ByteCode/builtins.cpp
 Line 40: expression evaluates to '0 != 0'
2 errors generated.

--




```



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


[clang] [clang][bytecode] Handle UETT_OpenMPRequiredSimdAlign (PR #111259)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-arm-ubuntu` running 
on `linaro-lldb-arm-ubuntu` while building `clang` at step 6 "test".

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


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

```
Step 6 (test) failure: build (failure)
...
UNSUPPORTED: lldb-api :: lang/cpp/gmodules/templates/TestGModules.py (791 of 
2809)
PASS: lldb-api :: 
lang/cpp/incompatible-class-templates/TestCppIncompatibleClassTemplates.py (792 
of 2809)
PASS: lldb-api :: lang/cpp/incomplete-stl-types/TestStlIncompleteTypes.py (793 
of 2809)
PASS: lldb-api :: 
lang/cpp/incomplete-types/members/TestCppIncompleteTypeMembers.py (794 of 2809)
PASS: lldb-api :: lang/cpp/inlines/TestInlines.py (795 of 2809)
PASS: lldb-api :: lang/cpp/keywords_enabled/TestCppKeywordsEnabled.py (796 of 
2809)
PASS: lldb-api :: lang/cpp/incomplete-types/TestCppIncompleteTypes.py (797 of 
2809)
PASS: lldb-api :: lang/cpp/lambdas/TestLambdas.py (798 of 2809)
PASS: lldb-api :: lang/cpp/llvm-style/TestLLVMStyle.py (799 of 2809)
UNSUPPORTED: lldb-api :: lang/cpp/modules-import/TestCXXModulesImport.py (800 
of 2809)
FAIL: lldb-api :: 
lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py (801 of 2809)
 TEST 'lldb-api :: 
lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py' FAILED 

Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/dotest.py 
-u CXXFLAGS -u CFLAGS --env ARCHIVER=/usr/local/bin/llvm-ar --env 
OBJCOPY=/usr/bin/llvm-objcopy --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/include --env 
LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --arch 
armv8l --build-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/dsymutil 
--llvm-tools-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin 
--lldb-obj-root /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/tools/lldb 
--lldb-libs-dir /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/lang/c/shared_lib_stripped_symbols
 -p TestSharedLibStrippedSymbols.py
--
Exit Code: 1

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
c57418037a002f4c5f19339837cc37e3a8f4ecb8)
  clang revision c57418037a002f4c5f19339837cc37e3a8f4ecb8
  llvm revision c57418037a002f4c5f19339837cc37e3a8f4ecb8
Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 
'debugserver', 'objc']

--
Command Output (stderr):
--
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dsym (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase) (test 
case does not fall in any category of interest for this run) 
FAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dwarf (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
PASS: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_expr_dwo (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dsym 
(TestSharedLibStrippedSymbols.SharedLibStrippedTestCase) (test case does not 
fall in any category of interest for this run) 
XFAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dwarf 
(TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
XFAIL: LLDB (/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/bin/clang-arm) :: 
test_frame_variable_dwo (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
==
FAIL: test_expr_dwarf (TestSharedLibStrippedSymbols.SharedLibStrippedTestCase)
   Test that types work when defined in a shared library and forwa/d-declared 
in the main executable
--
Traceback (most recent call last):
  File 
"/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/packages/Python/lldbsuite/test/lldbtest.py",
 line 1769, in test_method
return attrvalue(self)
  File 
"/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.

[clang] [clang][bytecode] Handle UETT_OpenMPRequiredSimdAlign (PR #111259)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-solaris11-sparcv9` 
running on `solaris11-sparcv9` while building `clang` at step 5 "ninja check 1".

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


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

```
Step 5 (ninja check 1) failure: stage 1 checked (failure)
 TEST 'Clang :: AST/ByteCode/builtins.cpp' FAILED 

Exit Code: 1

Command Output (stderr):
--
RUN: at line 1: 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/stage1/bin/clang
 -cc1 -internal-isystem 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/stage1/lib/clang/20/include
 -nostdsysteminc -fexperimental-new-constant-interpreter 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/llvm/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
+ 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/stage1/bin/clang
 -cc1 -internal-isystem 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/stage1/lib/clang/20/include
 -nostdsysteminc -fexperimental-new-constant-interpreter 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/llvm/clang/test/AST/ByteCode/builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
error: 'expected-error' diagnostics seen but not expected: 
  File 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/llvm/clang/test/AST/ByteCode/builtins.cpp
 Line 40: static assertion failed due to requirement 
'__builtin_omp_required_simd_align(int) != 0'
error: 'expected-note' diagnostics seen but not expected: 
  File 
/opt/llvm-buildbot/home/solaris11-sparcv9/clang-solaris11-sparcv9/llvm/clang/test/AST/ByteCode/builtins.cpp
 Line 40: expression evaluates to '0 != 0'
2 errors generated.

--




```



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


[clang] 020b8e8 - [clang][test] Remove a broken bytecode test

2024-10-05 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-10-05T18:46:21+02:00
New Revision: 020b8e8f8dfef2392351e66215d11cccb573a88f

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

LOG: [clang][test] Remove a broken bytecode test

See e.g. https://lab.llvm.org/buildbot/#/builders/13/builds/2705

Looks like the expected value is legitimately sometimes 0.
I'll add another test back later.

Added: 


Modified: 
clang/test/AST/ByteCode/builtins.cpp

Removed: 




diff  --git a/clang/test/AST/ByteCode/builtins.cpp 
b/clang/test/AST/ByteCode/builtins.cpp
index 324b8c741130c6..9b2b20773be58a 100644
--- a/clang/test/AST/ByteCode/builtins.cpp
+++ b/clang/test/AST/ByteCode/builtins.cpp
@@ -36,5 +36,3 @@ void test_builtin_os_log(void *buf, int i, const char *data) {
   constexpr int len = __builtin_os_log_format_buffer_size("%d %{public}s 
%{private}.16P", i, data, data);
   static_assert(len > 0, "Expect len > 0");
 }
-
-static_assert(__builtin_omp_required_simd_align(int) != 0);



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


[clang] 8aa76d3 - [Driver] Avoid repeated hash lookups (NFC) (#111225)

2024-10-05 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-10-05T09:49:49-07:00
New Revision: 8aa76d34ea95031abed32761251951c5f87492c6

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

LOG: [Driver] Avoid repeated hash lookups (NFC) (#111225)

Added: 


Modified: 
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index e9bf60d5e2ee46..2aaa52072b03d2 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -984,8 +984,9 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation 
&C,
 } else
   TC = &getToolChain(C.getInputArgs(), TT);
 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
-if (DerivedArchs.contains(TT.getTriple()))
-  KnownArchs[TC] = DerivedArchs[TT.getTriple()];
+auto It = DerivedArchs.find(TT.getTriple());
+if (It != DerivedArchs.end())
+  KnownArchs[TC] = It->second;
   }
 }
   } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) {
@@ -3749,11 +3750,10 @@ class OffloadingActionBuilder final {
   void recordHostAction(Action *HostAction, const Arg *InputArg) {
 assert(HostAction && "Invalid host action");
 assert(InputArg && "Invalid input argument");
-auto Loc = HostActionToInputArgMap.find(HostAction);
-if (Loc == HostActionToInputArgMap.end())
-  HostActionToInputArgMap[HostAction] = InputArg;
-assert(HostActionToInputArgMap[HostAction] == InputArg &&
+auto Loc = HostActionToInputArgMap.try_emplace(HostAction, InputArg).first;
+assert(Loc->second == InputArg &&
"host action mapped to multiple input arguments");
+(void)Loc;
   }
 
   /// Generate an action that adds device dependences (if any) to a host 
action.
@@ -5581,8 +5581,9 @@ InputInfoList Driver::BuildJobsForActionNoCache(
 std::pair ActionTC = {
 OA->getHostDependence(),
 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
-if (CachedResults.find(ActionTC) != CachedResults.end()) {
-  InputInfoList Inputs = CachedResults[ActionTC];
+auto It = CachedResults.find(ActionTC);
+if (It != CachedResults.end()) {
+  InputInfoList Inputs = It->second;
   Inputs.append(OffloadDependencesInputInfo);
   return Inputs;
 }



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


[clang] [Driver] Avoid repeated hash lookups (NFC) (PR #111225)

2024-10-05 Thread Kazu Hirata via cfe-commits

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


[clang] [Sema] Avoid repeated hash lookups (NFC) (PR #111227)

2024-10-05 Thread Kazu Hirata via cfe-commits

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


[clang] e8f01b0 - [Sema] Avoid repeated hash lookups (NFC) (#111227)

2024-10-05 Thread via cfe-commits

Author: Kazu Hirata
Date: 2024-10-05T09:51:12-07:00
New Revision: e8f01b0557354a28d17bfe618df5e257ec3e982a

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

LOG: [Sema] Avoid repeated hash lookups (NFC) (#111227)

Added: 


Modified: 
clang/lib/Sema/SemaOpenMP.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 8615da4b044a82..74ab52106e3234 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -1405,10 +1405,9 @@ const Expr *DSAStackTy::addUniqueAligned(const ValueDecl 
*D,
   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
   D = getCanonicalDecl(D);
   SharingMapTy &StackElem = getTopOfStack();
-  auto It = StackElem.AlignedMap.find(D);
-  if (It == StackElem.AlignedMap.end()) {
+  auto [It, Inserted] = StackElem.AlignedMap.try_emplace(D, NewDE);
+  if (Inserted) {
 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
-StackElem.AlignedMap[D] = NewDE;
 return nullptr;
   }
   assert(It->second && "Unexpected nullptr expr in the aligned map");
@@ -1420,10 +1419,9 @@ const Expr *DSAStackTy::addUniqueNontemporal(const 
ValueDecl *D,
   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
   D = getCanonicalDecl(D);
   SharingMapTy &StackElem = getTopOfStack();
-  auto It = StackElem.NontemporalMap.find(D);
-  if (It == StackElem.NontemporalMap.end()) {
+  auto [It, Inserted] = StackElem.NontemporalMap.try_emplace(D, NewDE);
+  if (Inserted) {
 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
-StackElem.NontemporalMap[D] = NewDE;
 return nullptr;
   }
   assert(It->second && "Unexpected nullptr expr in the aligned map");
@@ -21650,9 +21648,7 @@ SemaOpenMP::ActOnOpenMPDeclareReductionDirectiveStart(
 while (Filter.hasNext()) {
   auto *PrevDecl = cast(Filter.next());
   if (InCompoundScope) {
-auto I = UsedAsPrevious.find(PrevDecl);
-if (I == UsedAsPrevious.end())
-  UsedAsPrevious[PrevDecl] = false;
+UsedAsPrevious.try_emplace(PrevDecl, false);
 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
   UsedAsPrevious[D] = true;
   }
@@ -21906,9 +21902,7 @@ SemaOpenMP::DeclGroupPtrTy 
SemaOpenMP::ActOnOpenMPDeclareMapperDirective(
 while (Filter.hasNext()) {
   auto *PrevDecl = cast(Filter.next());
   if (InCompoundScope) {
-auto I = UsedAsPrevious.find(PrevDecl);
-if (I == UsedAsPrevious.end())
-  UsedAsPrevious[PrevDecl] = false;
+UsedAsPrevious.try_emplace(PrevDecl, false);
 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
   UsedAsPrevious[D] = true;
   }



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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata updated 
https://github.com/llvm/llvm-project/pull/111228

>From 2e3d116613a7441b31036cf603d581db6e0afe9b Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Fri, 4 Oct 2024 08:00:11 -0700
Subject: [PATCH 1/2] [Basic] Avoid repeated hash lookups (NFC)

---
 clang/lib/Basic/TargetID.cpp | 13 ++---
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Basic/TargetID.cpp b/clang/lib/Basic/TargetID.cpp
index fa1bfec2aacb9c..18f649c7137d7d 100644
--- a/clang/lib/Basic/TargetID.cpp
+++ b/clang/lib/Basic/TargetID.cpp
@@ -92,11 +92,10 @@ parseTargetIDWithFormatCheckingOnly(llvm::StringRef 
TargetID,
 if (Sign != '+' && Sign != '-')
   return std::nullopt;
 bool IsOn = Sign == '+';
-auto Loc = FeatureMap->find(Feature);
+auto [Loc, Inserted] = FeatureMap->try_emplace(Feature, IsOn);
 // Each feature can only show up at most once in target ID.
-if (Loc != FeatureMap->end())
+if (!Inserted)
   return std::nullopt;
-(*FeatureMap)[Feature] = IsOn;
 Features = Splits.second;
   }
   return Processor;
@@ -147,15 +146,15 @@ getConflictTargetIDCombination(const 
std::set &TargetIDs) {
   struct Info {
 llvm::StringRef TargetID;
 llvm::StringMap Features;
+Info(llvm::StringRef TargetID, const llvm::StringMap &Features)
+: TargetID(TargetID), Features(Features) {}
   };
   llvm::StringMap FeatureMap;
   for (auto &&ID : TargetIDs) {
 llvm::StringMap Features;
 llvm::StringRef Proc = *parseTargetIDWithFormatCheckingOnly(ID, &Features);
-auto Loc = FeatureMap.find(Proc);
-if (Loc == FeatureMap.end())
-  FeatureMap[Proc] = Info{ID, Features};
-else {
+auto [Loc, Inserted] = FeatureMap.try_emplace(Proc, ID, Features);
+if (!Inserted) {
   auto &ExistingFeatures = Loc->second.Features;
   if (llvm::any_of(Features, [&](auto &F) {
 return ExistingFeatures.count(F.first()) == 0;

>From 53778b2f63ed276bf66073ebbcbeb3d8a61bfa22 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 5 Oct 2024 09:57:16 -0700
Subject: [PATCH 2/2] Remove an unused variable.

---
 clang/lib/Basic/TargetID.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang/lib/Basic/TargetID.cpp b/clang/lib/Basic/TargetID.cpp
index 18f649c7137d7d..b42d1f07013c26 100644
--- a/clang/lib/Basic/TargetID.cpp
+++ b/clang/lib/Basic/TargetID.cpp
@@ -92,9 +92,8 @@ parseTargetIDWithFormatCheckingOnly(llvm::StringRef TargetID,
 if (Sign != '+' && Sign != '-')
   return std::nullopt;
 bool IsOn = Sign == '+';
-auto [Loc, Inserted] = FeatureMap->try_emplace(Feature, IsOn);
 // Each feature can only show up at most once in target ID.
-if (!Inserted)
+if (!FeatureMap->try_emplace(Feature, IsOn).second)
   return std::nullopt;
 Features = Splits.second;
   }

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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Kazu Hirata via cfe-commits


@@ -92,11 +92,10 @@ parseTargetIDWithFormatCheckingOnly(llvm::StringRef 
TargetID,
 if (Sign != '+' && Sign != '-')
   return std::nullopt;
 bool IsOn = Sign == '+';
-auto Loc = FeatureMap->find(Feature);
+auto [Loc, Inserted] = FeatureMap->try_emplace(Feature, IsOn);

kazutakahirata wrote:

Thank you for pointing this out!

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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Kazu Hirata via cfe-commits

kazutakahirata wrote:

Please take a look.  Thanks!

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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Nikita Popov via cfe-commits

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

LGTM

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


[clang] [clang] Allow `pragma float_control(precise, *)` to... (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits


@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -disable-llvm-passes -emit-llvm -menable-no-infs 
-fapprox-func\
+// RUN: -funsafe-math-optimizations -fno-signed-zeros -mreassociate 
-freciprocal-math\
+// RUN: -ffp-contract=fast -ffast-math %s -o - | FileCheck %s
+
+float test_precise_off_select(int c) {
+#pragma float_control(precise, off)
+  return c ? 0.0f : 1.0f;
+}
+
+// CHECK-LABEL: test_precise_off_select
+// CHECK: select fast i1 {{%.+}}, float 0.00e+00, float 1.00e+00
+
+float test_precise_off_phi(int c, float t, float f) {
+#pragma float_control(precise, off)
+return c ? t : f;
+}
+
+// CHECK-LABEL: test_precise_off_phi
+// CHECK: phi fast float [ {{%.+}}, {{%.+}} ], [ {{%.+}}, {{%.+}} ]
+
+float test_precise_on_select(int c) {
+#pragma float_control(precise, on)
+return c ? 0.0f : 1.0f;
+}
+
+// CHECK-LABEL: test_precise_on_select
+// CHECK: select i1 {{%.+}}, float 0.00e+00, float 1.00e+00
+
+float test_precise_on_phi(int c, float t, float f) {
+#pragma float_control(precise, on)
+  return c ? t : f;
+}
+

echesakov wrote:

For "vector case" do you mean something along the lines of

```c
typedef float float2 __attribute__((ext_vector_type(2)));
typedef int int2 __attribute__((ext_vector_type(2)));

float2 foo(int2 c, float2 t, float2 f) {
#pragma float_control(precise, off)
return c ? t : f;
}
```

In this case, the expression would be codegen-d to a sequence of bitwise 
operations and these are not affected by fast-math flags

```llvm
; Function Attrs: noinline nounwind optnone
define <2 x float> @foo(<2 x i32> noundef %c, <2 x float> noundef %t, <2 x 
float> noundef %f) #0 {
entry:
  %c.addr = alloca <2 x i32>, align 8
  %t.addr = alloca <2 x float>, align 8
  %f.addr = alloca <2 x float>, align 8
  store <2 x i32> %c, ptr %c.addr, align 8
  store <2 x float> %t, ptr %t.addr, align 8
  store <2 x float> %f, ptr %f.addr, align 8
  %0 = load <2 x i32>, ptr %c.addr, align 8
  %1 = load <2 x float>, ptr %t.addr, align 8
  %2 = load <2 x float>, ptr %f.addr, align 8
  %3 = icmp slt <2 x i32> %0, zeroinitializer
  %sext = sext <2 x i1> %3 to <2 x i32>
  %4 = xor <2 x i32> %sext, 
  %5 = bitcast <2 x float> %2 to <2 x i32>
  %6 = bitcast <2 x float> %1 to <2 x i32>
  %7 = and <2 x i32> %5, %4
  %8 = and <2 x i32> %6, %sext
  %cond = or <2 x i32> %7, %8
  %9 = bitcast <2 x i32> %cond to <2 x float>
  ret <2 x float> %9
}
```

Not really sure what I will be testing here?

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


[clang] [clang][bytecode] Handle UETT_OpenMPRequiredSimdAlign (PR #111259)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-arm64-windows-msvc` 
running on `linaro-armv8-windows-msvc-04` while building `clang` at step 5 
"ninja check 1".

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


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

```
Step 5 (ninja check 1) failure: stage 1 checked (failure)
 TEST 'Clang :: AST/ByteCode/builtins.cpp' FAILED 

Exit Code: 1

Command Output (stdout):
--
# RUN: at line 1
c:\users\tcwg\llvm-worker\clang-arm64-windows-msvc\stage1\bin\clang.exe -cc1 
-internal-isystem 
C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\stage1\lib\clang\20\include 
-nostdsysteminc -fexperimental-new-constant-interpreter 
C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\llvm\clang\test\AST\ByteCode\builtins.cpp
 -Wno-constant-evaluated -verify -fms-extensions
# executed command: 
'c:\users\tcwg\llvm-worker\clang-arm64-windows-msvc\stage1\bin\clang.exe' -cc1 
-internal-isystem 
'C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\stage1\lib\clang\20\include'
 -nostdsysteminc -fexperimental-new-constant-interpreter 
'C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\llvm\clang\test\AST\ByteCode\builtins.cpp'
 -Wno-constant-evaluated -verify -fms-extensions
# .---command stderr
# | error: 'expected-error' diagnostics seen but not expected: 
# |   File 
C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\llvm\clang\test\AST\ByteCode\builtins.cpp
 Line 40: static assertion failed due to requirement 
'__builtin_omp_required_simd_align(int) != 0'
# | error: 'expected-note' diagnostics seen but not expected: 
# |   File 
C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\llvm\clang\test\AST\ByteCode\builtins.cpp
 Line 40: expression evaluates to '0 != 0'
# | 2 errors generated.
# `-
# error: command failed with exit status: 1

--




```



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


[clang] [clang] Allow `pragma float_control(precise, *)` to... (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits


@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -disable-llvm-passes -emit-llvm -menable-no-infs 
-fapprox-func\
+// RUN: -funsafe-math-optimizations -fno-signed-zeros -mreassociate 
-freciprocal-math\
+// RUN: -ffp-contract=fast -ffast-math %s -o - | FileCheck %s

echesakov wrote:

These flags correspond to how the clang driver `-ffast-math` are expanded to 
the individual flags passed to `-cc1`.

Several tests (e.g. `clang/test/Parser/fp-floatcontrol-syntax.cpp` and 
`clang/test/CodeGen/math-errno.c`) use similar command lines for testing 
fast-path behavior and I was trying to be consistent with them.

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


[clang] [clang] Allow `pragma float_control(precise, *)` to... (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

https://github.com/echesakov updated 
https://github.com/llvm/llvm-project/pull/105912

>From 124a1c4c7c102421b74eaaa1133ea58a9017e07b Mon Sep 17 00:00:00 2001
From: Egor Chesakov <5292656+echesa...@users.noreply.github.com>
Date: Fri, 23 Aug 2024 18:44:14 -0700
Subject: [PATCH 1/2] [clang] Allow `pragma float_control(precise, *)` to...

...control `FastMathFlags` during code-generation of `ConditionalOperator`.

This involves storing `FPOptionsOverride` in trailing storage of
`ConditionalOperator` and storing `CurFPOptionsOverride` when creating
an AST node.

Fixes #84648
---
 clang/include/clang/AST/Expr.h| 67 +--
 clang/include/clang/AST/Stmt.h| 11 +++
 clang/include/clang/AST/TextNodeDumper.h  |  1 +
 clang/lib/AST/ASTImporter.cpp |  6 +-
 clang/lib/AST/Expr.cpp| 22 ++
 clang/lib/AST/TextNodeDumper.cpp  |  5 ++
 clang/lib/CodeGen/CGExprScalar.cpp|  2 +
 .../Frontend/Rewrite/RewriteModernObjC.cpp|  7 +-
 clang/lib/Frontend/Rewrite/RewriteObjC.cpp| 13 ++--
 clang/lib/Sema/SemaExpr.cpp   |  6 +-
 clang/lib/Sema/SemaOpenMP.cpp | 12 ++--
 clang/lib/Serialization/ASTReaderStmt.cpp |  8 ++-
 clang/lib/Serialization/ASTWriterStmt.cpp |  3 +
 clang/test/AST/conditional-operator.c | 21 ++
 clang/test/CodeGen/conditional-operator.c | 36 ++
 15 files changed, 193 insertions(+), 27 deletions(-)
 create mode 100644 clang/test/AST/conditional-operator.c
 create mode 100644 clang/test/CodeGen/conditional-operator.c

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 7bacf028192c65..cc79496e809829 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4210,26 +4210,45 @@ class AbstractConditionalOperator : public Expr {
 
 /// ConditionalOperator - The ?: ternary operator.  The GNU "missing
 /// middle" extension is a BinaryConditionalOperator.
-class ConditionalOperator : public AbstractConditionalOperator {
+class ConditionalOperator final
+: public AbstractConditionalOperator,
+  llvm::TrailingObjects {
   enum { COND, LHS, RHS, END_EXPR };
   Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
 
   friend class ASTStmtReader;
-public:
+
   ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
   SourceLocation CLoc, Expr *rhs, QualType t,
-  ExprValueKind VK, ExprObjectKind OK)
+  ExprValueKind VK, ExprObjectKind OK,
+  FPOptionsOverride FPFeatures)
   : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
 CLoc) {
 SubExprs[COND] = cond;
 SubExprs[LHS] = lhs;
 SubExprs[RHS] = rhs;
+ConditionalOperatorBits.HasFPFeatures =
+FPFeatures.requiresTrailingStorage();
+if (hasStoredFPFeatures())
+  setStoredFPFeatures(FPFeatures);
 setDependence(computeDependence(this));
   }
 
   /// Build an empty conditional operator.
-  explicit ConditionalOperator(EmptyShell Empty)
-: AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
+  ConditionalOperator(EmptyShell Empty, bool HasFPFeatures)
+  : AbstractConditionalOperator(ConditionalOperatorClass, Empty) {
+ConditionalOperatorBits.HasFPFeatures = HasFPFeatures;
+  }
+
+public:
+  static ConditionalOperator *CreateEmpty(const ASTContext &C, EmptyShell 
Empty,
+  bool HasFPFeatures);
+
+  static ConditionalOperator *Create(const ASTContext &C, Expr *cond,
+ SourceLocation QLoc, Expr *lhs,
+ SourceLocation CLoc, Expr *rhs, QualType 
t,
+ ExprValueKind VK, ExprObjectKind OK,
+ FPOptionsOverride FPFeatures);
 
   /// getCond - Return the expression representing the condition for
   ///   the ?: operator.
@@ -4265,6 +4284,44 @@ class ConditionalOperator : public 
AbstractConditionalOperator {
   const_child_range children() const {
 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
   }
+
+  /// Is FPFeatures in trailing storage?
+  bool hasStoredFPFeatures() const {
+return ConditionalOperatorBits.HasFPFeatures;
+  }
+  /// Get FPFeatures from trailing storage.
+  FPOptionsOverride getStoredFPFeatures() const {
+return *getTrailingFPFeatures();
+  }
+
+  // Get the FP features status of this operator. Only meaningful for
+  // operations on floating point types.
+  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
+if (hasStoredFPFeatures())
+  return getStoredFPFeatures().applyOverrides(LO);
+return FPOptions::defaultWithoutTrailingStorage(LO);
+  }
+  FPOptionsOverride getFPFeatures() const {
+return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
+  }
+
+

[clang] [clang] Allow `pragma float_control(precise, *)` to... (PR #105912)

2024-10-05 Thread Egor Chesakov via cfe-commits

echesakov wrote:

> Not very clear to me what the issue is. Can you please explain this in the 
> description. I think here the `#pragma float_control(precise, on)` should be 
> taking precedence over the `-ffast-math` flag and it's not. Right?

@zahiraam Correct, this is not happening right now and flags on codegen-d 
`select`/`phi` are not taking into account the pragma.

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread Chris Apple via cfe-commits

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

LGTM

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread Chris Apple via cfe-commits


@@ -58,31 +58,71 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
 non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error if any function attributed with

cjappl wrote:

nit, take or leave: "raise an error at run time" - to differentiate between 
compile time. 

Author's choice on whether or not to change it, may be obvious from the rest of 
the context

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread Chris Apple via cfe-commits

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread via cfe-commits

https://github.com/davidtrevelyan updated 
https://github.com/llvm/llvm-project/pull/111249

>From cb9d14bf2341f8570f29124ec26460811aa9eba9 Mon Sep 17 00:00:00 2001
From: David Trevelyan 
Date: Sat, 5 Oct 2024 12:34:23 +0100
Subject: [PATCH 1/2] [NFC][rtsan] Update docs to include [[clang::blocking]]

---
 clang/docs/RealtimeSanitizer.rst | 80 
 1 file changed, 60 insertions(+), 20 deletions(-)

diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 3f96267603aefa..c3beefce4018c1 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -9,7 +9,7 @@ Introduction
 
 RealtimeSanitizer (a.k.a. RTSan) is a real-time safety testing tool for C and 
C++
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
-that are not safe for use in functions with deterministic runtime requirements.
+that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
 to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
 ``pthread_mutex_lock``, or anything else that could have a non-deterministic
@@ -58,7 +58,7 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
@@ -66,23 +66,63 @@ non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error if any function attributed with
+``[[clang::blocking]]`` is called in a ``[[clang::nonblocking]]`` context.
+
+.. code-block:: console
+
+$ cat example_blocking_violation.cpp
+#include 
+#include 
+
+std::atomic has_permission{false};
+
+int wait_for_permission() [[clang::blocking]] {
+  while (has_permission.load() == false)
+std::this_thread::yield();
+  return 0;
+}
+
+int real_time_function() [[clang::nonblocking]] {
+  return wait_for_permission();
+}
+
+int main() {
+  return real_time_function();
+}
+
+$ clang++ -fsanitize=realtime example_blocking_violation.cpp && ./a.out
+==76131==ERROR: RealtimeSanitizer: blocking-call
+Call to blocking function `wait_for_permission()` in real-time context!
+#0 0x0001000c3db0 in wait_for_permission()+0x10 
(a.out:arm64+0x13db0)
+#1 0x0001000c3e3c in real_time_function()+0x10 
(a.out:arm64+0x13e3c)
+#2 0x0001000c3e68 in main+0x10 (a.out:arm64+0x13e68)
+#

[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread via cfe-commits


@@ -58,31 +58,71 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
 non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error if any function attributed with

davidtrevelyan wrote:

Agreed - "at run time" is a good addition - thanks

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/111267

…on templates

When instantiating a class template, we would lose track of function template 
explicit specializations, marking them with the wrong specialization kind.

This would lead to improperly using the explcit specialization arguments to 
instantiate the function body.

This also better matches MSVC on the behaviour of explicitly vs implicitly 
instantiating these.

Fixes #111266

>From 58d4f7e9dd8a9861b8cb73d13b07e81d3c09ae7d Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 17:01:53 -0300
Subject: [PATCH] [clang] Don't lose track of explicit specializations of
 member function templates

When instantiating a class template, we would lose track of function
template explicit specializations, marking them with the wrong
specialization kind.

This would lead to improperly using the explcit specialization arguments
to instantiate the function body.

This also better matches MSVC on the behaviour of explicitly vs
implicitly instantiating these.

Fixes #111266
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 16 -
 ...ms-function-specialization-class-scope.cpp | 34 +--
 3 files changed, 39 insertions(+), 13 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 44d5f348ed2d54..ba5620deae4395 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -471,6 +471,8 @@ Bug Fixes to C++ Support
 - Fixed an issue deducing non-type template arguments of reference type. 
(#GH73460)
 - Fixed an issue in constraint evaluation, where type constraints on the 
lambda expression
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
+- Fixes crashes with function template member specializations, and increases
+  conformance of explicit instantiation behaviour with MSVC. (#GH111266)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
 
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 898255ff7c6a32..4ce47d8c1ee761 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -4206,18 +4206,14 @@ Sema::InstantiateClassMembers(SourceLocation 
PointOfInstantiation,
 if (Function->hasAttr())
   continue;
 
-MemberSpecializationInfo *MSInfo =
-Function->getMemberSpecializationInfo();
-assert(MSInfo && "No member specialization information?");
-if (MSInfo->getTemplateSpecializationKind()
- == TSK_ExplicitSpecialization)
+TemplateSpecializationKind PrevTSK =
+Function->getTemplateSpecializationKind();
+if (PrevTSK == TSK_ExplicitSpecialization)
   continue;
 
-if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
-   Function,
-
MSInfo->getTemplateSpecializationKind(),
-  
MSInfo->getPointOfInstantiation(),
-   SuppressNew) ||
+if (CheckSpecializationInstantiationRedecl(
+PointOfInstantiation, TSK, Function, PrevTSK,
+Function->getPointOfInstantiation(), SuppressNew) ||
 SuppressNew)
   continue;
 
diff --git a/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp 
b/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
index e1f3ab37ad947c..aacc092c2c66ca 100644
--- a/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
+++ b/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
@@ -156,7 +156,13 @@ namespace UsesThis {
 auto h() -> decltype(this); // expected-error {{'this' cannot be used 
in a static member function declaration}}
   };
 
-  template struct A; // expected-note 3{{in instantiation of}}
+  template struct A; // expected-note {{in instantiation of}}
+  template<> template<> void A::f();
+  template<> template<> void A::g();
+  void test1() {
+A().f(); // expected-note {{in instantiation of}}
+A().g(); // expected-note {{in instantiation of}}
+  }
 
   template 
   struct Foo {
@@ -390,7 +396,12 @@ namespace UsesThis {
 }
   };
 
-  template struct D; // expected-note 2{{in instantiation of}}
+  template struct D;
+
+  void test2() {
+D().non_static_spec(0); // expected-note {{in instantiation of}}
+D().static_spec(0); // expected-note {{in instantiation of}}
+  }
 
   template
   struct E : T {
@@ -574,6 +585,23 @@ namespace UsesThis {
 }
   };
 
-  template struct E; // expected-note 2{{in instantiation of}}
+  template struct E;
 
+  void test3() {
+E().n

[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matheus Izvekov (mizvekov)


Changes

…on templates

When instantiating a class template, we would lose track of function template 
explicit specializations, marking them with the wrong specialization kind.

This would lead to improperly using the explcit specialization arguments to 
instantiate the function body.

This also better matches MSVC on the behaviour of explicitly vs implicitly 
instantiating these.

Fixes #111266

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+6-10) 
- (modified) clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp 
(+31-3) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 44d5f348ed2d54..ba5620deae4395 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -471,6 +471,8 @@ Bug Fixes to C++ Support
 - Fixed an issue deducing non-type template arguments of reference type. 
(#GH73460)
 - Fixed an issue in constraint evaluation, where type constraints on the 
lambda expression
   containing outer unexpanded parameters were not correctly expanded. 
(#GH101754)
+- Fixes crashes with function template member specializations, and increases
+  conformance of explicit instantiation behaviour with MSVC. (#GH111266)
 - Fixed a bug in constraint expression comparison where the ``sizeof...`` 
expression was not handled properly
   in certain friend declarations. (#GH93099)
 
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 898255ff7c6a32..4ce47d8c1ee761 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -4206,18 +4206,14 @@ Sema::InstantiateClassMembers(SourceLocation 
PointOfInstantiation,
 if (Function->hasAttr())
   continue;
 
-MemberSpecializationInfo *MSInfo =
-Function->getMemberSpecializationInfo();
-assert(MSInfo && "No member specialization information?");
-if (MSInfo->getTemplateSpecializationKind()
- == TSK_ExplicitSpecialization)
+TemplateSpecializationKind PrevTSK =
+Function->getTemplateSpecializationKind();
+if (PrevTSK == TSK_ExplicitSpecialization)
   continue;
 
-if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
-   Function,
-
MSInfo->getTemplateSpecializationKind(),
-  
MSInfo->getPointOfInstantiation(),
-   SuppressNew) ||
+if (CheckSpecializationInstantiationRedecl(
+PointOfInstantiation, TSK, Function, PrevTSK,
+Function->getPointOfInstantiation(), SuppressNew) ||
 SuppressNew)
   continue;
 
diff --git a/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp 
b/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
index e1f3ab37ad947c..aacc092c2c66ca 100644
--- a/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
+++ b/clang/test/SemaTemplate/ms-function-specialization-class-scope.cpp
@@ -156,7 +156,13 @@ namespace UsesThis {
 auto h() -> decltype(this); // expected-error {{'this' cannot be used 
in a static member function declaration}}
   };
 
-  template struct A; // expected-note 3{{in instantiation of}}
+  template struct A; // expected-note {{in instantiation of}}
+  template<> template<> void A::f();
+  template<> template<> void A::g();
+  void test1() {
+A().f(); // expected-note {{in instantiation of}}
+A().g(); // expected-note {{in instantiation of}}
+  }
 
   template 
   struct Foo {
@@ -390,7 +396,12 @@ namespace UsesThis {
 }
   };
 
-  template struct D; // expected-note 2{{in instantiation of}}
+  template struct D;
+
+  void test2() {
+D().non_static_spec(0); // expected-note {{in instantiation of}}
+D().static_spec(0); // expected-note {{in instantiation of}}
+  }
 
   template
   struct E : T {
@@ -574,6 +585,23 @@ namespace UsesThis {
 }
   };
 
-  template struct E; // expected-note 2{{in instantiation of}}
+  template struct E;
 
+  void test3() {
+E().non_static_spec(0); // expected-note {{in instantiation of}}
+E().static_spec(0); // expected-note {{in instantiation of}}
+  }
 }
+
+namespace GH111266 {
+  template struct S {
+template auto foo();
+template<> auto foo<1>() {
+  return [](auto x) { return x; };
+}
+  };
+  template struct S;
+  void test() {
+S().foo<1>();
+  }
+} // namespace GH111266

``




https://github.com/llvm/llvm-project/pull/111267
___
cfe-commits mailing list
cfe-commits@lists.l

[clang] 47e6d18 - [NFC][rtsan] Update docs to include [[clang::blocking]] (#111249)

2024-10-05 Thread via cfe-commits

Author: davidtrevelyan
Date: 2024-10-05T13:46:32-07:00
New Revision: 47e6d1816251e90b3d589710c5203a92c6015a7c

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

LOG: [NFC][rtsan] Update docs to include [[clang::blocking]] (#111249)

Updates the RealtimeSanitizer documentation to:

- include information about how to use `[[clang::blocking]]`, and
- update the displayed error messages to the latest style

Added: 


Modified: 
clang/docs/RealtimeSanitizer.rst

Removed: 




diff  --git a/clang/docs/RealtimeSanitizer.rst 
b/clang/docs/RealtimeSanitizer.rst
index 3f96267603aefa..103842e055db70 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -9,7 +9,7 @@ Introduction
 
 RealtimeSanitizer (a.k.a. RTSan) is a real-time safety testing tool for C and 
C++
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
-that are not safe for use in functions with deterministic runtime requirements.
+that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
 to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
 ``pthread_mutex_lock``, or anything else that could have a non-deterministic
@@ -58,7 +58,7 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
@@ -66,23 +66,63 @@ non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error at run time if any function attributed
+with ``[[clang::blocking]]`` is called in a ``[[clang::nonblocking]]`` context.
+
+.. code-block:: console
+
+$ cat example_blocking_violation.cpp
+#include 
+#include 
+
+std::atomic has_permission{false};
+
+int wait_for_permission() [[clang::blocking]] {
+  while (has_permission.load() == false)
+std::this_thread::yield();
+  return 0;
+}
+
+int real_time_function() [[clang::nonblocking]] {
+  return wait_for_permission();
+}
+
+int main() {
+  return real_time_function();
+}
+
+$ clang++ -fsanitize=realtime example_blocking_violation.cpp && ./a.out
+==76131==ERROR: RealtimeSanitizer: blocking-call
+Call to blocking function

[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread Chris Apple via cfe-commits

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

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

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


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

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

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

[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Matheus Izvekov via cfe-commits


@@ -5185,9 +5189,24 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
 RebuildTypeSourceInfoForDefaultSpecialMembers();
 SetDeclDefaulted(Function, PatternDecl->getLocation());
   } else {
+NamedDecl *ND = Function;
+std::optional> Innermost;
+if (auto *Primary = Function->getPrimaryTemplate();
+Primary &&
+!isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) {
+  ND = *llvm::find_if(Primary->redecls(),
+  [](const RedeclarableTemplateDecl *RTD) {
+auto *FTD = cast(RTD);
+return FTD->isInstantiatedFromDefinition() ||
+   FTD->isThisDeclarationADefinition();
+  });

mizvekov wrote:

We are finding one declaration within all the redeclarations of the primary 
template.
The list of redeclarations can't have a null element in it.

Otherwise, if you meant a null iterator, we shouldn't get here without a 
definition, as we should have diagnosed that before.
We could perhaps add a null check for that. Is that what you meant?

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Matheus Izvekov via cfe-commits


@@ -492,8 +489,10 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 // has a depth of 0.
 if (const auto *TTP = dyn_cast(CurDecl))
   HandleDefaultTempArgIntoTempTempParam(TTP, Result);
-CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
-  }
+CurDecl = DC ? Decl::castFromDeclContext(DC)
+ : Response::UseNextDecl(CurDecl).NextDecl;

mizvekov wrote:

In this case, we don't even have the real function declaration that we want to 
start with, so I am afraid this is too much of an special case  to handle 
within `getTemplateInstantiationArgs()`.

I think the best way to handle this one is to have one overload of 
`getTemplateInstantiationArgs` which takes an initial MLTAL, and just adds more 
template arguments on top of it.

Yeah, I am planning on holding this off a little bit until the refactoring 
lands.

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Younan Zhang via cfe-commits


@@ -4206,18 +4206,14 @@ Sema::InstantiateClassMembers(SourceLocation 
PointOfInstantiation,
 if (Function->hasAttr())
   continue;
 
-MemberSpecializationInfo *MSInfo =
-Function->getMemberSpecializationInfo();
-assert(MSInfo && "No member specialization information?");
-if (MSInfo->getTemplateSpecializationKind()
- == TSK_ExplicitSpecialization)
+TemplateSpecializationKind PrevTSK =
+Function->getTemplateSpecializationKind();
+if (PrevTSK == TSK_ExplicitSpecialization)
   continue;

zyn0217 wrote:

IIUC the new behavior handles `DependentFunctionTemplateSpecializationInfo` as 
well, right?

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Younan Zhang via cfe-commits

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

Makes sense to me, but I'd like to @erichkeane to have a look as well.

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Younan Zhang via cfe-commits

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Younan Zhang via cfe-commits


@@ -156,7 +156,13 @@ namespace UsesThis {
 auto h() -> decltype(this); // expected-error {{'this' cannot be used 
in a static member function declaration}}
   };
 
-  template struct A; // expected-note 3{{in instantiation of}}
+  template struct A; // expected-note {{in instantiation of}}
+  template<> template<> void A::f();
+  template<> template<> void A::g();
+  void test1() {
+A().f(); // expected-note {{in instantiation of}}
+A().g(); // expected-note {{in instantiation of}}
+  }

zyn0217 wrote:

There weren't test failures here, right?
(Changes here are hopefully not hiding the failures)

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Younan Zhang via cfe-commits


@@ -5185,9 +5189,24 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
 RebuildTypeSourceInfoForDefaultSpecialMembers();
 SetDeclDefaulted(Function, PatternDecl->getLocation());
   } else {
+NamedDecl *ND = Function;
+std::optional> Innermost;
+if (auto *Primary = Function->getPrimaryTemplate();
+Primary &&
+!isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) {
+  ND = *llvm::find_if(Primary->redecls(),
+  [](const RedeclarableTemplateDecl *RTD) {
+auto *FTD = cast(RTD);
+return FTD->isInstantiatedFromDefinition() ||
+   FTD->isThisDeclarationADefinition();
+  });

zyn0217 wrote:

Oh yeah, I think I was saying the iterator shouldn't be null.


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


[clang] clang-format: Add AlignFunctionDeclarations attribute to AlignConsecutiveDeclarations (PR #108241)

2024-10-05 Thread Brad House via cfe-commits

bradh352 wrote:

ping

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


[clang] [clang] Track function template instantiation from definition (PR #110387)

2024-10-05 Thread Matheus Izvekov via cfe-commits


@@ -1994,8 +1995,10 @@ 
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   // Link the instantiation back to the pattern *unless* this is a
   // non-definition friend declaration.
   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
-  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
+  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) {
+InstTemplate->setInstantiatedFromDefinition();

mizvekov wrote:

That's true, but the only problematic cases are the friends.

We could make the flag more accurate, as named, for non-friends, but then we 
don't have a motivation, and we would make searching for a declaration which is 
compatible with the definition slightly more expensive for those.

Another option is to rename the flag to something like 
`InstantiatedFromDefinitionForFriend`.

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Matheus Izvekov via cfe-commits


@@ -156,7 +156,13 @@ namespace UsesThis {
 auto h() -> decltype(this); // expected-error {{'this' cannot be used 
in a static member function declaration}}
   };
 
-  template struct A; // expected-note 3{{in instantiation of}}
+  template struct A; // expected-note {{in instantiation of}}
+  template<> template<> void A::f();
+  template<> template<> void A::g();
+  void test1() {
+A().f(); // expected-note {{in instantiation of}}
+A().g(); // expected-note {{in instantiation of}}
+  }

mizvekov wrote:

No, we are still producing the same bunch of diagnostics, except now only when 
we use the function, instead of when instantiating the enclosing class.
This matches the behavior of MSVC.

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


[clang] [clang] Don't lose track of explicit specializations of member functi… (PR #111267)

2024-10-05 Thread Matheus Izvekov via cfe-commits


@@ -4206,18 +4206,14 @@ Sema::InstantiateClassMembers(SourceLocation 
PointOfInstantiation,
 if (Function->hasAttr())
   continue;
 
-MemberSpecializationInfo *MSInfo =
-Function->getMemberSpecializationInfo();
-assert(MSInfo && "No member specialization information?");
-if (MSInfo->getTemplateSpecializationKind()
- == TSK_ExplicitSpecialization)
+TemplateSpecializationKind PrevTSK =
+Function->getTemplateSpecializationKind();
+if (PrevTSK == TSK_ExplicitSpecialization)
   continue;

mizvekov wrote:

I don't think that would matter, unless the assert above was wrong, as the 
`DependentFunctionTemplateSpecializationInfo` case is handled in the fallback 
path, when `MSInfo` is null.

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


[clang] [Driver] Avoid repeated hash lookups (NFC) (PR #111225)

2024-10-05 Thread Nikita Popov via cfe-commits

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

LGTM

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


[clang] [Sema] Avoid repeated hash lookups (NFC) (PR #111227)

2024-10-05 Thread Nikita Popov via cfe-commits

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

LGTM

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


[clang] [Basic] Avoid repeated hash lookups (NFC) (PR #111228)

2024-10-05 Thread Nikita Popov via cfe-commits


@@ -92,11 +92,10 @@ parseTargetIDWithFormatCheckingOnly(llvm::StringRef 
TargetID,
 if (Sign != '+' && Sign != '-')
   return std::nullopt;
 bool IsOn = Sign == '+';
-auto Loc = FeatureMap->find(Feature);
+auto [Loc, Inserted] = FeatureMap->try_emplace(Feature, IsOn);

nikic wrote:

Loc not used?

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


[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread via cfe-commits

https://github.com/davidtrevelyan created 
https://github.com/llvm/llvm-project/pull/111249

Updates the RealtimeSanitizer documentation to:

- include information about how to use `[[clang::blocking]]`, and
- update the displayed error messages to the latest style

@cjappl for review 

>From cb9d14bf2341f8570f29124ec26460811aa9eba9 Mon Sep 17 00:00:00 2001
From: David Trevelyan 
Date: Sat, 5 Oct 2024 12:34:23 +0100
Subject: [PATCH] [NFC][rtsan] Update docs to include [[clang::blocking]]

---
 clang/docs/RealtimeSanitizer.rst | 80 
 1 file changed, 60 insertions(+), 20 deletions(-)

diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 3f96267603aefa..c3beefce4018c1 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -9,7 +9,7 @@ Introduction
 
 RealtimeSanitizer (a.k.a. RTSan) is a real-time safety testing tool for C and 
C++
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
-that are not safe for use in functions with deterministic runtime requirements.
+that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
 to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
 ``pthread_mutex_lock``, or anything else that could have a non-deterministic
@@ -58,7 +58,7 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
@@ -66,23 +66,63 @@ non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error if any function attributed with
+``[[clang::blocking]]`` is called in a ``[[clang::nonblocking]]`` context.
+
+.. code-block:: console
+
+$ cat example_blocking_violation.cpp
+#include 
+#include 
+
+std::atomic has_permission{false};
+
+int wait_for_permission() [[clang::blocking]] {
+  while (has_permission.load() == false)
+std::this_thread::yield();
+  return 0;
+}
+
+int real_time_function() [[clang::nonblocking]] {
+  return wait_for_permission();
+}
+
+int main() {
+  return real_time_function();
+}
+
+$ clang++ -fsanitize=realtime example_blocking_violation.cpp && ./a.out
+==76131==ERROR: RealtimeSanitizer: blocking-call
+Call to blocking function `wait_for_permission()` in real-time context!
+#0 0x0001000c3db0 in wait_for_permission()+

[clang] [NFC][rtsan] Update docs to include [[clang::blocking]] (PR #111249)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (davidtrevelyan)


Changes

Updates the RealtimeSanitizer documentation to:

- include information about how to use `[[clang::blocking]]`, and
- update the displayed error messages to the latest style

@cjappl for review 

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


1 Files Affected:

- (modified) clang/docs/RealtimeSanitizer.rst (+60-20) 


``diff
diff --git a/clang/docs/RealtimeSanitizer.rst b/clang/docs/RealtimeSanitizer.rst
index 3f96267603aefa..c3beefce4018c1 100644
--- a/clang/docs/RealtimeSanitizer.rst
+++ b/clang/docs/RealtimeSanitizer.rst
@@ -9,7 +9,7 @@ Introduction
 
 RealtimeSanitizer (a.k.a. RTSan) is a real-time safety testing tool for C and 
C++
 projects. RTSan can be used to detect real-time violations, i.e. calls to 
methods
-that are not safe for use in functions with deterministic runtime requirements.
+that are not safe for use in functions with deterministic run time 
requirements.
 RTSan considers any function marked with the ``[[clang::nonblocking]]`` 
attribute
 to be a real-time function. If RTSan detects a call to ``malloc``, ``free``,
 ``pthread_mutex_lock``, or anything else that could have a non-deterministic
@@ -58,7 +58,7 @@ code.
  return 0;
}
# Compile and link
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
 
 If a real-time safety violation is detected in a ``[[clang::nonblocking]]``
 context, or any function invoked by that function, the program will exit with a
@@ -66,23 +66,63 @@ non-zero exit code.
 
 .. code-block:: console
 
-   % clang++ -fsanitize=realtime -g example_realtime_violation.cpp
+   % clang++ -fsanitize=realtime example_realtime_violation.cpp
% ./a.out
-   Real-time violation: intercepted call to real-time unsafe function `malloc` 
in real-time context! Stack trace:
-#0 0x000102893034 in __rtsan::PrintStackTrace() rtsan_stack.cpp:45
-#1 0x000102892e64 in __rtsan::Context::ExpectNotRealtime(char const*) 
rtsan_context.cpp:78
-#2 0x00010289397c in malloc rtsan_interceptors.cpp:286
-#3 0x000195bd7bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
-#4 0x5c7f00010230f07c  ()
-#5 0x00010230f058 in std::__1::__libcpp_allocate[abi:ue170006](unsigned 
long, unsigned long) new:324
-#6 0x00010230effc in 
std::__1::allocator::allocate[abi:ue170006](unsigned long) 
allocator.h:114
-... snip ...
-#10 0x00010230e4bc in std::__1::vector>::__append(unsigned long) vector:1162
-#11 0x00010230dcdc in std::__1::vector>::resize(unsigned long) vector:1981
-#12 0x00010230dc28 in violation() main.cpp:5
-#13 0x00010230dd64 in main main.cpp:9
-#14 0x0001958960dc  ()
-#15 0x2f557ffc  ()
+   ==76290==ERROR: RealtimeSanitizer: unsafe-library-call
+   Intercepted call to real-time unsafe function `malloc` in real-time context!
+   #0 0x000102a7b884 in malloc rtsan_interceptors.cpp:426
+   #1 0x00019c326bd0 in operator new(unsigned long)+0x1c 
(libc++abi.dylib:arm64+0x16bd0)
+   #2 0xa30d0001024f79a8  ()
+   #3 0x0001024f794c in std::__1::__libcpp_allocate[abi:ne20](unsigned 
long, unsigned long)+0x44
+   #4 0x0001024f78c4 in 
std::__1::allocator::allocate[abi:ne20](unsigned long)+0x44
+   ... snip ...
+   #9 0x0001024f6868 in std::__1::vector>::resize(unsigned long)+0x48
+   #10 0x0001024f67b4 in violation()+0x24
+   #11 0x0001024f68f0 in main+0x18 (a.out:arm64+0x128f0)
+   #12 0x00019bfe3150  ()
+   #13 0xed5efffc  ()
+
+
+Blocking functions
+--
+
+Calls to system library functions such as ``malloc`` are automatically caught 
by
+RealtimeSanitizer. Real-time programmers may also write their own blocking
+(real-time unsafe) functions that they wish RealtimeSanitizer to be aware of.
+RealtimeSanitizer will raise an error if any function attributed with
+``[[clang::blocking]]`` is called in a ``[[clang::nonblocking]]`` context.
+
+.. code-block:: console
+
+$ cat example_blocking_violation.cpp
+#include 
+#include 
+
+std::atomic has_permission{false};
+
+int wait_for_permission() [[clang::blocking]] {
+  while (has_permission.load() == false)
+std::this_thread::yield();
+  return 0;
+}
+
+int real_time_function() [[clang::nonblocking]] {
+  return wait_for_permission();
+}
+
+int main() {
+  return real_time_function();
+}
+
+$ clang++ -fsanitize=realtime example_blocking_violation.cpp && ./a.out
+==76131==ERROR: RealtimeSanitizer: blocking-call
+Call to blocking function `wait_for_permission()` in real-time context!
+#0 0x0001000c3db0 in wait_for_permission()+0x10 
(a.out:arm64+0x13db0)
+#1 0x0001000c3e3c in real_time_function()+0x10 
(a.out:arm64+0x13e3c)
+#2 0x0001000c3e68 in main+0x10 (a.out:arm64+0x13

[clang] [llvm] [HLSL] implement elementwise firstbithigh hlsl builtin (PR #111082)

2024-10-05 Thread Sarah Spall via cfe-commits

spall wrote:

> It is not correct to limit firstbithigh to 32 bit integers. There are a 
> couple of reasons that might make one think that it is, but we do in fact 
> want/need to support int16 and int64 here.
> 
> 1. The [HLSL 
> docs](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/firstbithigh)
>  only mention integer. Unfortunately that's true for most of these functions, 
> as many of these docs were not updated as 64 and 16 bit types gained support 
> in the language.
> 
If you click through the definition of Int it defines it to be 32 bits.
> 2. DXC's SPIR-V implementation doesn't handle 16- and 64-bit for these 
> functions. As noted in [Incorrect SPIR-V generated when `firstbithigh` is 
> used on a `uint64_t` 
> microsoft/DirectXShaderCompiler#4702](https://github.com/microsoft/DirectXShaderCompiler/issues/4702)
>  we decided not to implement those overloads in DXC, but should reconsider 
> this for clang.
> 
> 
> Despite all of this, DXC does indeed support 16- and 64-bit overloads, as 
> seen here: https://hlsl.godbolt.org/z/qbc17xz35
> 
> Note that the return type of the operation is not overloaded - all of the 
> overloads of this function return uint.

https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#firstbithi
FirstBitHi does explicitly mention only 32 bit integers. 

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


[clang] WIP Add suppress weak loop assumptions visitor (PR #111258)

2024-10-05 Thread Balazs Benics via cfe-commits

https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/111258

This is an alternative implementation of the idea present in #109804.

In this implementation, the suppression is purely implemented by a 
`BugReportVisitor`, to avoid coupling the suppression with the engine itself.
The idea is to visit the bug-path, and along the way record each time we 
entered the basic-block that has a comparison in the end that drives the 
decision of entering or avoiding a loop construct.

We also record expressions that caused a state-split. These are basically the 
expressions that eagerly assume would force a split on - but this approach 
works even if eager-assumptions are disabled.

Once we collected all the data, we go over the loops that we saw, and check if 
the condition of that loop construct was evaluated N times. This then triggers 
a heuristic to decide if we should suppress this, e.g. because we "assumed" not 
to enter the loop, or "assumed" to iterate more than 2 times in the loop.


---

This is WIP, because I just scratched the idea, but it seems to work good 
enough to have some discussion about this, while refining it if I have some 
time later.

>From c429df63af6cdeec7e721e8f9c322f1ac6ba3b3d Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sat, 5 Oct 2024 15:14:37 +0200
Subject: [PATCH 1/5] Use the eager assumption tags only if the decision was
 ambiguous

---
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  | 15 
 clang/test/Analysis/assuming-unsigned-ge-0.c  |  5 +---
 clang/test/Analysis/cast-value-notes.cpp  | 20 +++-
 clang/test/Analysis/cast-value-state-dump.cpp |  5 ++--
 .../std-c-library-functions-arg-constraints.c | 24 +++
 5 files changed, 29 insertions(+), 40 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index b1919d7027cf4d..62066632db87d0 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -3771,24 +3771,29 @@ void 
ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
 SVal V = state->getSVal(Ex, Pred->getLocationContext());
 std::optional SEV = V.getAs();
 if (SEV && SEV->isExpression()) {
-  const std::pair &tags =
-geteagerlyAssumeBinOpBifurcationTags();
-
   ProgramStateRef StateTrue, StateFalse;
   std::tie(StateTrue, StateFalse) = state->assume(*SEV);
 
+  const ProgramPointTag *EagerTrueTag = nullptr;
+  const ProgramPointTag *EagerFalseTag = nullptr;
+
+  // Use the eager assumption tags if the choice was ambiguous.
+  if (StateTrue && StateFalse)
+std::tie(EagerTrueTag, EagerFalseTag) =
+geteagerlyAssumeBinOpBifurcationTags();
+
   // First assume that the condition is true.
   if (StateTrue) {
 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
-Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
+Bldr.generateNode(Ex, Pred, StateTrue, EagerTrueTag);
   }
 
   // Next, assume that the condition is false.
   if (StateFalse) {
 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
-Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
+Bldr.generateNode(Ex, Pred, StateFalse, EagerFalseTag);
   }
 }
   }
diff --git a/clang/test/Analysis/assuming-unsigned-ge-0.c 
b/clang/test/Analysis/assuming-unsigned-ge-0.c
index 553e68cb96c6bd..18e637a6e5310e 100644
--- a/clang/test/Analysis/assuming-unsigned-ge-0.c
+++ b/clang/test/Analysis/assuming-unsigned-ge-0.c
@@ -2,10 +2,7 @@
 // RUN: -analyzer-checker=core -verify %s
 
 int assuming_unsigned_ge_0(unsigned arg) {
-  // TODO This testcase demonstrates the current incorrect behavior of Clang
-  // Static Analyzer: here 'arg' is unsigned, so "arg >= 0" is not a fresh
-  // assumption, but it still appears in the diagnostics as if it's fresh:
-  // expected-note@+2 {{Assuming 'arg' is >= 0}}
+  // expected-note@+2 {{'arg' is >= 0}}
   // expected-note@+1 {{Taking false branch}}
   if (arg < 0)
 return 0;
diff --git a/clang/test/Analysis/cast-value-notes.cpp 
b/clang/test/Analysis/cast-value-notes.cpp
index 7ee224dc6e5d8f..0235404e73adf6 100644
--- a/clang/test/Analysis/cast-value-notes.cpp
+++ b/clang/test/Analysis/cast-value-notes.cpp
@@ -168,9 +168,8 @@ void evalNonNullParamNonNullReturnReference(const Shape &S) 
{
 // expected-note@-2 {{Taking true branch}}
 
 (void)(1 / !C);
-// expected-note@-1 {{'C' is non-null}}
-// expected-note@-2 {{Division by zero}}
-// expected-warning@-3 {{Division by zero}}
+// expected-note@-1 {{Division by zero}}
+// expected-warning@-2 {{Division by zero}}
   }
 }
 
@@ -226,9 +225,8 @@ void evalNonNullParamNonNullReturn(const Shape *S) {
 // expected-not

[clang] WIP Add suppress weak loop assumptions visitor (PR #111258)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




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

Author: Balazs Benics (steakhal)


Changes

This is an alternative implementation of the idea present in #109804.

In this implementation, the suppression is purely implemented by a 
`BugReportVisitor`, to avoid coupling the suppression with the engine itself.
The idea is to visit the bug-path, and along the way record each time we 
entered the basic-block that has a comparison in the end that drives the 
decision of entering or avoiding a loop construct.

We also record expressions that caused a state-split. These are basically the 
expressions that eagerly assume would force a split on - but this approach 
works even if eager-assumptions are disabled.

Once we collected all the data, we go over the loops that we saw, and check if 
the condition of that loop construct was evaluated N times. This then triggers 
a heuristic to decide if we should suppress this, e.g. because we "assumed" not 
to enter the loop, or "assumed" to iterate more than 2 times in the loop.


---

This is WIP, because I just scratched the idea, but it seems to work good 
enough to have some discussion about this, while refining it if I have some 
time later.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp (+164-1) 
- (modified) clang/test/Analysis/out-of-bounds.c (+149-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index 3f837564cf47c4..aafd44d037273d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -11,18 +11,28 @@
 //
 
//===--===//
 
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/CharUnits.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/ProgramPoint.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Checkers/Taint.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
-#include "llvm/ADT/SmallString.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -32,6 +42,158 @@ using namespace ento;
 using namespace taint;
 using llvm::formatv;
 
+namespace {
+
+class SuppressReportsHavingWeakLoopAssumption : public BugReporterVisitor {
+public:
+  SuppressReportsHavingWeakLoopAssumption(const PathSensitiveBugReport &R)
+  : OrigCursor(R.getErrorNode()) {}
+
+private:
+  friend class BugReporterVisitor;
+
+  // The exploded node we are currently visiting, but in the original exploded
+  // graph. This graph is not trimmed, unlike the one we usually visit.
+  const ExplodedNode *OrigCursor;
+
+  llvm::DenseSet LoopsSeen;
+  llvm::DenseMap NumTimesTakenTrueDecision;
+  llvm::DenseMap NumTimesTakenFalseDecision;
+
+  void Profile(llvm::FoldingSetNodeID &ID) const final {
+static const bool Tag = 0;
+ID.AddPointer(&Tag);
+  }
+
+  static const ExplodedNode *selectMatchingPred(const ExplodedNode *OrigSucc,
+unsigned SoughtPredId) {
+auto MatchesSoughtId = [SoughtPredId](const ExplodedNode *N) {
+  return N->getID() == SoughtPredId;
+};
+auto It = llvm::find_if(OrigSucc->preds(), MatchesSoughtId);
+assert(It != OrigSucc->pred_end());
+return *It;
+  }
+
+  static bool isLoopAndNonNull(const Stmt *S) {
+return isa_and_nonnull(S);
+  }
+
+  void registerLoopStatements(const ExplodedNode *N) {
+if (auto Entrance = N->getLocation().getAs()) {
+  const Stmt *TermStmt = Entrance->getBlock()->getTerminatorStmt();
+  if (isLoopAndNonNull(TermStmt))
+LoopsSeen.insert(TermStmt);
+}
+  }
+
+  void registerOccurrence(llvm::DenseMap &Map,
+  const Expr *Key) {
+if (auto [Place, Inserted] = Map.try_emplace(Key, 1); !Inserted)
+  ++Place->second;
+  }
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ,
+   BugReporterContext &

[clang] [analyzer] Suppress out of bounds reports after weak loop assumptions (PR #109804)

2024-10-05 Thread Balazs Benics via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


steakhal wrote:

I implemented my idea of doing this suppression sole within a BugReport visitor 
in PR #111258. Let me know what do you think.

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Pavel Skripkin via cfe-commits

pskrgag wrote:

CI looks unrelated 

```
bk;t=1728134304433Failed Tests (1):

_bk;t=1728134304433  LLVM :: Transforms/InstCombine/and-or-icmps.ll
```

Should I re-trigger it just in case?

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


[clang] fba6c88 - [analyzer] Fix wrong `builtin_*_overflow` return type (#111253)

2024-10-05 Thread via cfe-commits

Author: Pavel Skripkin
Date: 2024-10-05T17:21:31+02:00
New Revision: fba6c887c110a501b311f6b01721eaf3a5dd994e

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

LOG: [analyzer] Fix wrong `builtin_*_overflow` return type (#111253)

`builtin_*_overflow` functions return `_Bool` according to [1].
`BuiltinFunctionChecker` was using `makeTruthVal` w/o specifying
explicit type, which creates an `int` value, since it's the type of any
compassion according to C standard.

Fix it by directly passing `BoolTy` to `makeTruthVal`

Closes: #47

[1]
https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
clang/test/Analysis/builtin_overflow.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index 69d8e968283b37..4ab0c4c9ae7b70 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -183,6 +183,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   ProgramStateRef State = C.getState();
   SValBuilder &SVB = C.getSValBuilder();
   const Expr *CE = Call.getOriginExpr();
+  auto BoolTy = C.getASTContext().BoolTy;
 
   SVal Arg1 = Call.getArgSVal(0);
   SVal Arg2 = Call.getArgSVal(1);
@@ -193,8 +194,8 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
-ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false));
+ProgramStateRef StateNoOverflow = State->BindExpr(
+CE, C.getLocationContext(), SVB.makeTruthVal(false, BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -212,9 +213,9 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   }
 
   if (Overflow) {
-C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true)),
-createBuiltinOverflowNoteTag(C));
+C.addTransition(State->BindExpr(CE, C.getLocationContext(),
+SVB.makeTruthVal(true, BoolTy)),
+createBuiltinOverflowNoteTag(C));
   }
 }
 

diff  --git a/clang/test/Analysis/builtin_overflow.c 
b/clang/test/Analysis/builtin_overflow.c
index 5c61795661d095..9d98ce7a1af45c 100644
--- a/clang/test/Analysis/builtin_overflow.c
+++ b/clang/test/Analysis/builtin_overflow.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -triple x86_64-unknown-unknown -verify %s \
-// RUN:   -analyzer-checker=core,debug.ExprInspection
+// RUN:   -analyzer-checker=core,debug.ExprInspection,alpha.core.BoolAssignment
 
 #define __UINT_MAX__ (__INT_MAX__ * 2U + 1U)
 #define __INT_MIN__  (-__INT_MAX__ - 1)
@@ -155,3 +155,12 @@ void test_uadd_overflow_contraints(unsigned a, unsigned b)
  return;
}
 }
+
+void test_bool_assign(void)
+{
+int res;
+
+// Reproduce issue from GH#47. __builtin_*_overflow funcions
+// should return _Bool, but not int.
+_Bool ret = __builtin_mul_overflow(10, 20, &res); // no crash
+}



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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Pavel Skripkin via cfe-commits

https://github.com/pskrgag created 
https://github.com/llvm/llvm-project/pull/111253

`builtin_*_overflow` functions return `_Bool` according to [1]. 
`BuiltinFunctionChecker` was using `makeTruthVal` for return type, which 
creates an `int` value, since it's the type of any compassion according to C 
standard.

Fix it by directly passing `BoolTy` to `makeTruthVal`

Closes: #47

[1] 
https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins

>From 4f5fc3e12747064b35c490e510c63702afc8a800 Mon Sep 17 00:00:00 2001
From: Pavel Skripkin 
Date: Sat, 5 Oct 2024 15:58:15 +0300
Subject: [PATCH] clang/csa: fix wrong __builtin_*_overflow return type

---
 .../Checkers/BuiltinFunctionChecker.cpp   |  5 +++--
 clang/test/Analysis/builtin_overflow.c| 11 ++-
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index 69d8e968283b37..d49f01898e2241 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -183,6 +183,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   ProgramStateRef State = C.getState();
   SValBuilder &SVB = C.getSValBuilder();
   const Expr *CE = Call.getOriginExpr();
+  auto BoolTy = C.getASTContext().BoolTy;
 
   SVal Arg1 = Call.getArgSVal(0);
   SVal Arg2 = Call.getArgSVal(1);
@@ -194,7 +195,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
 ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false));
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false, 
BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -213,7 +214,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   if (Overflow) {
 C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true)),
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true, 
BoolTy)),
 createBuiltinOverflowNoteTag(C));
   }
 }
diff --git a/clang/test/Analysis/builtin_overflow.c 
b/clang/test/Analysis/builtin_overflow.c
index 5c61795661d095..9d98ce7a1af45c 100644
--- a/clang/test/Analysis/builtin_overflow.c
+++ b/clang/test/Analysis/builtin_overflow.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -triple x86_64-unknown-unknown -verify %s \
-// RUN:   -analyzer-checker=core,debug.ExprInspection
+// RUN:   -analyzer-checker=core,debug.ExprInspection,alpha.core.BoolAssignment
 
 #define __UINT_MAX__ (__INT_MAX__ * 2U + 1U)
 #define __INT_MIN__  (-__INT_MAX__ - 1)
@@ -155,3 +155,12 @@ void test_uadd_overflow_contraints(unsigned a, unsigned b)
  return;
}
 }
+
+void test_bool_assign(void)
+{
+int res;
+
+// Reproduce issue from GH#47. __builtin_*_overflow funcions
+// should return _Bool, but not int.
+_Bool ret = __builtin_mul_overflow(10, 20, &res); // no crash
+}

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread via cfe-commits

llvmbot wrote:




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

Author: Pavel Skripkin (pskrgag)


Changes

`builtin_*_overflow` functions return `_Bool` according to [1]. 
`BuiltinFunctionChecker` was using `makeTruthVal` for return type, which 
creates an `int` value, since it's the type of any compassion according to C 
standard.

Fix it by directly passing `BoolTy` to `makeTruthVal`

Closes: #47

[1] 
https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
(+3-2) 
- (modified) clang/test/Analysis/builtin_overflow.c (+10-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index 69d8e968283b37..d49f01898e2241 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -183,6 +183,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   ProgramStateRef State = C.getState();
   SValBuilder &SVB = C.getSValBuilder();
   const Expr *CE = Call.getOriginExpr();
+  auto BoolTy = C.getASTContext().BoolTy;
 
   SVal Arg1 = Call.getArgSVal(0);
   SVal Arg2 = Call.getArgSVal(1);
@@ -194,7 +195,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
 ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false));
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false, 
BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -213,7 +214,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   if (Overflow) {
 C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true)),
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true, 
BoolTy)),
 createBuiltinOverflowNoteTag(C));
   }
 }
diff --git a/clang/test/Analysis/builtin_overflow.c 
b/clang/test/Analysis/builtin_overflow.c
index 5c61795661d095..9d98ce7a1af45c 100644
--- a/clang/test/Analysis/builtin_overflow.c
+++ b/clang/test/Analysis/builtin_overflow.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -triple x86_64-unknown-unknown -verify %s \
-// RUN:   -analyzer-checker=core,debug.ExprInspection
+// RUN:   -analyzer-checker=core,debug.ExprInspection,alpha.core.BoolAssignment
 
 #define __UINT_MAX__ (__INT_MAX__ * 2U + 1U)
 #define __INT_MIN__  (-__INT_MAX__ - 1)
@@ -155,3 +155,12 @@ void test_uadd_overflow_contraints(unsigned a, unsigned b)
  return;
}
 }
+
+void test_bool_assign(void)
+{
+int res;
+
+// Reproduce issue from GH#47. __builtin_*_overflow funcions
+// should return _Bool, but not int.
+_Bool ret = __builtin_mul_overflow(10, 20, &res); // no crash
+}

``




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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Pavel Skripkin via cfe-commits

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

>From 4f5fc3e12747064b35c490e510c63702afc8a800 Mon Sep 17 00:00:00 2001
From: Pavel Skripkin 
Date: Sat, 5 Oct 2024 15:58:15 +0300
Subject: [PATCH 1/2] clang/csa: fix wrong __builtin_*_overflow return type

---
 .../Checkers/BuiltinFunctionChecker.cpp   |  5 +++--
 clang/test/Analysis/builtin_overflow.c| 11 ++-
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index 69d8e968283b37..d49f01898e2241 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -183,6 +183,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   ProgramStateRef State = C.getState();
   SValBuilder &SVB = C.getSValBuilder();
   const Expr *CE = Call.getOriginExpr();
+  auto BoolTy = C.getASTContext().BoolTy;
 
   SVal Arg1 = Call.getArgSVal(0);
   SVal Arg2 = Call.getArgSVal(1);
@@ -194,7 +195,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
 ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false));
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false, 
BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -213,7 +214,7 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   if (Overflow) {
 C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true)),
+State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true, 
BoolTy)),
 createBuiltinOverflowNoteTag(C));
   }
 }
diff --git a/clang/test/Analysis/builtin_overflow.c 
b/clang/test/Analysis/builtin_overflow.c
index 5c61795661d095..9d98ce7a1af45c 100644
--- a/clang/test/Analysis/builtin_overflow.c
+++ b/clang/test/Analysis/builtin_overflow.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -triple x86_64-unknown-unknown -verify %s \
-// RUN:   -analyzer-checker=core,debug.ExprInspection
+// RUN:   -analyzer-checker=core,debug.ExprInspection,alpha.core.BoolAssignment
 
 #define __UINT_MAX__ (__INT_MAX__ * 2U + 1U)
 #define __INT_MIN__  (-__INT_MAX__ - 1)
@@ -155,3 +155,12 @@ void test_uadd_overflow_contraints(unsigned a, unsigned b)
  return;
}
 }
+
+void test_bool_assign(void)
+{
+int res;
+
+// Reproduce issue from GH#47. __builtin_*_overflow funcions
+// should return _Bool, but not int.
+_Bool ret = __builtin_mul_overflow(10, 20, &res); // no crash
+}

>From dcfd42f8c30c1000e13c636df58ae9b2d2b2a9b4 Mon Sep 17 00:00:00 2001
From: Pavel Skripkin 
Date: Sat, 5 Oct 2024 16:05:58 +0300
Subject: [PATCH 2/2] fix formatting

---
 .../StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp | 10 +-
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index d49f01898e2241..4ab0c4c9ae7b70 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -194,8 +194,8 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
-ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false, 
BoolTy));
+ProgramStateRef StateNoOverflow = State->BindExpr(
+CE, C.getLocationContext(), SVB.makeTruthVal(false, BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -213,9 +213,9 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   }
 
   if (Overflow) {
-C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true, 
BoolTy)),
-createBuiltinOverflowNoteTag(C));
+C.addTransition(State->BindExpr(CE, C.getLocationContext(),
+SVB.makeTruthVal(true, BoolTy)),
+createBuiltinOverflowNoteTag(C));
   }
 }
 

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 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 91fdfec263ff2b8e88433c4294a550cabb0f2314 
4f5fc3e12747064b35c490e510c63702afc8a800 --extensions c,cpp -- 
clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
clang/test/Analysis/builtin_overflow.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index d49f01898e..4ab0c4c9ae 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -194,8 +194,8 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
 
   auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
   if (NotOverflow) {
-ProgramStateRef StateNoOverflow =
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(false, 
BoolTy));
+ProgramStateRef StateNoOverflow = State->BindExpr(
+CE, C.getLocationContext(), SVB.makeTruthVal(false, BoolTy));
 
 if (auto L = Call.getArgSVal(2).getAs()) {
   StateNoOverflow =
@@ -213,9 +213,9 @@ void BuiltinFunctionChecker::handleOverflowBuiltin(const 
CallEvent &Call,
   }
 
   if (Overflow) {
-C.addTransition(
-State->BindExpr(CE, C.getLocationContext(), SVB.makeTruthVal(true, 
BoolTy)),
-createBuiltinOverflowNoteTag(C));
+C.addTransition(State->BindExpr(CE, C.getLocationContext(),
+SVB.makeTruthVal(true, BoolTy)),
+createBuiltinOverflowNoteTag(C));
   }
 }
 

``




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


[clang] WIP Add suppress weak loop assumptions visitor (PR #111258)

2024-10-05 Thread Balazs Benics via cfe-commits

steakhal wrote:

Ideally, I should use a location context and expr pairs a map keys, to make 
sure these numbers are kept separate for different stack frames. I leave it for 
the reader this time, to not complicate things further. Once we settle, I'll do 
that too.

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Balazs Benics via cfe-commits

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

LGTM, thanks.

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


[clang] [analyzer] Fix wrong `builtin_*_overflow` return type (PR #111253)

2024-10-05 Thread Pavel Skripkin via cfe-commits

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


[clang] 4e5f8a8 - [clang][bytecode] Save a per-Block IsWeak bit (#111248)

2024-10-05 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-10-05T17:35:52+02:00
New Revision: 4e5f8a8f0bf855fdac93fa09b4b82b69339235b9

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

LOG: [clang][bytecode] Save a per-Block IsWeak bit (#111248)

Checking the decl for every load is rather expensive.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBlock.cpp
clang/lib/AST/ByteCode/InterpBlock.h
clang/lib/AST/ByteCode/Pointer.h
clang/lib/AST/ByteCode/Program.cpp
clang/lib/AST/ByteCode/Program.h

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBlock.cpp 
b/clang/lib/AST/ByteCode/InterpBlock.cpp
index 0ce88ca7e52365..9ef44cd29ff875 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.cpp
+++ b/clang/lib/AST/ByteCode/InterpBlock.cpp
@@ -100,8 +100,8 @@ bool Block::hasPointer(const Pointer *P) const {
 #endif
 
 DeadBlock::DeadBlock(DeadBlock *&Root, Block *Blk)
-: Root(Root),
-  B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, /*isDead=*/true) {
+: Root(Root), B(~0u, Blk->Desc, Blk->IsStatic, Blk->IsExtern, Blk->IsWeak,
+/*isDead=*/true) {
   // Add the block to the chain of dead blocks.
   if (Root)
 Root->Prev = this;

diff  --git a/clang/lib/AST/ByteCode/InterpBlock.h 
b/clang/lib/AST/ByteCode/InterpBlock.h
index a5cd58e3a655a0..985e4c152191c6 100644
--- a/clang/lib/AST/ByteCode/InterpBlock.h
+++ b/clang/lib/AST/ByteCode/InterpBlock.h
@@ -50,16 +50,17 @@ class Block final {
 public:
   /// Creates a new block.
   Block(unsigned EvalID, const std::optional &DeclID,
-const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false)
+const Descriptor *Desc, bool IsStatic = false, bool IsExtern = false,
+bool IsWeak = false)
   : EvalID(EvalID), DeclID(DeclID), IsStatic(IsStatic), IsExtern(IsExtern),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsStatic = false,
-bool IsExtern = false)
+bool IsExtern = false, bool IsWeak = false)
   : EvalID(EvalID), DeclID((unsigned)-1), IsStatic(IsStatic),
-IsExtern(IsExtern), IsDynamic(false), Desc(Desc) {
+IsExtern(IsExtern), IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -73,6 +74,7 @@ class Block final {
   bool isStatic() const { return IsStatic; }
   /// Checks if the block is temporary.
   bool isTemporary() const { return Desc->IsTemporary; }
+  bool isWeak() const { return IsWeak; }
   bool isDynamic() const { return IsDynamic; }
   /// Returns the size of the block.
   unsigned getSize() const { return Desc->getAllocSize(); }
@@ -135,9 +137,9 @@ class Block final {
   friend class DynamicAllocator;
 
   Block(unsigned EvalID, const Descriptor *Desc, bool IsExtern, bool IsStatic,
-bool IsDead)
+bool IsWeak, bool IsDead)
   : EvalID(EvalID), IsStatic(IsStatic), IsExtern(IsExtern), IsDead(true),
-IsDynamic(false), Desc(Desc) {
+IsDynamic(false), IsWeak(IsWeak), Desc(Desc) {
 assert(Desc);
   }
 
@@ -170,6 +172,7 @@ class Block final {
   /// Flag indicating if this block has been allocated via dynamic
   /// memory allocation (e.g. malloc).
   bool IsDynamic = false;
+  bool IsWeak = false;
   /// Pointer to the stack slot descriptor.
   const Descriptor *Desc;
 };

diff  --git a/clang/lib/AST/ByteCode/Pointer.h 
b/clang/lib/AST/ByteCode/Pointer.h
index 08bc4b7e40b636..72e255dba13f6b 100644
--- a/clang/lib/AST/ByteCode/Pointer.h
+++ b/clang/lib/AST/ByteCode/Pointer.h
@@ -524,9 +524,7 @@ class Pointer {
   return false;
 
 assert(isBlockPointer());
-if (const ValueDecl *VD = getDeclDesc()->asValueDecl())
-  return VD->isWeak();
-return false;
+return asBlockPointer().Pointee->isWeak();
   }
   /// Checks if an object was initialized.
   bool isInitialized() const;

diff  --git a/clang/lib/AST/ByteCode/Program.cpp 
b/clang/lib/AST/ByteCode/Program.cpp
index 79c645257306e0..969f523db51dfe 100644
--- a/clang/lib/AST/ByteCode/Program.cpp
+++ b/clang/lib/AST/ByteCode/Program.cpp
@@ -152,10 +152,12 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 return It->second;
 
   QualType QT;
+  bool IsWeak = false;
   if (const auto *E = D.dyn_cast()) {
 QT = E->getType();
   } else {
 const ValueDecl *VD = cast(D.get());
+IsWeak = VD->isWeak();
 QT = VD->getType();
 if (const auto *RT = QT->getAs())
   QT = RT->getPointeeType();
@@ -182,7 +184,7 @@ std::optional Program::getOrCreateDummy(const 
DeclTy &D) {
 
   auto *G = new (Allocator, Desc->getAllocSize())
   Global(Ctx.getEvalID(), getCurrentDecl(), Desc, /*IsStatic=*/true,
- /*IsExtern=*/false);
+ /*IsExtern=*/false

[clang] [clang][bytecode] Save a per-Block IsWeak bit (PR #111248)

2024-10-05 Thread Timm Baeder via cfe-commits

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


  1   2   >