[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)

2024-03-25 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,50 @@
+//===--- ExceptionRethrowCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ExceptionRethrowCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); 
}
+} // namespace
+
+void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxThrowExpr(unless(isExpansionInSystemHeader()),
+   anyOf(unless(has(expr())),
+ has(declRefExpr(to(varDecl(isExceptionVariable()),
+   optionally(hasAncestor(cxxCatchStmt().bind("catch"
+  .bind("throw"),
+  this);
+}
+
+void ExceptionRethrowCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *MatchedThrow = Result.Nodes.getNodeAs("throw");
+
+  if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) {
+diag(MatchedThrow->getThrowLoc(),

PiotrZSL wrote:

I usually avoid adding fix-it hints to bugprone check, simply because devs 
apply them sometimes without even checking, and then complain that code does 
not compile (like because some variable is unused).

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


[clang] [clang-format] Fix anonymous reference parameter with default value (PR #86254)

2024-03-25 Thread via cfe-commits

https://github.com/rayroudc updated 
https://github.com/llvm/llvm-project/pull/86254

>From 3d4d9d701ee39d0bd4d60e4d0cd4a8577ce085d7 Mon Sep 17 00:00:00 2001
From: "C. Rayroud" 
Date: Mon, 18 Mar 2024 06:39:26 +
Subject: [PATCH 1/2] [clang-format] Fix anonymous reference parameter with
 default value

---
 clang/lib/Format/WhitespaceManager.cpp | 3 +++
 clang/unittests/Format/FormatTest.cpp  | 7 +++
 2 files changed, 10 insertions(+)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index fef85abf79a38c3..b2f7fb2643a67a4 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -475,6 +475,9 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
Previous >= 0 &&
Changes[Previous].Tok->getType() == TT_PointerOrReference;
--Previous) {
+// Don't align function default argument using return type maximum size
+if (Changes[Previous + 1].Tok->is(tok::equal))
+  continue;
 assert(Changes[Previous].Tok->isPointerOrReference());
 if (Changes[Previous].Tok->isNot(tok::star)) {
   if (ReferenceNotRightAligned)
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index bea989c8c306db7..a59480e0d3c505c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -19056,6 +19056,9 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
   verifyFormat("inta(int x);\n"
"double b();",
Alignment);
+  verifyFormat("inta(const Test & = Test());\n"
+   "double b();",
+   Alignment);
   verifyFormat("struct Test {\n"
"  Test(const Test &) = default;\n"
"  ~Test() = default;\n"
@@ -19277,6 +19280,10 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
"intfoobar;",
AlignmentLeft);
 
+  verifyFormat("inta(const Test& = Test());\n"
+   "double b();",
+   AlignmentLeft);
+
   // PAS_Middle
   FormatStyle AlignmentMiddle = Alignment;
   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;

>From 6fee149c7e2cd86a4a7d5f50967b4c23d423eb8c Mon Sep 17 00:00:00 2001
From: "C. Rayroud" 
Date: Mon, 25 Mar 2024 07:26:39 +
Subject: [PATCH 2/2] Simplify and add more tests

---
 clang/lib/Format/WhitespaceManager.cpp | 8 +++-
 clang/unittests/Format/FormatTest.cpp  | 9 +++--
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index b2f7fb2643a67a4..4908dda46f8ec26 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -464,10 +464,11 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 if (i + 1 != Changes.size())
   Changes[i + 1].PreviousEndOfTokenColumn += Shift;
 
-// If PointerAlignment is PAS_Right, keep *s or &s next to the token
+// If PointerAlignment is PAS_Right, keep *s or &s next to the token,
+// except if the token is equal, then a space is needed.
 if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
  Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
-CurrentChange.Spaces != 0) {
+CurrentChange.Spaces != 0 && !CurrentChange.Tok->is(tok::equal)) {
   const bool ReferenceNotRightAligned =
   Style.ReferenceAlignment != FormatStyle::RAS_Right &&
   Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
@@ -475,9 +476,6 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
Previous >= 0 &&
Changes[Previous].Tok->getType() == TT_PointerOrReference;
--Previous) {
-// Don't align function default argument using return type maximum size
-if (Changes[Previous + 1].Tok->is(tok::equal))
-  continue;
 assert(Changes[Previous].Tok->isPointerOrReference());
 if (Changes[Previous].Tok->isNot(tok::star)) {
   if (ReferenceNotRightAligned)
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a59480e0d3c505c..296ce81781e508a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -19056,7 +19056,8 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
   verifyFormat("inta(int x);\n"
"double b();",
Alignment);
-  verifyFormat("inta(const Test & = Test());\n"
+  verifyFormat("inta(int &count, SomeType &foo, const Test & = Test());\n"
+   "inta2(int &foo, const Test &name = Test());\n"
"double b();",
Alignment);
   verifyFormat("struct Test {\n"
@@ -19280,7 +19281,7 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
"intfoobar;",
AlignmentL

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 commented:

Thanks for the patch!

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Nathan Ridge via cfe-commits


@@ -367,7 +367,13 @@ class Checker {
 auto Hints = inlayHints(*AST, LineRange);
 
 for (const auto &Hint : Hints) {
-  vlog("  {0} {1} {2}", Hint.kind, Hint.position, Hint.label);
+  vlog("  {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
+return llvm::join(llvm::map_range(Hint.label,
+  [&](auto &L) {
+return llvm::formatv("{{{0}}", L);

HighCommander4 wrote:

There are three `{` in this format string, I assume that is a typo

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Nathan Ridge via cfe-commits


@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},

HighCommander4 wrote:

Is this needed? Looking at the code for serializing other vectors in this file, 
the conversion to `llvm::json::Array` Just Works.

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


[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)

2024-03-25 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

> By the way, looking at the issue, it seems like someone claimed to be working 
> on it, though we haven't seen any progress so far. Was it okay to take over 
> before asking that person first?

No pull request, no branch, no update for almost 3 months.
I assumed that it's abandoned.




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


[clang] [clang-format] Fix anonymous reference parameter with default value (PR #86254)

2024-03-25 Thread via cfe-commits


@@ -471,6 +471,9 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
Previous >= 0 &&
Changes[Previous].Tok->getType() == TT_PointerOrReference;
--Previous) {
+// Don't align function default argument using return type maximum size
+if (Changes[Previous + 1].Tok->is(tok::equal))
+  continue;

rayroudc wrote:

I pushed a new patch, to move the check out of the loop

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


[clang] [clang-format] Fix anonymous reference parameter with default value (PR #86254)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


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

2024-03-25 Thread Felix via cfe-commits


@@ -3369,6 +3369,48 @@ SDValue 
PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
   bool Is64Bit = Subtarget.isPPC64();
   bool HasAIXSmallLocalExecTLS = Subtarget.hasAIXSmallLocalExecTLS();
   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
+  // Initialize heuristic setting lazily:
+  // (1) Use initial-exec for single TLS var reference within current function.
+  // (2) Use local-dynamic for multiple TLS var references within current func.
+  PPCFunctionInfo *FuncInfo =
+  DAG.getMachineFunction().getInfo();
+  if (Subtarget.hasAIXShLibTLSModelHeuristic() &&
+  !FuncInfo->isAIXFuncUseInitDone()) {
+std::set TLSGV;
+for (SDNode &Node : DAG.allnodes()) {

orcguru wrote:

Emm, I will update test case to expose this issue. I will propose scan over all 
instructions in my next update. Thank you!

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


[clang] [llvm] [Sema] Implement support for -Wformat-signedness (PR #74440)

2024-03-25 Thread Karl-Johan Karlsson via cfe-commits

karka228 wrote:

> Can you also add a test showing the difference between `-Wformat 
> -Wformat-signedness` and `-Wformat-signedness` by itself (which does nothing)?

With the current implementation `-Wformat-signedness` by itself actually turn 
on the signedness warnings. This is not compatible with how gcc do it. I guess 
I have thought that it was not that important to be compatible with gcc in this 
respect. However if it is I guess this could be implemented.

> I'd also like to see a test demonstrating that `#pragma GCC diagnostic 
> ignored -Wformat` disables the signedness warnings.

There is a single test in the end of 
clang/test/Sema/format-strings-signedness.c that demonstrate this.


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


[clang] [llvm] [Sema] Implement support for -Wformat-signedness (PR #74440)

2024-03-25 Thread Karl-Johan Karlsson via cfe-commits

https://github.com/karka228 updated 
https://github.com/llvm/llvm-project/pull/74440

>From aa9d6cd10ff32fdcdd3d1b2ef334aa70f56cccb1 Mon Sep 17 00:00:00 2001
From: Karl-Johan Karlsson 
Date: Tue, 5 Dec 2023 10:03:00 +0100
Subject: [PATCH 1/8] [Sema] Implement support for -Wformat-signedness

In gcc there exist a modifier option -Wformat-signedness that turns on
additional signedness warnings in the already existing -Wformat warning.

This patch implements that support in clang.
---
 clang/include/clang/AST/FormatString.h|   2 +
 .../include/clang/Basic/DiagnosticOptions.def |   1 +
 clang/include/clang/Driver/Options.td |   3 +
 clang/lib/AST/FormatString.cpp|  29 +++--
 clang/lib/Driver/ToolChains/Clang.cpp |   2 +
 clang/lib/Sema/SemaChecking.cpp   |  26 -
 format-strings-signedness.c   | 107 ++
 7 files changed, 158 insertions(+), 12 deletions(-)
 create mode 100644 format-strings-signedness.c

diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index e2232fb4a47153..41cd0443ca2ac7 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -275,6 +275,8 @@ class ArgType {
 /// The conversion specifier and the argument type are compatible. For
 /// instance, "%d" and int.
 Match = 1,
+/// The conversion specifier and the argument type have different sign
+MatchSignedness,
 /// The conversion specifier and the argument type are compatible because 
of
 /// default argument promotions. For instance, "%hhd" and int.
 MatchPromotion,
diff --git a/clang/include/clang/Basic/DiagnosticOptions.def 
b/clang/include/clang/Basic/DiagnosticOptions.def
index 6d0c1b14acc120..a9562e7d8dcb0d 100644
--- a/clang/include/clang/Basic/DiagnosticOptions.def
+++ b/clang/include/clang/Basic/DiagnosticOptions.def
@@ -44,6 +44,7 @@ DIAGOPT(Name, Bits, Default)
 #endif
 
 SEMANTIC_DIAGOPT(IgnoreWarnings, 1, 0)   /// -w
+DIAGOPT(FormatSignedness, 1, 0) /// -Wformat-signedness
 DIAGOPT(NoRewriteMacros, 1, 0)  /// -Wno-rewrite-macros
 DIAGOPT(Pedantic, 1, 0) /// -pedantic
 DIAGOPT(PedanticErrors, 1, 0)   /// -pedantic-errors
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 4a954258ce40b6..1698c6c89e6e98 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -954,6 +954,9 @@ def Wdeprecated : Flag<["-"], "Wdeprecated">, 
Group,
   HelpText<"Enable warnings for deprecated constructs and define 
__DEPRECATED">;
 def Wno_deprecated : Flag<["-"], "Wno-deprecated">, Group,
   Visibility<[ClangOption, CC1Option]>;
+def Wformat_signedness : Flag<["-"], "Wformat-signedness">,
+  Flags<[HelpHidden]>, Visibility<[ClangOption, CC1Option]>,
+  MarshallingInfoFlag>;
 def Wl_COMMA : CommaJoined<["-"], "Wl,">, Visibility<[ClangOption, 
FlangOption]>,
   Flags<[LinkerInput, RenderAsInput]>,
   HelpText<"Pass the comma separated arguments in  to the linker">,
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index 0c80ad109ccbb2..bdd2f046113e7e 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -413,7 +413,7 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const {
 return Match;
   if (const auto *BT = argTy->getAs()) {
 // Check if the only difference between them is signed vs unsigned
-// if true, we consider they are compatible.
+// if true, return match signedness.
 switch (BT->getKind()) {
   default:
 break;
@@ -423,44 +423,53 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const 
{
 [[fallthrough]];
   case BuiltinType::Char_S:
   case BuiltinType::SChar:
+if (T == C.UnsignedShortTy || T == C.ShortTy)
+  return NoMatchTypeConfusion;
+if (T == C.UnsignedCharTy)
+  return MatchSignedness;
+if (T == C.SignedCharTy)
+  return Match;
+break;
   case BuiltinType::Char_U:
   case BuiltinType::UChar:
 if (T == C.UnsignedShortTy || T == C.ShortTy)
   return NoMatchTypeConfusion;
-if (T == C.UnsignedCharTy || T == C.SignedCharTy)
+if (T == C.UnsignedCharTy)
   return Match;
+if (T == C.SignedCharTy)
+  return MatchSignedness;
 break;
   case BuiltinType::Short:
 if (T == C.UnsignedShortTy)
-  return Match;
+  return MatchSignedness;
 break;
   case BuiltinType::UShort:
 if (T == C.ShortTy)
-  return Match;
+  return MatchSignedness;
 break;
   case BuiltinType::Int:
 if (T == C.UnsignedIntTy)
-  return Match;
+  return MatchSignedness;
 b

[clang] [OpenMP] Allow dynamic `condition` selector in Metadirective (PR #86457)

2024-03-25 Thread Robin Caloudis via cfe-commits

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


[clang] [llvm] [Sema] Implement support for -Wformat-signedness (PR #74440)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [OpenMP] Allow dynamic `condition` selector in Metadirective (PR #86457)

2024-03-25 Thread Robin Caloudis via cfe-commits

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


[clang] Issue #19 and #20 - Describe auto (C++11) type inferences (PR #86474)

2024-03-25 Thread Nisarga V via cfe-commits

https://github.com/nisarga3 created 
https://github.com/llvm/llvm-project/pull/86474

None

>From 6d3343fe3894d1706baa6316d76a5277af596f91 Mon Sep 17 00:00:00 2001
From: Nisarga V 
Date: Tue, 19 Mar 2024 06:35:04 -0500
Subject: [PATCH 1/2] Added 'fdump-autotype inference' option for Issue #19.

- Further refactoring in progress
---
 clang/include/clang/Basic/LangOptions.def  | 1 +
 clang/include/clang/Driver/Options.td  | 6 ++
 clang/include/clang/Frontend/FrontendOptions.h | 6 ++
 clang/lib/Frontend/CompilerInvocation.cpp  | 7 +++
 clang/tools/driver/cc1_main.cpp| 6 ++
 5 files changed, 26 insertions(+)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 472fd9f093a718..6cb262c845af8b 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -100,6 +100,7 @@ LANGOPT(CPlusPlus20   , 1, 0, "C++20")
 LANGOPT(CPlusPlus23   , 1, 0, "C++23")
 LANGOPT(CPlusPlus26   , 1, 0, "C++26")
 LANGOPT(ObjC  , 1, 0, "Objective-C")
+LANGOPT(DumpAutoTypeInference , 1, 0, "Dump auto type inference information")
 BENIGN_LANGOPT(ObjCDefaultSynthProperties , 1, 0,
"Objective-C auto-synthesized properties")
 BENIGN_LANGOPT(EncodeExtendedBlockSig , 1, 0,
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index aca8c9b0d5487a..542065be3c8811 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -7474,6 +7474,12 @@ def stats_file : Joined<["-"], "stats-file=">,
 def stats_file_append : Flag<["-"], "stats-file-append">,
   HelpText<"If stats should be appended to stats-file instead of overwriting 
it">,
   MarshallingInfoFlag>;
+
+def fdump_auto_type_inference : Flag<["-"], "fdump-auto-type-inference">, 
Group,
+HelpText<"Enable dumping of auto type inference information">;
+def fno_dump_auto_type_inference : Flag<["-"], 
"fno-dump-auto-type-inference">,Group,
+HelpText<"Disable dumping of auto type inference information">;
+
 def fdump_record_layouts_simple : Flag<["-"], "fdump-record-layouts-simple">,
   HelpText<"Dump record layout information in a simple form used for testing">,
   MarshallingInfoFlag>;
diff --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 8085dbcbf671a6..fac6ff18ecae69 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -134,6 +134,9 @@ enum ActionKind {
   /// Run one or more source code analyses.
   RunAnalysis,
 
+  /// for dumping auto type inference
+  DumpAutoTypeInference,
+
   /// Dump template instantiations
   TemplightDump,
 
@@ -274,6 +277,9 @@ class FrontendInputFile {
 /// FrontendOptions - Options for controlling the behavior of the frontend.
 class FrontendOptions {
 public:
+bool DumpAutoTypeInference=false;
+bool shouldDumpAutoTypeInference() const { return DumpAutoTypeInference; }
+void setDumpAutoTypeInference(bool Value) { DumpAutoTypeInference = Value; }
   /// Disable memory freeing on exit.
   LLVM_PREFERRED_TYPE(bool)
   unsigned DisableFree : 1;
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 451bdb9386f587..17d100f8ba2aa7 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2576,6 +2576,7 @@ static const auto &getFrontendActionTable() {
   {frontend::RunPreprocessorOnly, OPT_Eonly},
   {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
OPT_print_dependency_directives_minimized_source},
+  {frontend::DumpAutoTypeInference, OPT_fdump_auto_type_inference},
   };
 
   return Table;
@@ -2842,6 +2843,11 @@ static bool ParseFrontendArgs(FrontendOptions &Opts, 
ArgList &Args,
   for (const auto *AA : Args.filtered(OPT_plugin_arg))
 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
 
+// Add custom flag handling for -fdump-auto-type-inference
+  if (Args.hasArg(OPT_fdump_auto_type_inference)) {
+Opts.setDumpAutoTypeInference(true);
+  }
+
   for (const std::string &Arg :
  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
 std::string BlockName;
@@ -4295,6 +4301,7 @@ static bool 
isStrictlyPreprocessorAction(frontend::ActionKind Action) {
   case frontend::RunAnalysis:
   case frontend::TemplightDump:
   case frontend::MigrateSource:
+  case frontend::DumpAutoTypeInference:
 return false;
 
   case frontend::DumpCompilerOptions:
diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index b5c6be3c557bb3..a3e366ebcdeea1 100644
--- a/clang/tools/driver/cc1_main.cpp
+++ b/clang/tools/driver/cc1_main.cpp
@@ -191,6 +191,12 @@ int cc1_main(ArrayRef Argv, const char 
*Argv0, void *MainAddr) {
 
   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
 

[clang] Issue #19 and #20 - Describe auto (C++11) type inferences (PR #86474)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] Issue #19 and #20 - Describe auto (C++11) type inferences (PR #86474)

2024-03-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nisarga V (nisarga3)


Changes



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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) 
- (modified) clang/include/clang/Basic/LangOptions.def (+1) 
- (modified) clang/include/clang/Driver/Options.td (+6) 
- (modified) clang/include/clang/Frontend/FrontendOptions.h (+6) 
- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+7) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+8) 
- (modified) clang/tools/driver/cc1_main.cpp (+4) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9b5245695153ec..c1c8e2a58d1701 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2496,6 +2496,8 @@ def err_auto_init_list_from_c : Error<
   "%select{initializer list|array}1 in C">;
 def err_auto_bitfield : Error<
   "cannot pass bit-field as __auto_type initializer in C">;
+def note_deduced_auto_type : Note<
+"deduced type of %0 is %1">;
 
 // C++1y decltype(auto) type
 def err_decltype_auto_invalid : Error<
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 472fd9f093a718..6cb262c845af8b 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -100,6 +100,7 @@ LANGOPT(CPlusPlus20   , 1, 0, "C++20")
 LANGOPT(CPlusPlus23   , 1, 0, "C++23")
 LANGOPT(CPlusPlus26   , 1, 0, "C++26")
 LANGOPT(ObjC  , 1, 0, "Objective-C")
+LANGOPT(DumpAutoTypeInference , 1, 0, "Dump auto type inference information")
 BENIGN_LANGOPT(ObjCDefaultSynthProperties , 1, 0,
"Objective-C auto-synthesized properties")
 BENIGN_LANGOPT(EncodeExtendedBlockSig , 1, 0,
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index aca8c9b0d5487a..542065be3c8811 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -7474,6 +7474,12 @@ def stats_file : Joined<["-"], "stats-file=">,
 def stats_file_append : Flag<["-"], "stats-file-append">,
   HelpText<"If stats should be appended to stats-file instead of overwriting 
it">,
   MarshallingInfoFlag>;
+
+def fdump_auto_type_inference : Flag<["-"], "fdump-auto-type-inference">, 
Group,
+HelpText<"Enable dumping of auto type inference information">;
+def fno_dump_auto_type_inference : Flag<["-"], 
"fno-dump-auto-type-inference">,Group,
+HelpText<"Disable dumping of auto type inference information">;
+
 def fdump_record_layouts_simple : Flag<["-"], "fdump-record-layouts-simple">,
   HelpText<"Dump record layout information in a simple form used for testing">,
   MarshallingInfoFlag>;
diff --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 8085dbcbf671a6..fac6ff18ecae69 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -134,6 +134,9 @@ enum ActionKind {
   /// Run one or more source code analyses.
   RunAnalysis,
 
+  /// for dumping auto type inference
+  DumpAutoTypeInference,
+
   /// Dump template instantiations
   TemplightDump,
 
@@ -274,6 +277,9 @@ class FrontendInputFile {
 /// FrontendOptions - Options for controlling the behavior of the frontend.
 class FrontendOptions {
 public:
+bool DumpAutoTypeInference=false;
+bool shouldDumpAutoTypeInference() const { return DumpAutoTypeInference; }
+void setDumpAutoTypeInference(bool Value) { DumpAutoTypeInference = Value; }
   /// Disable memory freeing on exit.
   LLVM_PREFERRED_TYPE(bool)
   unsigned DisableFree : 1;
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 451bdb9386f587..17d100f8ba2aa7 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2576,6 +2576,7 @@ static const auto &getFrontendActionTable() {
   {frontend::RunPreprocessorOnly, OPT_Eonly},
   {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
OPT_print_dependency_directives_minimized_source},
+  {frontend::DumpAutoTypeInference, OPT_fdump_auto_type_inference},
   };
 
   return Table;
@@ -2842,6 +2843,11 @@ static bool ParseFrontendArgs(FrontendOptions &Opts, 
ArgList &Args,
   for (const auto *AA : Args.filtered(OPT_plugin_arg))
 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
 
+// Add custom flag handling for -fdump-auto-type-inference
+  if (Args.hasArg(OPT_fdump_auto_type_inference)) {
+Opts.setDumpAutoTypeInference(true);
+  }
+
   for (const std::string &Arg :
  Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
 std::string BlockName;
@@ -4295,6 +4301,7 @@ static bool 
isStrictlyPreprocessorAction(frontend::ActionKind Action) {
   case frontend::RunAnaly

[clang] Issue #19 and #20 - Describe auto (C++11) type inferences (PR #86474)

2024-03-25 Thread Nisarga V via cfe-commits

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


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

2024-03-25 Thread Felix via cfe-commits


@@ -329,6 +329,12 @@ def FeatureAIXLocalExecTLS :
"Produce a TOC-free local-exec TLS sequence for this 
function "
"for 64-bit AIX">;
 
+def FeatureAIXSharedLibraryTLSModelHeuristic :
+  SubtargetFeature<"aix-shared-library-tls-model-heuristic",

orcguru wrote:

I changed the name to `aix-shared-lib-tls-model-opt`. Hope that is fine.

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


[clang-tools-extra] [clangd] Support outgoing calls in call hierarchy (PR #77556)

2024-03-25 Thread via cfe-commits

pidgeon777 wrote:

I was thinking that it's a real pity this branch is so hard to get merged 😅 I 
think other than the review it would be 100% done? I mean, no big further 
modifications would be involved?

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


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

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


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

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the C/C++ code 
formatter.

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


[clang] [clang-repl] Fix Value for platforms where unqualified char is unsigned (PR #86118)

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

weliveindetail wrote:

Windows buildbot failure is unrelated. This code is covered in unittest 
ClangReplInterpreterTests and it passed.

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


[clang] aa962d6 - [clang-repl] Fix Value for platforms where unqualified char is unsigned (#86118)

2024-03-25 Thread via cfe-commits

Author: Stefan Gränitz
Date: 2024-03-25T09:42:41+01:00
New Revision: aa962d67ee896f416e285a9298e45fc08ff95eef

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

LOG: [clang-repl] Fix Value for platforms where unqualified char is unsigned 
(#86118)

Signedness of unqualified `char` is unspecified and varies between
platforms. This patch adds `Char_U` in `REPL_BUILTIN_TYPES` to account
for platforms that default to `unsigned char`.

Added: 


Modified: 
clang/include/clang/Interpreter/Value.h
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
index c380cd91550def..d70e8f8719026b 100644
--- a/clang/include/clang/Interpreter/Value.h
+++ b/clang/include/clang/Interpreter/Value.h
@@ -76,6 +76,7 @@ class QualType;
   X(bool, Bool)
\
   X(char, Char_S)  
\
   X(signed char, SChar)
\
+  X(unsigned char, Char_U) 
\
   X(unsigned char, UChar)  
\
   X(short, Short)  
\
   X(unsigned short, UShort)
\

diff  --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index e76c0677db5ead..69bc2da242884e 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -340,6 +340,12 @@ TEST(InterpreterTest, Value) {
   EXPECT_EQ(V1.getKind(), Value::K_Int);
   EXPECT_FALSE(V1.isManuallyAlloc());
 
+  Value V1b;
+  llvm::cantFail(Interp->ParseAndExecute("char c = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("c", &V1b));
+  EXPECT_TRUE(V1b.getKind() == Value::K_Char_S ||
+  V1b.getKind() == Value::K_Char_U);
+
   Value V2;
   llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
   llvm::cantFail(Interp->ParseAndExecute("y", &V2));



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


[clang] [clang-repl] Fix Value for platforms where unqualified char is unsigned (PR #86118)

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

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


[clang] 0cf4788 - [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (#84461)

2024-03-25 Thread via cfe-commits

Author: Stefan Gränitz
Date: 2024-03-25T09:44:25+01:00
New Revision: 0cf4788d9d0df60980cb48d28aafe7a86aa15a14

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

LOG: [clang-repl] Factor out CreateJITBuilder() and allow specialization in 
derived classes (#84461)

The LLJITBuilder interface provides a very convenient way to configure
the ORCv2 JIT engine. IncrementalExecutor already used it internally to
construct the JIT, but didn't provide external access. This patch lifts
control of the creation process to the Interpreter and allows injection
of a custom instance through the extended interface. The Interpreter's
default behavior remains unchanged and the IncrementalExecutor remains
an implementation detail.

Added: 


Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/IncrementalExecutor.cpp
clang/lib/Interpreter/IncrementalExecutor.h
clang/lib/Interpreter/Interpreter.cpp
clang/unittests/Interpreter/InterpreterExtensionsTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index 1dcba1ef967980..970e0245417b51 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -30,6 +30,7 @@
 namespace llvm {
 namespace orc {
 class LLJIT;
+class LLJITBuilder;
 class ThreadSafeContext;
 } // namespace orc
 } // namespace llvm
@@ -127,6 +128,13 @@ class Interpreter {
   // custom runtime.
   virtual std::unique_ptr FindRuntimeInterface();
 
+  // Lazily construct thev ORCv2 JITBuilder. This called when the internal
+  // IncrementalExecutor is created. The default implementation populates an
+  // in-process JIT with debugging support. Override this to configure the JIT
+  // engine used for execution.
+  virtual llvm::Expected>
+  CreateJITBuilder(CompilerInstance &CI);
+
 public:
   virtual ~Interpreter();
 

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index 40bcef94797d43..6f036107c14a9c 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"
 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
+#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
@@ -36,26 +37,28 @@ LLVM_ATTRIBUTE_USED void linkComponents() {
 
 namespace clang {
 
+llvm::Expected>
+IncrementalExecutor::createDefaultJITBuilder(
+llvm::orc::JITTargetMachineBuilder JTMB) {
+  auto JITBuilder = std::make_unique();
+  JITBuilder->setJITTargetMachineBuilder(std::move(JTMB));
+  JITBuilder->setPrePlatformSetup([](llvm::orc::LLJIT &J) {
+// Try to enable debugging of JIT'd code (only works with JITLink for
+// ELF and MachO).
+consumeError(llvm::orc::enableDebuggerSupport(J));
+return llvm::Error::success();
+  });
+  return std::move(JITBuilder);
+}
+
 IncrementalExecutor::IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC,
- llvm::Error &Err,
- const clang::TargetInfo &TI)
+ llvm::orc::LLJITBuilder &JITBuilder,
+ llvm::Error &Err)
 : TSCtx(TSC) {
   using namespace llvm::orc;
   llvm::ErrorAsOutParameter EAO(&Err);
 
-  auto JTMB = JITTargetMachineBuilder(TI.getTriple());
-  JTMB.addFeatures(TI.getTargetOpts().Features);
-  LLJITBuilder Builder;
-  Builder.setJITTargetMachineBuilder(JTMB);
-  Builder.setPrePlatformSetup(
-  [](LLJIT &J) {
-// Try to enable debugging of JIT'd code (only works with JITLink for
-// ELF and MachO).
-consumeError(enableDebuggerSupport(J));
-return llvm::Error::success();
-  });
-
-  if (auto JitOrErr = Builder.create())
+  if (auto JitOrErr = JITBuilder.create())
 Jit = std::move(*JitOrErr);
   else {
 Err = JitOrErr.takeError();

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.h 
b/clang/lib/Interpreter/IncrementalExecutor.h
index dd0a210a061415..b4347209e14fe3 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.h
+++ b/clang/lib/Interpreter/IncrementalExecutor.h
@@ -23,7 +23,9 @@
 namespace llvm {
 class Error;
 namespace orc {
+class JITTargetMachineBuilder;
 class LLJIT;
+class LLJITBuilder;
 class ThreadSafeContext;
 } // namespace orc
 } // namespace llvm
@@ -44,8 +46,8 @@ class IncrementalExecutor {
 public:
   enum SymbolNameKind { IRNa

[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

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

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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

usx95 wrote:

Ping for review: @AaronBallman @jyknight @efriedma-quic @zygoloid 
Could you please suggest other reviewers if you do not have the bandwidth for 
the same?

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


[clang] [clang][dataflow] Bail out if input is Objective-C++. (PR #86479)

2024-03-25 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/86479

We only ever intended to support C++, but the condition we were testing allowed
Objective-C++ code by mistake.


>From cfbd1b3633b78a2323eb5aebcb637112eeaa1571 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Mon, 25 Mar 2024 09:07:01 +
Subject: [PATCH] [clang][dataflow] Bail out if input is Objective-C++.

We only ever intended to support C++, but the condition we were testing allowed
Objective-C++ code by mistake.
---
 .../lib/Analysis/FlowSensitive/AdornedCFG.cpp |  2 +-
 .../FlowSensitive/DeterminismTest.cpp |  4 ++-
 .../Analysis/FlowSensitive/TransferTest.cpp   | 33 +++
 3 files changed, 31 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp 
b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
index daa73bed1bd9f5..255543021a998c 100644
--- a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
+++ b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
@@ -144,7 +144,7 @@ llvm::Expected AdornedCFG::build(const Decl &D, 
Stmt &S,
 
   // The shape of certain elements of the AST can vary depending on the
   // language. We currently only support C++.
-  if (!C.getLangOpts().CPlusPlus)
+  if (!C.getLangOpts().CPlusPlus || C.getLangOpts().ObjC)
 return llvm::createStringError(
 std::make_error_code(std::errc::invalid_argument),
 "Can only analyze C++");
diff --git a/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
index e794bd4943f232..a2cbfb1ff5826b 100644
--- a/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
@@ -30,7 +30,9 @@ namespace clang::dataflow {
 // flow-condition at function exit.
 std::string analyzeAndPrintExitCondition(llvm::StringRef Code) {
   DataflowAnalysisContext DACtx(std::make_unique());
-  clang::TestAST AST(Code);
+  TestInputs Inputs(Code);
+  Inputs.Language = TestLanguage::Lang_CXX17;
+  clang::TestAST AST(Inputs);
   const auto *Target =
   cast(test::findValueDecl(AST.context(), "target"));
   Environment InitEnv(DACtx, *Target);
diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 1d3b268976a767..ca055a462a2866 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
+#include "clang/Testing/TestAST.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Testing/Support/Error.h"
@@ -135,12 +136,32 @@ const Formula &getFormula(const ValueDecl &D, const 
Environment &Env) {
 }
 
 TEST(TransferTest, CNotSupported) {
-  std::string Code = R"(
-void target() {}
-  )";
-  ASSERT_THAT_ERROR(checkDataflowWithNoopAnalysis(
-Code, [](const auto &, auto &) {}, {BuiltinOptions{}},
-LangStandard::lang_c89),
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_C89;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
+llvm::FailedWithMessage("Can only analyze C++"));
+}
+
+TEST(TransferTest, ObjectiveCNotSupported) {
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_OBJC;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
+llvm::FailedWithMessage("Can only analyze C++"));
+}
+
+TEST(TransferTest, ObjectiveCXXNotSupported) {
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_OBJCXX;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
 llvm::FailedWithMessage("Can only analyze C++"));
 }
 

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


[clang] [clang][dataflow] Bail out if input is Objective-C++. (PR #86479)

2024-03-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: None (martinboehme)


Changes

We only ever intended to support C++, but the condition we were testing allowed
Objective-C++ code by mistake.


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


3 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp (+1-1) 
- (modified) clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp (+3-1) 
- (modified) clang/unittests/Analysis/FlowSensitive/TransferTest.cpp (+27-6) 


``diff
diff --git a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp 
b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
index daa73bed1bd9f5..255543021a998c 100644
--- a/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
+++ b/clang/lib/Analysis/FlowSensitive/AdornedCFG.cpp
@@ -144,7 +144,7 @@ llvm::Expected AdornedCFG::build(const Decl &D, 
Stmt &S,
 
   // The shape of certain elements of the AST can vary depending on the
   // language. We currently only support C++.
-  if (!C.getLangOpts().CPlusPlus)
+  if (!C.getLangOpts().CPlusPlus || C.getLangOpts().ObjC)
 return llvm::createStringError(
 std::make_error_code(std::errc::invalid_argument),
 "Can only analyze C++");
diff --git a/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
index e794bd4943f232..a2cbfb1ff5826b 100644
--- a/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DeterminismTest.cpp
@@ -30,7 +30,9 @@ namespace clang::dataflow {
 // flow-condition at function exit.
 std::string analyzeAndPrintExitCondition(llvm::StringRef Code) {
   DataflowAnalysisContext DACtx(std::make_unique());
-  clang::TestAST AST(Code);
+  TestInputs Inputs(Code);
+  Inputs.Language = TestLanguage::Lang_CXX17;
+  clang::TestAST AST(Inputs);
   const auto *Target =
   cast(test::findValueDecl(AST.context(), "target"));
   Environment InitEnv(DACtx, *Target);
diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 1d3b268976a767..ca055a462a2866 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
+#include "clang/Testing/TestAST.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Testing/Support/Error.h"
@@ -135,12 +136,32 @@ const Formula &getFormula(const ValueDecl &D, const 
Environment &Env) {
 }
 
 TEST(TransferTest, CNotSupported) {
-  std::string Code = R"(
-void target() {}
-  )";
-  ASSERT_THAT_ERROR(checkDataflowWithNoopAnalysis(
-Code, [](const auto &, auto &) {}, {BuiltinOptions{}},
-LangStandard::lang_c89),
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_C89;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
+llvm::FailedWithMessage("Can only analyze C++"));
+}
+
+TEST(TransferTest, ObjectiveCNotSupported) {
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_OBJC;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
+llvm::FailedWithMessage("Can only analyze C++"));
+}
+
+TEST(TransferTest, ObjectiveCXXNotSupported) {
+  TestInputs Inputs("void target() {}");
+  Inputs.Language = TestLanguage::Lang_OBJCXX;
+  clang::TestAST AST(Inputs);
+  const auto *Target =
+  cast(test::findValueDecl(AST.context(), "target"));
+  ASSERT_THAT_ERROR(AdornedCFG::build(*Target).takeError(),
 llvm::FailedWithMessage("Can only analyze C++"));
 }
 

``




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


[clang] [clang][dataflow] Bail out if input is Objective-C++. (PR #86479)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the C/C++ code 
formatter.

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


[clang] [clang][dataflow] Bail out if input is Objective-C++. (PR #86479)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-03-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 7adedf54a6c4d509046915777600b6e66b90bb8c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 13 Oct 2023 14:45:15 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   4 +-
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 105 +
 clang/test/Sema/attr-format-missing.c | 223 ++
 clang/test/Sema/attr-format-missing.cpp   | 211 +
 8 files changed, 552 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9cc2a72f4c864d..1ca055f65f2115 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,7 +65,9 @@ Improvements to Clang's diagnostics
 ^^^
 - We now generate a diagnostic for signed integer overflow due to unary minus
   in a non-constant expression context. This fixes
-  `Issue 31643 `_
+  `Issue 31643 `_.
+- We now generate a diagnostic for missing format attributes
+  `Issue 60718 `_.
 
 Non-comprehensive list of changes in this release
 -
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 17fdcffa2d4274..114cbbc2e82b85 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -482,7 +482,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6d6f474f6dcdab..964166b70c2aee 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -936,6 +936,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 741c2503127af7..064506e7096033 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10615,6 +10615,10 @@ class Sema final {
 ChangedStateAtExit
   };
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
  SourceLocation IncludeLoc);
   void DiagnoseUnterminatedPragmaAlignPack();
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 4602284309491c..d3ac6cb519c56e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6014,8 +6014,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 /// CheckConstructorCall - Check a constructor call for correctness and safety
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 1a0bfb3d91bcc8..f2134f2aac70bd 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6849,6 +6849,111 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// This function is called only if function call is not inside template body.
+// TODO: Add call for function calls inside template body.
+// Check if parent function misses for

[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 



@@ -394,8 +394,10 @@ class MallocChecker
  const CallEvent &Call, CheckerContext 
&C)>;
 
   const CallDescriptionMap PreFnMap{
-  {{{"getline"}, 3}, &MallocChecker::preGetdelim},
-  {{{"getdelim"}, 4}, &MallocChecker::preGetdelim},
+  // NOTE: the following CallDescription also matches the C++ standard
+  // library function std::getdelim(); the callback will filter it out.

NagyDonat wrote:

```suggestion
  // library function std::getline(); the callback will filter it out.
```

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


[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy 
Message-ID:
In-Reply-To: 



@@ -446,8 +448,11 @@ class MallocChecker
std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
   {{{"g_realloc_n"}, 3}, &MallocChecker::checkReallocN},
   {{{"g_try_realloc_n"}, 3}, &MallocChecker::checkReallocN},
-  {{{"getline"}, 3}, &MallocChecker::checkGetdelim},
-  {{{"getdelim"}, 4}, &MallocChecker::checkGetdelim},
+
+  // NOTE: the following CallDescription also matches the C++ standard
+  // library function std::getdelim(); the callback will filter it out.

NagyDonat wrote:

```suggestion
  // library function std::getline(); the callback will filter it out.
```

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


[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 
Message-ID:
In-Reply-To: 


https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/85791

>From 3fbc8da42726aa63ad0aef7ba12141125197279b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Tue, 19 Mar 2024 14:14:19 +0100
Subject: [PATCH 1/4] Reapply "[analyzer] Accept C library functions from the
 `std` namespace" again

This reapplies 80ab8234ac309418637488b97e0a62d8377b2ecf again, after
fixing a name collision warning in the unit tests (see the revert commit
13ccaf9b9d4400bb128b35ff4ac733e4afc3ad1c for details).

Co-authored-by: Balazs Benics 
---
 .../Core/PathSensitive/CallDescription.h  |  8 +-
 .../StaticAnalyzer/Core/CheckerContext.cpp|  8 +-
 clang/unittests/StaticAnalyzer/CMakeLists.txt |  1 +
 .../StaticAnalyzer/IsCLibraryFunctionTest.cpp | 82 +++
 .../clang/unittests/StaticAnalyzer/BUILD.gn   |  1 +
 5 files changed, 91 insertions(+), 9 deletions(-)
 create mode 100644 clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 3432d2648633c2..b4e1636130ca7c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -41,12 +41,8 @@ class CallDescription {
 ///  - We also accept calls where the number of arguments or parameters is
 ///greater than the specified value.
 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
-/// Note that functions whose declaration context is not a TU (e.g.
-/// methods, functions in namespaces) are not accepted as C library
-/// functions.
-/// FIXME: If I understand it correctly, this discards calls where C++ code
-/// refers a C library function through the namespace `std::` via headers
-/// like .
+/// (This mode only matches functions that are declared either directly
+/// within a TU or in the namespace `std`.)
 CLibrary,
 
 /// Matches "simple" functions that are not methods. (Static methods are
diff --git a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
index d6d4cec9dd3d4d..1a9bff529e9bb1 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
@@ -87,9 +87,11 @@ bool CheckerContext::isCLibraryFunction(const FunctionDecl 
*FD,
   if (!II)
 return false;
 
-  // Look through 'extern "C"' and anything similar invented in the future.
-  // If this function is not in TU directly, it is not a C library function.
-  if (!FD->getDeclContext()->getRedeclContext()->isTranslationUnit())
+  // C library functions are either declared directly within a TU (the common
+  // case) or they are accessed through the namespace `std` (when they are used
+  // in C++ via headers like ).
+  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
+  if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
 return false;
 
   // If this function is not externally visible, it is not a C library 
function.
diff --git a/clang/unittests/StaticAnalyzer/CMakeLists.txt 
b/clang/unittests/StaticAnalyzer/CMakeLists.txt
index 775f0f8486b8f9..db56e77331b821 100644
--- a/clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ b/clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_unittest(StaticAnalysisTests
   CallEventTest.cpp
   ConflictingEvalCallsTest.cpp
   FalsePositiveRefutationBRVisitorTest.cpp
+  IsCLibraryFunctionTest.cpp
   NoStateChangeFuncVisitorTest.cpp
   ParamRegionTest.cpp
   RangeSetTest.cpp
diff --git a/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp 
b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
new file mode 100644
index 00..f26acf07e23ac0
--- /dev/null
+++ b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
@@ -0,0 +1,82 @@
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+#include 
+
+using namespace clang;
+using namespace ento;
+using namespace ast_matchers;
+
+class IsCLibraryFunctionTest : public testing::Test {
+  std::unique_ptr ASTUnitP;
+  const FunctionDecl *Result = nullptr;
+public:
+  const FunctionDecl *getFunctionDecl() const { return Result; }
+
+  testing::AssertionResult buildAST(StringRef Code) {
+ASTUnitP = tooling::buildASTFromCode(Code);
+if (!ASTUnitP)
+  return testing::AssertionFailure() << "AST construction failed";
+
+ASTContext &Context = ASTUnitP->getASTContext();
+if (Context.getDiagnostics().hasErrorOccurred())

[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 
Message-ID:
In-Reply-To: 


https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/85791

>From 3fbc8da42726aa63ad0aef7ba12141125197279b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Tue, 19 Mar 2024 14:14:19 +0100
Subject: [PATCH 1/4] Reapply "[analyzer] Accept C library functions from the
 `std` namespace" again

This reapplies 80ab8234ac309418637488b97e0a62d8377b2ecf again, after
fixing a name collision warning in the unit tests (see the revert commit
13ccaf9b9d4400bb128b35ff4ac733e4afc3ad1c for details).

Co-authored-by: Balazs Benics 
---
 .../Core/PathSensitive/CallDescription.h  |  8 +-
 .../StaticAnalyzer/Core/CheckerContext.cpp|  8 +-
 clang/unittests/StaticAnalyzer/CMakeLists.txt |  1 +
 .../StaticAnalyzer/IsCLibraryFunctionTest.cpp | 82 +++
 .../clang/unittests/StaticAnalyzer/BUILD.gn   |  1 +
 5 files changed, 91 insertions(+), 9 deletions(-)
 create mode 100644 clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 3432d2648633c2..b4e1636130ca7c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -41,12 +41,8 @@ class CallDescription {
 ///  - We also accept calls where the number of arguments or parameters is
 ///greater than the specified value.
 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
-/// Note that functions whose declaration context is not a TU (e.g.
-/// methods, functions in namespaces) are not accepted as C library
-/// functions.
-/// FIXME: If I understand it correctly, this discards calls where C++ code
-/// refers a C library function through the namespace `std::` via headers
-/// like .
+/// (This mode only matches functions that are declared either directly
+/// within a TU or in the namespace `std`.)
 CLibrary,
 
 /// Matches "simple" functions that are not methods. (Static methods are
diff --git a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
index d6d4cec9dd3d4d..1a9bff529e9bb1 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
@@ -87,9 +87,11 @@ bool CheckerContext::isCLibraryFunction(const FunctionDecl 
*FD,
   if (!II)
 return false;
 
-  // Look through 'extern "C"' and anything similar invented in the future.
-  // If this function is not in TU directly, it is not a C library function.
-  if (!FD->getDeclContext()->getRedeclContext()->isTranslationUnit())
+  // C library functions are either declared directly within a TU (the common
+  // case) or they are accessed through the namespace `std` (when they are used
+  // in C++ via headers like ).
+  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
+  if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
 return false;
 
   // If this function is not externally visible, it is not a C library 
function.
diff --git a/clang/unittests/StaticAnalyzer/CMakeLists.txt 
b/clang/unittests/StaticAnalyzer/CMakeLists.txt
index 775f0f8486b8f9..db56e77331b821 100644
--- a/clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ b/clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_unittest(StaticAnalysisTests
   CallEventTest.cpp
   ConflictingEvalCallsTest.cpp
   FalsePositiveRefutationBRVisitorTest.cpp
+  IsCLibraryFunctionTest.cpp
   NoStateChangeFuncVisitorTest.cpp
   ParamRegionTest.cpp
   RangeSetTest.cpp
diff --git a/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp 
b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
new file mode 100644
index 00..f26acf07e23ac0
--- /dev/null
+++ b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
@@ -0,0 +1,82 @@
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+#include 
+
+using namespace clang;
+using namespace ento;
+using namespace ast_matchers;
+
+class IsCLibraryFunctionTest : public testing::Test {
+  std::unique_ptr ASTUnitP;
+  const FunctionDecl *Result = nullptr;
+public:
+  const FunctionDecl *getFunctionDecl() const { return Result; }
+
+  testing::AssertionResult buildAST(StringRef Code) {
+ASTUnitP = tooling::buildASTFromCode(Code);
+if (!ASTUnitP)
+  return testing::AssertionFailure() << "AST construction failed";
+
+ASTContext &Context = ASTUnitP->getASTContext();
+if (Context.getDiagnostics().hasErrorOccurred())

[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 
Message-ID:
In-Reply-To: 


github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

2024-03-25 Thread Jan Patrick Lehr via cfe-commits
Stefan =?utf-8?q?Gränitz?= 
Message-ID:
In-Reply-To: 


jplehr wrote:

Hi,
I think this one broke one of our buildbots: 
https://lab.llvm.org/buildbot/#/builders/259/builds/1769 
I'm happy to help looking into it.

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


[clang] 772e316 - [FMV] Allow multi versioning without default declaration. (#85454)

2024-03-25 Thread via cfe-commits

Author: Alexandros Lamprineas
Date: 2024-03-25T09:43:41Z
New Revision: 772e316457ef94759804d9f4da0af70d8d2ca4d4

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

LOG: [FMV] Allow multi versioning without default declaration. (#85454)

This was a limitation which has now been lifted. Please read the
thread below for more details:

https://github.com/llvm/llvm-project/pull/84405#discussion_r1525583647

Basically it allows to separate versioned implementations across
different TUs without having to share private header files which
contain the default declaration.

The ACLE spec has been updated accordingly to make this explicit:
"Each version declaration should be visible at the translation
 unit in which the corresponding function version resides."

https://github.com/ARM-software/acle/pull/310

If a resolver is required (because there is a caller in the TU),
then a default declaration is implicitly generated.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/CodeGen/attr-target-version.c
clang/test/CodeGenCXX/attr-target-version.cpp
clang/test/Sema/aarch64-sme-func-attrs.c
clang/test/Sema/attr-target-version.c
clang/test/SemaCXX/attr-target-version.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index cb153066b28dd1..ac81df8cf7adfe 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3711,7 +3711,8 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
-  if (!FD->doesDeclarationForceExternallyVisibleDefinition())
+  if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
+  !FD->isTargetVersionMultiVersion())
 return;
 
   StringRef MangledName = getMangledName(GD);
@@ -4092,6 +4093,23 @@ llvm::GlobalValue::LinkageTypes 
getMultiversionLinkage(CodeGenModule &CGM,
   return llvm::GlobalValue::WeakODRLinkage;
 }
 
+static FunctionDecl *createDefaultTargetVersionFrom(const FunctionDecl *FD) {
+  DeclContext *DeclCtx = FD->getASTContext().getTranslationUnitDecl();
+  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
+  StorageClass SC = FD->getStorageClass();
+  DeclarationName Name = FD->getNameInfo().getName();
+
+  FunctionDecl *NewDecl =
+  FunctionDecl::Create(FD->getASTContext(), DeclCtx, FD->getBeginLoc(),
+   FD->getEndLoc(), Name, TInfo->getType(), TInfo, SC);
+
+  NewDecl->setIsMultiVersion();
+  NewDecl->addAttr(TargetVersionAttr::CreateImplicit(
+  NewDecl->getASTContext(), "default", NewDecl->getSourceRange()));
+
+  return NewDecl;
+}
+
 void CodeGenModule::emitMultiVersionFunctions() {
   std::vector MVFuncsToEmit;
   MultiVersionFuncs.swap(MVFuncsToEmit);
@@ -4099,70 +4117,54 @@ void CodeGenModule::emitMultiVersionFunctions() {
 const auto *FD = cast(GD.getDecl());
 assert(FD && "Expected a FunctionDecl");
 
-bool EmitResolver = !FD->isTargetVersionMultiVersion();
+auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
+  GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, 
MVIdx};
+  StringRef MangledName = getMangledName(CurGD);
+  llvm::Constant *Func = GetGlobalValue(MangledName);
+  if (!Func) {
+if (Decl->isDefined()) {
+  EmitGlobalFunctionDefinition(CurGD, nullptr);
+  Func = GetGlobalValue(MangledName);
+} else {
+  const CGFunctionInfo &FI = 
getTypes().arrangeGlobalDeclaration(CurGD);
+  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
+  Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
+   /*DontDefer=*/false, ForDefinition);
+}
+assert(Func && "This should have just been created");
+  }
+  return cast(Func);
+};
+
+bool HasDefaultDecl = !FD->isTargetVersionMultiVersion();
+bool ShouldEmitResolver = !FD->isTargetVersionMultiVersion();
 SmallVector Options;
 if (FD->isTargetMultiVersion()) {
   getContext().forEachMultiversionedFunctionVersion(
-  FD, [this, &GD, &Options, &EmitResolver](const FunctionDecl *CurFD) {
-GlobalDecl CurGD{
-(CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
-StringRef MangledName = getMangledName(CurGD);
-llvm::Constant *Func = GetGlobalValue(MangledName);
-if (!Func) {
-  if (CurFD->isDefined()) {
-EmitGlobalFunctionDefinition(CurGD, nullptr);
-Func = GetGlobalValue(MangledName);
-  } else {
-  

[clang] [FMV] Allow multi versioning without default declaration. (PR #85454)

2024-03-25 Thread Alexandros Lamprineas via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-03-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 7adedf54a6c4d509046915777600b6e66b90bb8c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 13 Oct 2023 14:45:15 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   4 +-
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 105 +
 clang/test/Sema/attr-format-missing.c | 223 ++
 clang/test/Sema/attr-format-missing.cpp   | 211 +
 8 files changed, 552 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9cc2a72f4c864d..1ca055f65f2115 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -65,7 +65,9 @@ Improvements to Clang's diagnostics
 ^^^
 - We now generate a diagnostic for signed integer overflow due to unary minus
   in a non-constant expression context. This fixes
-  `Issue 31643 `_
+  `Issue 31643 `_.
+- We now generate a diagnostic for missing format attributes
+  `Issue 60718 `_.
 
 Non-comprehensive list of changes in this release
 -
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 17fdcffa2d4274..114cbbc2e82b85 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -482,7 +482,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6d6f474f6dcdab..964166b70c2aee 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -936,6 +936,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 741c2503127af7..064506e7096033 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10615,6 +10615,10 @@ class Sema final {
 ChangedStateAtExit
   };
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
  SourceLocation IncludeLoc);
   void DiagnoseUnterminatedPragmaAlignPack();
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 4602284309491c..d3ac6cb519c56e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6014,8 +6014,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 /// CheckConstructorCall - Check a constructor call for correctness and safety
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 1a0bfb3d91bcc8..f2134f2aac70bd 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6849,6 +6849,111 @@ static void handleSwiftAsyncAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
 }
 
+// This function is called only if function call is not inside template body.
+// TODO: Add call for function calls inside template body.
+// Check if parent function misses for

[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-25 Thread Nathan Gauër via cfe-commits


@@ -1295,11 +1295,13 @@ double4 trunc(double4);
 /// true, across all active lanes in the current wave.
 _HLSL_AVAILABILITY(shadermodel, 6.0)
 _HLSL_BUILTIN_ALIAS(__builtin_hlsl_wave_active_count_bits)
+__attribute__((convergent))

Keenuts wrote:

Right, so in that case, I'll add the convergent attribute again, and later down 
the road, once we have the noconvergent-default in place, we'll be able to flip 
this back.
Thanks all for the context and explanations!

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


[clang] [analyzer] Set and display CSA analysis entry points as notes on debugging (PR #84823)

2024-03-25 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/84823

>From 94c6be96d92d8a25693ccbbffedf9edabfe79cc5 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Mon, 11 Mar 2024 21:18:30 +0100
Subject: [PATCH 1/2] [analyzer] Set and display CSA analysis entry points as
 notes on debugging

When debugging CSA issues, sometimes it would be useful to have a
dedicated note for the analysis entry point, aka. the function name you
would need to pass as "-analyze-function=XYZ" to reproduce a specific
issue.
One way we use (or will use) this downstream is to provide tooling on
top of creduce to enhance to supercharge prductivity by automatically
reduce cases on crashes for example.

This will be added only if the "-analyzer-note-analysis-entry-points"
is set or the "analyzer-display-progress" is on.

This additional entry point marker will be the first "note" if enabled,
with the following message: "[invisible] analyzing from XYZ".
They are prefixed by "[invisible]" to remind the CSA developer that this
is only visible or meant to be visible for them.

CPP-5012
---
 clang/include/clang/Analysis/PathDiagnostic.h |  8 +-
 clang/include/clang/Driver/Options.td |  3 +
 .../StaticAnalyzer/Core/AnalyzerOptions.h |  9 ++-
 .../Core/BugReporter/BugReporter.h| 12 +++
 .../Core/PathSensitive/ExprEngine.h   |  2 +
 clang/lib/Analysis/PathDiagnostic.cpp |  7 +-
 clang/lib/StaticAnalyzer/Core/BugReporter.cpp | 36 ++---
 .../Frontend/AnalysisConsumer.cpp |  4 +-
 .../Analysis/analyzer-display-progress.cpp| 42 ---
 .../test/Analysis/analyzer-display-progress.m | 31 +---
 .../analyzer-note-analysis-entry-points.cpp   | 75 +++
 11 files changed, 193 insertions(+), 36 deletions(-)
 create mode 100644 clang/test/Analysis/analyzer-note-analysis-entry-points.cpp

diff --git a/clang/include/clang/Analysis/PathDiagnostic.h 
b/clang/include/clang/Analysis/PathDiagnostic.h
index 90559e7efb06f0..5907df022e449d 100644
--- a/clang/include/clang/Analysis/PathDiagnostic.h
+++ b/clang/include/clang/Analysis/PathDiagnostic.h
@@ -780,6 +780,9 @@ class PathDiagnostic : public llvm::FoldingSetNode {
   PathDiagnosticLocation UniqueingLoc;
   const Decl *UniqueingDecl;
 
+  /// The top-level entry point from which this issue was discovered.
+  const Decl *AnalysisEntryPoint = nullptr;
+
   /// Lines executed in the path.
   std::unique_ptr ExecutedLines;
 
@@ -788,7 +791,7 @@ class PathDiagnostic : public llvm::FoldingSetNode {
   PathDiagnostic(StringRef CheckerName, const Decl *DeclWithIssue,
  StringRef bugtype, StringRef verboseDesc, StringRef shortDesc,
  StringRef category, PathDiagnosticLocation LocationToUnique,
- const Decl *DeclToUnique,
+ const Decl *DeclToUnique, const Decl *AnalysisEntryPoint,
  std::unique_ptr ExecutedLines);
   ~PathDiagnostic();
 
@@ -852,6 +855,9 @@ class PathDiagnostic : public llvm::FoldingSetNode {
 return *ExecutedLines;
   }
 
+  /// Get the top-level entry point from which this issue was discovered.
+  const Decl *getAnalysisEntryPoint() const { return AnalysisEntryPoint; }
+
   /// Return the semantic context where an issue occurred.  If the
   /// issue occurs along a path, this represents the "central" area
   /// where the bug manifests.
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5b3d366dbcf91b..55bfd1cc450809 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6656,6 +6656,9 @@ def analyzer_opt_analyze_headers : Flag<["-"], 
"analyzer-opt-analyze-headers">,
 def analyzer_display_progress : Flag<["-"], "analyzer-display-progress">,
   HelpText<"Emit verbose output about the analyzer's progress">,
   MarshallingInfoFlag>;
+def analyzer_note_analysis_entry_points : Flag<["-"], 
"analyzer-note-analysis-entry-points">,
+  HelpText<"Add a note for each bug report to denote their analysis entry 
points">,
+  MarshallingInfoFlag>;
 def analyze_function : Separate<["-"], "analyze-function">,
   HelpText<"Run analysis on specific function (for C++ include parameters in 
name)">,
   MarshallingInfoString>;
diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
index 276d11e80a5b21..3a3c1a13d67dd5 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -227,6 +227,7 @@ class AnalyzerOptions : public 
RefCountedBase {
   unsigned ShouldEmitErrorsOnInvalidConfigValue : 1;
   unsigned AnalyzeAll : 1;
   unsigned AnalyzerDisplayProgress : 1;
+  unsigned AnalyzerNoteAnalysisEntryPoints : 1;
 
   unsigned eagerlyAssumeBinOpBifurcation : 1;
 
@@ -291,10 +292,10 @@ class AnalyzerOptions : public 
RefCountedBase {
 ShowCheckerOptionDeveloperList(false), ShowEnabledChec

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Younan Zhang via cfe-commits


@@ -367,7 +367,13 @@ class Checker {
 auto Hints = inlayHints(*AST, LineRange);
 
 for (const auto &Hint : Hints) {
-  vlog("  {0} {1} {2}", Hint.kind, Hint.position, Hint.label);
+  vlog("  {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
+return llvm::join(llvm::map_range(Hint.label,
+  [&](auto &L) {
+return llvm::formatv("{{{0}}", L);

zyn0217 wrote:

I admit this is quite strange, but the current `formatv` implementation doesn't 
require escaping `}`s (but does require doubling `{{`s for a literal `{`). See 
https://reviews.llvm.org/D83888.

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-25 Thread Wang Pengcheng via cfe-commits


@@ -49,3 +49,62 @@ if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
   # despite potential dllexports.
   target_link_options(clangInterpreter PRIVATE LINKER:--export-all-symbols)
 endif()
+
+if(MSVC)
+  set_target_properties(clangInterpreter PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS 
1)
+
+  # RTTI/C++ symbols
+  set(clangInterpreter_exports ${clangInterpreter_exports} ??_7type_info@@6B@
+?__type_info_root_node@@3U__type_info_node@@A
+?nothrow@std@@3Unothrow_t@1@B
+  )
+
+  # Compiler added symbols for static variables. NOT for VStudio < 2015
+  set(clangInterpreter_exports ${clangInterpreter_exports} _Init_thread_abort 
_Init_thread_epoch
+_Init_thread_footer _Init_thread_header _tls_index
+  )
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+# new/delete variants needed when linking to static msvc runtime (esp. 
Debug)
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPEAX_K@Z
+  ??3@YAXPEAX@Z
+  ??_U@YAPEAX_K@Z
+  ??_V@YAXPEAX@Z
+  ??3@YAXPEAX_K@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@PEBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@P6AAEAV01@AEAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@PEBD@Z
+  ?_Facet_Register@std@@YAXPEAV_Facet_base@1@@Z
+)
+  else()
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPAXI@Z
+  ??3@YAXPAX@Z
+  ??3@YAXPAXI@Z
+  ??_U@YAPAXI@Z
+  ??_V@YAXPAX@Z
+  ??_V@YAXPAXI@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@P6AAAV01@AAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z
+  ?_Facet_Register@std@@YAXPAV_Facet_base@1@@Z
+)
+  endif()
+
+  # List to '/EXPORT:sym0 /EXPORT:sym1 /EXPORT:sym2 ...'
+  foreach(sym ${clangInterpreter_exports})
+set(clangInterpreter_link_str "${clangInterpreter_link_str} 
/EXPORT:${sym}")
+  endforeach(sym ${clangInterpreter_exports})
+
+  set_property(TARGET clangInterpreter APPEND_STRING PROPERTY LINK_FLAGS 
${clangInterpreter_link_str})
+
+endif(MSVC)

wangpc-pp wrote:

It seems using `target_link_options ` doesn't work. So I added all exports to 
`ClangReplInterpreterTests`  and `clang-repl`.

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-25 Thread Wang Pengcheng via cfe-commits

wangpc-pp wrote:

Windows CI is passed now, many thanks to @AaronBallman @vgvassilev!
I may land this in a few days if there is no more comment. :-)

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


[clang] [analyzer] Set and display CSA analysis entry points as notes on debugging (PR #84823)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [analyzer] Set and display CSA analysis entry points as notes on debugging (PR #84823)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the C/C++ code 
formatter.

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Younan Zhang via cfe-commits


@@ -367,7 +367,13 @@ class Checker {
 auto Hints = inlayHints(*AST, LineRange);
 
 for (const auto &Hint : Hints) {
-  vlog("  {0} {1} {2}", Hint.kind, Hint.position, Hint.label);
+  vlog("  {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
+return llvm::join(llvm::map_range(Hint.label,
+  [&](auto &L) {
+return llvm::formatv("{{{0}}", L);

zyn0217 wrote:

(I don't know why Sam's comment was not reflected in that patch at last -- 
maybe I can add that in a separate NFC patch.)

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


[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 
Message-ID:
In-Reply-To: 



@@ -1435,9 +1440,17 @@ void MallocChecker::checkGMallocN0(const CallEvent &Call,
   C.addTransition(State);
 }
 
+static bool isFromStdNamespace(const CallEvent &Call) {
+  const Decl *FD = Call.getDecl();
+  assert(FD && "a CallDescription cannot match a call without a Decl");
+  return (FD->isInStdNamespace());

NagyDonat wrote:

```suggestion
  return FD->isInStdNamespace();
```

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


[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 ,NagyDonat 
Message-ID:
In-Reply-To: 


https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/85791

>From 3fbc8da42726aa63ad0aef7ba12141125197279b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Tue, 19 Mar 2024 14:14:19 +0100
Subject: [PATCH 1/5] Reapply "[analyzer] Accept C library functions from the
 `std` namespace" again

This reapplies 80ab8234ac309418637488b97e0a62d8377b2ecf again, after
fixing a name collision warning in the unit tests (see the revert commit
13ccaf9b9d4400bb128b35ff4ac733e4afc3ad1c for details).

Co-authored-by: Balazs Benics 
---
 .../Core/PathSensitive/CallDescription.h  |  8 +-
 .../StaticAnalyzer/Core/CheckerContext.cpp|  8 +-
 clang/unittests/StaticAnalyzer/CMakeLists.txt |  1 +
 .../StaticAnalyzer/IsCLibraryFunctionTest.cpp | 82 +++
 .../clang/unittests/StaticAnalyzer/BUILD.gn   |  1 +
 5 files changed, 91 insertions(+), 9 deletions(-)
 create mode 100644 clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 3432d2648633c2..b4e1636130ca7c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -41,12 +41,8 @@ class CallDescription {
 ///  - We also accept calls where the number of arguments or parameters is
 ///greater than the specified value.
 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
-/// Note that functions whose declaration context is not a TU (e.g.
-/// methods, functions in namespaces) are not accepted as C library
-/// functions.
-/// FIXME: If I understand it correctly, this discards calls where C++ code
-/// refers a C library function through the namespace `std::` via headers
-/// like .
+/// (This mode only matches functions that are declared either directly
+/// within a TU or in the namespace `std`.)
 CLibrary,
 
 /// Matches "simple" functions that are not methods. (Static methods are
diff --git a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
index d6d4cec9dd3d4d..1a9bff529e9bb1 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
@@ -87,9 +87,11 @@ bool CheckerContext::isCLibraryFunction(const FunctionDecl 
*FD,
   if (!II)
 return false;
 
-  // Look through 'extern "C"' and anything similar invented in the future.
-  // If this function is not in TU directly, it is not a C library function.
-  if (!FD->getDeclContext()->getRedeclContext()->isTranslationUnit())
+  // C library functions are either declared directly within a TU (the common
+  // case) or they are accessed through the namespace `std` (when they are used
+  // in C++ via headers like ).
+  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
+  if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
 return false;
 
   // If this function is not externally visible, it is not a C library 
function.
diff --git a/clang/unittests/StaticAnalyzer/CMakeLists.txt 
b/clang/unittests/StaticAnalyzer/CMakeLists.txt
index 775f0f8486b8f9..db56e77331b821 100644
--- a/clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ b/clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_unittest(StaticAnalysisTests
   CallEventTest.cpp
   ConflictingEvalCallsTest.cpp
   FalsePositiveRefutationBRVisitorTest.cpp
+  IsCLibraryFunctionTest.cpp
   NoStateChangeFuncVisitorTest.cpp
   ParamRegionTest.cpp
   RangeSetTest.cpp
diff --git a/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp 
b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
new file mode 100644
index 00..f26acf07e23ac0
--- /dev/null
+++ b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
@@ -0,0 +1,82 @@
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+#include 
+
+using namespace clang;
+using namespace ento;
+using namespace ast_matchers;
+
+class IsCLibraryFunctionTest : public testing::Test {
+  std::unique_ptr ASTUnitP;
+  const FunctionDecl *Result = nullptr;
+public:
+  const FunctionDecl *getFunctionDecl() const { return Result; }
+
+  testing::AssertionResult buildAST(StringRef Code) {
+ASTUnitP = tooling::buildASTFromCode(Code);
+if (!ASTUnitP)
+  return testing::AssertionFailure() << "AST construction failed";
+
+ASTContext &Context = ASTUnitP->getASTContext();
+if (Context.getDiagnostics().hasErrorO

[clang] 37785fe - [clang][analyzer] Bring cplusplus.ArrayDelete out of alpha (#83985)

2024-03-25 Thread via cfe-commits

Author: Discookie
Date: 2024-03-25T10:08:56Z
New Revision: 37785fedabd8fa752129ef5bac3462311af91c35

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

LOG: [clang][analyzer] Bring cplusplus.ArrayDelete out of alpha (#83985)

The checker finds a type of undefined behavior, where if the type of a
pointer to an object-array is different from the objects' underlying
type, calling `delete[]` is undefined, as the size of the two objects
might be different.

The checker has been in alpha for a while now, it is a simple checker
that causes no crashes, and considering the severity of the issue, it
has a low result-count on open-source projects (in my last test-run on
my usual projects, it had 0 results).

This commit cleans up the documentation and adds docs for the limitation
related to tracking through references, in addition to moving it to
`cplusplus`.

-

Co-authored-by: Balazs Benics 
Co-authored-by: whisperity 

Added: 


Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
clang/test/Analysis/ArrayDelete.cpp
clang/www/analyzer/alpha_checks.html
clang/www/analyzer/available_checks.html

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index fe211514914272..66da1c7b35f28b 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -340,6 +340,51 @@ cplusplus
 
 C++ Checkers.
 
+.. _cplusplus-ArrayDelete:
+
+cplusplus.ArrayDelete (C++)
+"""
+
+Reports destructions of arrays of polymorphic objects that are destructed as
+their base class. If the dynamic type of the array is 
diff erent from its static
+type, calling `delete[]` is undefined.
+
+This checker corresponds to the SEI CERT rule `EXP51-CPP: Do not delete an 
array through a pointer of the incorrect type 
`_.
+
+.. code-block:: cpp
+
+ class Base {
+ public:
+   virtual ~Base() {}
+ };
+ class Derived : public Base {};
+
+ Base *create() {
+   Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
+   return x;
+ }
+
+ void foo() {
+   Base *x = create();
+   delete[] x; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
+ }
+
+**Limitations**
+
+The checker does not emit note tags when casting to and from reference types,
+even though the pointer values are tracked across references.
+
+.. code-block:: cpp
+
+ void foo() {
+   Derived *d = new Derived[10];
+   Derived &dref = *d;
+
+   Base &bref = static_cast(dref); // no note
+   Base *b = &bref;
+   delete[] b; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
+ }
+
 .. _cplusplus-InnerPointer:
 
 cplusplus.InnerPointer (C++)
@@ -2139,30 +2184,6 @@ Either the comparison is useless or there is division by 
zero.
 alpha.cplusplus
 ^^^
 
-.. _alpha-cplusplus-ArrayDelete:
-
-alpha.cplusplus.ArrayDelete (C++)
-"
-Reports destructions of arrays of polymorphic objects that are destructed as 
their base class.
-This checker corresponds to the CERT rule `EXP51-CPP: Do not delete an array 
through a pointer of the incorrect type 
`_.
-
-.. code-block:: cpp
-
- class Base {
-   virtual ~Base() {}
- };
- class Derived : public Base {}
-
- Base *create() {
-   Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
-   return x;
- }
-
- void foo() {
-   Base *x = create();
-   delete[] x; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
- }
-
 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
 
 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 686e5e99f4a62c..bf46766d44b391 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -622,6 +622,11 @@ def BlockInCriticalSectionChecker : 
Checker<"BlockInCriticalSection">,
 
 let ParentPackage = Cplusplus in {
 
+def ArrayDeleteChecker : Checker<"ArrayDelete">,
+  HelpText<"Reports destructions of arrays of polymorphic objects that are "
+   "destructed as their base class.">,
+  Documentation;
+
 def InnerPointerChecker : Checker<"InnerPointer">,
   HelpText<"Check for inner pointers of C++ containers used after "
"re/deallocation">,
@@ -777,

[clang] [clang][analyzer] Bring cplusplus.ArrayDelete out of alpha (PR #83985)

2024-03-25 Thread via cfe-commits

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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-25 Thread Vassil Vassilev via cfe-commits


@@ -49,3 +49,62 @@ if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
   # despite potential dllexports.
   target_link_options(clangInterpreter PRIVATE LINKER:--export-all-symbols)
 endif()
+
+if(MSVC)
+  set_target_properties(clangInterpreter PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS 
1)
+
+  # RTTI/C++ symbols
+  set(clangInterpreter_exports ${clangInterpreter_exports} ??_7type_info@@6B@
+?__type_info_root_node@@3U__type_info_node@@A
+?nothrow@std@@3Unothrow_t@1@B
+  )
+
+  # Compiler added symbols for static variables. NOT for VStudio < 2015
+  set(clangInterpreter_exports ${clangInterpreter_exports} _Init_thread_abort 
_Init_thread_epoch
+_Init_thread_footer _Init_thread_header _tls_index
+  )
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+# new/delete variants needed when linking to static msvc runtime (esp. 
Debug)
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPEAX_K@Z
+  ??3@YAXPEAX@Z
+  ??_U@YAPEAX_K@Z
+  ??_V@YAXPEAX@Z
+  ??3@YAXPEAX_K@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@PEBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@P6AAEAV01@AEAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@PEBD@Z
+  ?_Facet_Register@std@@YAXPEAV_Facet_base@1@@Z
+)
+  else()
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPAXI@Z
+  ??3@YAXPAX@Z
+  ??3@YAXPAXI@Z
+  ??_U@YAPAXI@Z
+  ??_V@YAXPAX@Z
+  ??_V@YAXPAXI@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@P6AAAV01@AAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z
+  ?_Facet_Register@std@@YAXPAV_Facet_base@1@@Z
+)
+  endif()
+
+  # List to '/EXPORT:sym0 /EXPORT:sym1 /EXPORT:sym2 ...'
+  foreach(sym ${clangInterpreter_exports})
+set(clangInterpreter_link_str "${clangInterpreter_link_str} 
/EXPORT:${sym}")
+  endforeach(sym ${clangInterpreter_exports})
+
+  set_property(TARGET clangInterpreter APPEND_STRING PROPERTY LINK_FLAGS 
${clangInterpreter_link_str})
+
+endif(MSVC)

vgvassilev wrote:

Can we find a cmake guru to tell us how to reduce that duplicated code?

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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

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

weliveindetail wrote:

Thanks for your note. Looks like the problem is that the ARM target is not 
registered. It's an uncommon requirement for a unitttest.. Will see how to 
check that at runtime. If you have an idea, let me know. Thanks

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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

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

weliveindetail wrote:

I will try this 
https://github.com/llvm/llvm-project/blob/release/18.x/llvm/unittests/DebugInfo/LogicalView/CodeViewReaderTest.cpp#L482
 and push a quick-fix.

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


[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-25 Thread Nathan Gauër via cfe-commits

https://github.com/Keenuts updated 
https://github.com/llvm/llvm-project/pull/80680

From afbe709931942b3970f92884022e250c1e7eb84f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nathan=20Gau=C3=ABr?= 
Date: Fri, 2 Feb 2024 16:38:46 +0100
Subject: [PATCH 1/8] [clang][HLSL][SPRI-V] Add convergence intrinsics
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

HLSL has wave operations and other kind of function which required the
control flow to either be converged, or respect certain constraints as
where and how to re-converge.

At the HLSL level, the convergence are mostly obvious: the control flow
is expected to re-converge at the end of a scope.
Once translated to IR, HLSL scopes disapear. This means we need a way to
communicate convergence restrictions down to the backend.

For this, the SPIR-V backend uses convergence intrinsics. So this commit
adds some code to generate convergence intrinsics when required.

This commit is not to be submitted as-is (lacks testing), but
should serve as a basis for an upcoming RFC.

Signed-off-by: Nathan Gauër 
---
 clang/lib/CodeGen/CGBuiltin.cpp  | 102 +++
 clang/lib/CodeGen/CGCall.cpp |   4 ++
 clang/lib/CodeGen/CGLoopInfo.h   |   8 ++-
 clang/lib/CodeGen/CodeGenFunction.h  |  19 +
 llvm/include/llvm/IR/IntrinsicInst.h |  13 
 5 files changed, 145 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2eaceeba617700..9cc630cd05785a 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -1130,8 +1130,97 @@ struct BitTest {
 
   static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
 };
+
+// Returns the first convergence entry/loop/anchor instruction found in |BB|.
+// std::nullopt otherwise.
+std::optional getConvergenceToken(llvm::BasicBlock *BB) 
{
+  for (auto &I : *BB) {
+auto *II = dyn_cast(&I);
+if (II && isConvergenceControlIntrinsic(II->getIntrinsicID()))
+  return II;
+  }
+  return std::nullopt;
+}
+
 } // namespace
 
+llvm::CallBase *
+CodeGenFunction::AddConvergenceControlAttr(llvm::CallBase *Input,
+   llvm::Value *ParentToken) {
+  llvm::Value *bundleArgs[] = {ParentToken};
+  llvm::OperandBundleDef OB("convergencectrl", bundleArgs);
+  auto Output = llvm::CallBase::addOperandBundle(
+  Input, llvm::LLVMContext::OB_convergencectrl, OB, Input);
+  Input->replaceAllUsesWith(Output);
+  Input->eraseFromParent();
+  return Output;
+}
+
+llvm::IntrinsicInst *
+CodeGenFunction::EmitConvergenceLoop(llvm::BasicBlock *BB,
+ llvm::Value *ParentToken) {
+  CGBuilderTy::InsertPoint IP = Builder.saveIP();
+  Builder.SetInsertPoint(&BB->front());
+  auto CB = Builder.CreateIntrinsic(
+  llvm::Intrinsic::experimental_convergence_loop, {}, {});
+  Builder.restoreIP(IP);
+
+  auto I = AddConvergenceControlAttr(CB, ParentToken);
+  // Controlled convergence is incompatible with uncontrolled convergence.
+  // Removing any old attributes.
+  I->setNotConvergent();
+
+  assert(isa(I));
+  return dyn_cast(I);
+}
+
+llvm::IntrinsicInst *
+CodeGenFunction::getOrEmitConvergenceEntryToken(llvm::Function *F) {
+  auto *BB = &F->getEntryBlock();
+  auto token = getConvergenceToken(BB);
+  if (token.has_value())
+return token.value();
+
+  // Adding a convergence token requires the function to be marked as
+  // convergent.
+  F->setConvergent();
+
+  CGBuilderTy::InsertPoint IP = Builder.saveIP();
+  Builder.SetInsertPoint(&BB->front());
+  auto I = Builder.CreateIntrinsic(
+  llvm::Intrinsic::experimental_convergence_entry, {}, {});
+  assert(isa(I));
+  Builder.restoreIP(IP);
+
+  return dyn_cast(I);
+}
+
+llvm::IntrinsicInst *
+CodeGenFunction::getOrEmitConvergenceLoopToken(const LoopInfo *LI) {
+  assert(LI != nullptr);
+
+  auto token = getConvergenceToken(LI->getHeader());
+  if (token.has_value())
+return *token;
+
+  llvm::IntrinsicInst *PII =
+  LI->getParent()
+  ? EmitConvergenceLoop(LI->getHeader(),
+getOrEmitConvergenceLoopToken(LI->getParent()))
+  : getOrEmitConvergenceEntryToken(LI->getHeader()->getParent());
+
+  return EmitConvergenceLoop(LI->getHeader(), PII);
+}
+
+llvm::CallBase *
+CodeGenFunction::AddControlledConvergenceAttr(llvm::CallBase *Input) {
+  llvm::Value *ParentToken =
+  LoopStack.hasInfo()
+  ? getOrEmitConvergenceLoopToken(&LoopStack.getInfo())
+  : getOrEmitConvergenceEntryToken(Input->getFunction());
+  return AddConvergenceControlAttr(Input, ParentToken);
+}
+
 BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
   switch (BuiltinID) {
 // Main portable variants.
@@ -5801,6 +5890,19 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 {NDRange, Kernel, Block}));
   }
 
+  case Builtin::BI__builtin_hlsl_wave_active_count_bits: {
+llvm::Typ

[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-25 Thread Nathan Gauër via cfe-commits

Keenuts wrote:

Rebases on main (almost, HEAD is slightly broken), and added back the 
convergence attribute.
The backend changes are ready for this intrinsic.

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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

2024-03-25 Thread Jan Patrick Lehr via cfe-commits
Stefan =?utf-8?q?Gränitz?= 
Message-ID:
In-Reply-To: 


jplehr wrote:

Thanks! I am quite unfamiliar with that part of the code base and wonder if the 
symbol needs to just exist somewhere.
The other thing used there (`InitializeNativeTargetAsmPrinter`) is declared in 
`TargetSelect.h`. So, does it need to be a two parts fix: one to declare the 
symbol and then the magic to do the right thing at runtime. If what you linked 
does both, even better. :)

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


[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-25 Thread via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [[clang::always-destroy]] attribute silences warn-exit-time-destructor (PR #86486)

2024-03-25 Thread via cfe-commits

https://github.com/ycdtosa created 
https://github.com/llvm/llvm-project/pull/86486

user wants the warning silenced by the attribute
so no warning should be issued.

>From 016152bc21c2625db77d3e31a7123bcf08114133 Mon Sep 17 00:00:00 2001
From: ycdtosa 
Date: Mon, 25 Mar 2024 10:28:02 +
Subject: [PATCH] add test for [[clang::always-destroy]] attribute

user wants the warning silenced by the attribute
so no warning should be issued
---
 clang/lib/Sema/SemaDeclCXX.cpp| 3 ++-
 clang/test/SemaCXX/warn-exit-time-destructors.cpp | 6 ++
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index ee732679417e37..7070ea00cff275 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -16202,7 +16202,8 @@ void Sema::FinalizeVarWithDestructor(VarDecl *VD, const 
RecordType *Record) {
 
   // Emit warning for non-trivial dtor in global scope (a real global,
   // class-static, function-static).
-  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
+  if (!VD->hasAttr())
+Diag(VD->getLocation(), diag::warn_exit_time_destructor);
 
   // TODO: this should be re-enabled for static locals by !CXAAtExit
   if (!VD->isStaticLocal())
diff --git a/clang/test/SemaCXX/warn-exit-time-destructors.cpp 
b/clang/test/SemaCXX/warn-exit-time-destructors.cpp
index 2f14243cb48c47..8bd798c036333e 100644
--- a/clang/test/SemaCXX/warn-exit-time-destructors.cpp
+++ b/clang/test/SemaCXX/warn-exit-time-destructors.cpp
@@ -51,6 +51,11 @@ struct A { ~A(); };
 }
 
 namespace test5 {
+struct A { ~A(); };
+[[clang::always_destroy]] A a; // no warning
+}
+
+namespace test6 {
 #if __cplusplus >= 202002L
 #define CPP20_CONSTEXPR constexpr
 #else
@@ -68,3 +73,4 @@ namespace test5 {
   T t; // expected-warning {{exit-time destructor}}
 #undef CPP20_CONSTEXPR
 }
+

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


[clang] [[clang::always-destroy]] attribute silences warn-exit-time-destructor (PR #86486)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [[clang::always-destroy]] attribute silences warn-exit-time-destructor (PR #86486)

2024-03-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (ycdtosa)


Changes

user wants the warning silenced by the attribute
so no warning should be issued.

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+2-1) 
- (modified) clang/test/SemaCXX/warn-exit-time-destructors.cpp (+6) 


``diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index ee732679417e37..7070ea00cff275 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -16202,7 +16202,8 @@ void Sema::FinalizeVarWithDestructor(VarDecl *VD, const 
RecordType *Record) {
 
   // Emit warning for non-trivial dtor in global scope (a real global,
   // class-static, function-static).
-  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
+  if (!VD->hasAttr())
+Diag(VD->getLocation(), diag::warn_exit_time_destructor);
 
   // TODO: this should be re-enabled for static locals by !CXAAtExit
   if (!VD->isStaticLocal())
diff --git a/clang/test/SemaCXX/warn-exit-time-destructors.cpp 
b/clang/test/SemaCXX/warn-exit-time-destructors.cpp
index 2f14243cb48c47..8bd798c036333e 100644
--- a/clang/test/SemaCXX/warn-exit-time-destructors.cpp
+++ b/clang/test/SemaCXX/warn-exit-time-destructors.cpp
@@ -51,6 +51,11 @@ struct A { ~A(); };
 }
 
 namespace test5 {
+struct A { ~A(); };
+[[clang::always_destroy]] A a; // no warning
+}
+
+namespace test6 {
 #if __cplusplus >= 202002L
 #define CPP20_CONSTEXPR constexpr
 #else
@@ -68,3 +73,4 @@ namespace test5 {
   T t; // expected-warning {{exit-time destructor}}
 #undef CPP20_CONSTEXPR
 }
+

``




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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

2024-03-25 Thread Wang Pengcheng via cfe-commits


@@ -49,3 +49,62 @@ if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
   # despite potential dllexports.
   target_link_options(clangInterpreter PRIVATE LINKER:--export-all-symbols)
 endif()
+
+if(MSVC)
+  set_target_properties(clangInterpreter PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS 
1)
+
+  # RTTI/C++ symbols
+  set(clangInterpreter_exports ${clangInterpreter_exports} ??_7type_info@@6B@
+?__type_info_root_node@@3U__type_info_node@@A
+?nothrow@std@@3Unothrow_t@1@B
+  )
+
+  # Compiler added symbols for static variables. NOT for VStudio < 2015
+  set(clangInterpreter_exports ${clangInterpreter_exports} _Init_thread_abort 
_Init_thread_epoch
+_Init_thread_footer _Init_thread_header _tls_index
+  )
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+# new/delete variants needed when linking to static msvc runtime (esp. 
Debug)
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPEAX_K@Z
+  ??3@YAXPEAX@Z
+  ??_U@YAPEAX_K@Z
+  ??_V@YAXPEAX@Z
+  ??3@YAXPEAX_K@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@PEBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@P6AAEAV01@AEAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@PEBD@Z
+  ?_Facet_Register@std@@YAXPEAV_Facet_base@1@@Z
+)
+  else()
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPAXI@Z
+  ??3@YAXPAX@Z
+  ??3@YAXPAXI@Z
+  ??_U@YAPAXI@Z
+  ??_V@YAXPAX@Z
+  ??_V@YAXPAXI@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@P6AAAV01@AAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z
+  ?_Facet_Register@std@@YAXPAV_Facet_base@1@@Z
+)
+  endif()
+
+  # List to '/EXPORT:sym0 /EXPORT:sym1 /EXPORT:sym2 ...'
+  foreach(sym ${clangInterpreter_exports})
+set(clangInterpreter_link_str "${clangInterpreter_link_str} 
/EXPORT:${sym}")
+  endforeach(sym ${clangInterpreter_exports})
+
+  set_property(TARGET clangInterpreter APPEND_STRING PROPERTY LINK_FLAGS 
${clangInterpreter_link_str})
+
+endif(MSVC)

wangpc-pp wrote:

Yeah, I hope so. But I'm really not familiar with cmake. :-(
Maybe we can make it a TODO and fix it in #84769?


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


[clang] [[clang::always-destroy]] attribute silences warn-exit-time-destructor (PR #86486)

2024-03-25 Thread via cfe-commits

ycdtosa wrote:

this was lightly discussed in https://github.com/llvm/llvm-project/issues/68686

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Younan Zhang via cfe-commits

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

>From 6d61aa1e43bb522412904bdd77c7f1cfc4b42889 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 12:33:58 +0800
Subject: [PATCH 1/5] [clangd] Support go-to-definition on type hints. The
 protocol part

This is in preparation for implementing go-to-definition support
on type inlay hints, switching the label field within the InlayHint
protocol to an array of InlayHintLabelPart.
---
 clang-tools-extra/clangd/ClangdLSPServer.cpp  |  2 +-
 clang-tools-extra/clangd/InlayHints.cpp   |  8 +++-
 clang-tools-extra/clangd/Protocol.cpp | 40 +-
 clang-tools-extra/clangd/Protocol.h   | 41 ++-
 clang-tools-extra/clangd/test/inlayHints.test |  6 ++-
 clang-tools-extra/clangd/tool/Check.cpp   |  8 +++-
 .../clangd/unittests/InlayHintTests.cpp   |  9 ++--
 7 files changed, 103 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index f29dadde2b86d5..7fd599d4e1a0b0 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1390,7 +1390,7 @@ void ClangdLSPServer::onClangdInlayHints(const 
InlayHintsParams &Params,
   // Extension doesn't have paddingLeft/Right so adjust the label
   // accordingly.
   {"label",
-   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.label) +
+   ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.joinLabels()) 
+
 (Hint.paddingRight ? " " : ""))
.str()},
   });
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index a0ebc631ef8285..5a9ec9ab6762fa 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -977,8 +977,12 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   return;
 bool PadLeft = Prefix.consume_front(" ");
 bool PadRight = Suffix.consume_back(" ");
-Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
-PadLeft, PadRight, LSPRange});
+Results.push_back(InlayHint{LSPPos,
+/*label=*/{(Prefix + Label + Suffix).str()},
+Kind,
+PadLeft,
+PadRight,
+LSPRange});
   }
 
   // Get the range of the main file that *exactly* corresponds to R.
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index 8aa18bb0058abe..b1e29953337256 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},
 {"paddingLeft", H.paddingLeft},
 {"paddingRight", H.paddingRight}};
   auto K = toJSON(H.kind);
@@ -1501,6 +1510,10 @@ bool operator<(const InlayHint &A, const InlayHint &B) {
   return std::tie(A.position, A.range, A.kind, A.label) <
  std::tie(B.position, B.range, B.kind, B.label);
 }
+std::string InlayHint::joinLabels() const {
+  return llvm::join(llvm::map_range(label, [](auto &L) { return L.value; }),
+"");
+}
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
   auto ToString = [](InlayHintKind K) {
@@ -1519,6 +1532,31 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 
InlayHintKind Kind) {
   return OS << ToString(Kind);
 }
 
+llvm::json::Value toJSON(const InlayHintLabelPart &L) {
+  llvm::json::Object Result{{"value", L.value}};
+  if (L.tooltip)
+Result["tooltip"] = *L.tooltip;
+  if (L.location)
+Result["location"] = *L.location;
+  return Result;
+}
+
+bool operator==(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) == std::tie(RHS.value, 
RHS.location);
+}
+
+bool operator<(const InlayHintLabelPart &LHS, const InlayHintLabelPart &RHS) {
+  return std::tie(LHS.value, LHS.location) < std::tie(RHS.value, RHS.location);
+}
+
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
+  const InlayHintLabelPart &L) {
+  OS << L.value;
+  if (L.location)
+OS << " (" << L.location << ")";
+  return OS;
+}
+
 static const char *toString(OffsetEncoding OE) {
   switch (OE) {
   case Of

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread Younan Zhang via cfe-commits


@@ -1483,9 +1483,18 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
   llvm_unreachable("Unknown clang.clangd.InlayHintKind");
 }
 
+namespace {
+
+llvm::json::Array toJSON(const std::vector &Labels) {
+  return llvm::json::Array{
+  llvm::map_range(Labels, [](auto &Label) { return toJSON(Label); })};
+}
+
+} // namespace
+
 llvm::json::Value toJSON(const InlayHint &H) {
   llvm::json::Object Result{{"position", H.position},
-{"label", H.label},
+{"label", toJSON(H.label)},

zyn0217 wrote:

Ah, good catch! I didn't realize there's such an overload previously...

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The protocol part (PR #85497)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] 13078cb - [clang-repl] Skip cross-JIT tests if specified target is not available (#84461)

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

Author: Stefan Gränitz
Date: 2024-03-25T11:50:21+01:00
New Revision: 13078cbc3eeb0ae91c370ce0f604f7165b26e0c8

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

LOG: [clang-repl] Skip cross-JIT tests if specified target is not available 
(#84461)

Added: 


Modified: 
clang/unittests/Interpreter/InterpreterExtensionsTest.cpp

Removed: 




diff  --git a/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp 
b/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
index 8bc429d9ec2d7d..1ba865a79ed778 100644
--- a/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
@@ -19,6 +19,7 @@
 
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
+#include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/Threading.h"
@@ -44,14 +45,23 @@ static bool HostSupportsJit() {
   return false;
 }
 
+// Some tests require a arm-registered-target
+static bool IsARMTargetRegistered() {
+  llvm::Triple TT;
+  TT.setArch(llvm::Triple::arm);
+  TT.setVendor(llvm::Triple::UnknownVendor);
+  TT.setOS(llvm::Triple::UnknownOS);
+
+  std::string UnusedErr;
+  return llvm::TargetRegistry::lookupTarget(TT.str(), UnusedErr);
+}
+
 struct LLVMInitRAII {
   LLVMInitRAII() {
-llvm::InitializeNativeTarget();
-llvm::InitializeNativeTargetAsmPrinter();
-LLVMInitializeARMTarget();
-LLVMInitializeARMTargetInfo();
-LLVMInitializeARMTargetMC();
-LLVMInitializeARMAsmPrinter();
+llvm::InitializeAllTargets();
+llvm::InitializeAllTargetInfos();
+llvm::InitializeAllTargetMCs();
+llvm::InitializeAllAsmPrinters();
   }
   ~LLVMInitRAII() { llvm::llvm_shutdown(); }
 } LLVMInit;
@@ -190,6 +200,9 @@ TEST(InterpreterExtensionsTest, DISABLED_DefaultCrossJIT) {
 #else
 TEST(InterpreterExtensionsTest, DefaultCrossJIT) {
 #endif
+  if (!IsARMTargetRegistered())
+GTEST_SKIP();
+
   IncrementalCompilerBuilder CB;
   CB.SetTargetTriple("armv6-none-eabi");
   auto CI = cantFail(CB.CreateCpp());
@@ -204,6 +217,9 @@ TEST(InterpreterExtensionsTest, DISABLED_CustomCrossJIT) {
 #else
 TEST(InterpreterExtensionsTest, CustomCrossJIT) {
 #endif
+  if (!IsARMTargetRegistered())
+GTEST_SKIP();
+
   std::string TargetTriple = "armv6-none-eabi";
 
   IncrementalCompilerBuilder CB;



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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

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

weliveindetail wrote:

We do need the target and not just the symbols. It could be any non-native 
target, but implementing a selection mechanism isn't worth the effort. We just 
try ARM and (with my above patch) otherwise skip the test.

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-25 Thread Iain Sandoe via cfe-commits

https://github.com/iains commented:


I have no issue with the general intention or phasing here; my main concern is 
that we are introducing [yet] another user-facing modules option that actually 
we intend will become irrelevant after a few releases.

In practice, removing user-facing options is not very easy.

So:
  1. Perhaps we could have only the cc1 option and you could introduce some 
temporary handling in the driver to recognise it and amend the --precompile 
behaviour?
  2. Maybe the project could introduce something like -fexperimental-- 
with a clear statement that fexperimental flags cannot be relied on to be 
stable (or even present) in any future release)?

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-25 Thread Iain Sandoe via cfe-commits


@@ -3031,6 +3032,11 @@ defm skip_odr_check_in_gmf : BoolOption<"f", 
"skip-odr-check-in-gmf",
   "Perform ODR checks for decls in the global module fragment.">>,
   Group;
 
+def gen_reduced_bmi : Flag<["-"], "fgen-reduced-bmi">,

iains wrote:

If this is going to be a user-facing flag (even for a few releases) then I 
think it should be spelled in a way that make it modules-relatated (e.g. 
-fmodules-reduce-bmi, or -fmodules-minimise-bmi),  as you know I'm not a fan of 
increasing the already huge number of modules-related user-facing options... 
(but I'll comment on that separately)

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


[clang] [C++20] [Modules] Introduce -fgen-reduced-bmi (PR #85050)

2024-03-25 Thread Iain Sandoe via cfe-commits

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


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

2024-03-25 Thread Jan Patrick Lehr via cfe-commits
Stefan =?utf-8?q?Gr=C3=A4nitz?= 
Message-ID:
In-Reply-To: 


jplehr wrote:

I see. Thanks for the explanation and the fix! Bot is back to green.

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


[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread Balazs Benics via cfe-commits
=?utf-8?q?Don=C3=A1t?= Nagy ,
=?utf-8?q?Don=C3=A1t?= Nagy ,NagyDonat
 ,NagyDonat 
Message-ID:
In-Reply-To: 


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


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


[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)

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


@@ -49,3 +49,62 @@ if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
   # despite potential dllexports.
   target_link_options(clangInterpreter PRIVATE LINKER:--export-all-symbols)
 endif()
+
+if(MSVC)
+  set_target_properties(clangInterpreter PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS 
1)
+
+  # RTTI/C++ symbols
+  set(clangInterpreter_exports ${clangInterpreter_exports} ??_7type_info@@6B@
+?__type_info_root_node@@3U__type_info_node@@A
+?nothrow@std@@3Unothrow_t@1@B
+  )
+
+  # Compiler added symbols for static variables. NOT for VStudio < 2015
+  set(clangInterpreter_exports ${clangInterpreter_exports} _Init_thread_abort 
_Init_thread_epoch
+_Init_thread_footer _Init_thread_header _tls_index
+  )
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+# new/delete variants needed when linking to static msvc runtime (esp. 
Debug)
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPEAX_K@Z
+  ??3@YAXPEAX@Z
+  ??_U@YAPEAX_K@Z
+  ??_V@YAXPEAX@Z
+  ??3@YAXPEAX_K@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@PEBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@P6AAEAV01@AEAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@PEBD@Z
+  ?_Facet_Register@std@@YAXPEAV_Facet_base@1@@Z
+)
+  else()
+set(clangInterpreter_exports ${clangInterpreter_exports}
+  ??2@YAPAXI@Z
+  ??3@YAXPAX@Z
+  ??3@YAXPAXI@Z
+  ??_U@YAPAXI@Z
+  ??_V@YAXPAX@Z
+  ??_V@YAXPAXI@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@M@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@N@Z
+  ??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z
+  
??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@P6AAAV01@AAV01@@Z@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@D@Z
+  
??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z
+  ?_Facet_Register@std@@YAXPAV_Facet_base@1@@Z
+)
+  endif()
+
+  # List to '/EXPORT:sym0 /EXPORT:sym1 /EXPORT:sym2 ...'
+  foreach(sym ${clangInterpreter_exports})
+set(clangInterpreter_link_str "${clangInterpreter_link_str} 
/EXPORT:${sym}")
+  endforeach(sym ${clangInterpreter_exports})
+
+  set_property(TARGET clangInterpreter APPEND_STRING PROPERTY LINK_FLAGS 
${clangInterpreter_link_str})
+
+endif(MSVC)

AaronBallman wrote:

CC @petrhosek @Ericson2314 for CMake code owner expertise

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

2024-03-25 Thread via cfe-commits

Sirraide wrote:

I’m the wrong person to ping if it’s anything codegen-related; I’ll leave 
reviewing this to people more familiar w/ that part of Clang.

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


[clang] [clang][CodeComplete] Handle deref operator in getApproximateType (PR #86466)

2024-03-25 Thread Younan Zhang via cfe-commits

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

Thanks. LGTM apart from one nit.

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


[clang] [clang][CodeComplete] Handle deref operator in getApproximateType (PR #86466)

2024-03-25 Thread Younan Zhang via cfe-commits


@@ -5674,6 +5675,11 @@ QualType getApproximateType(const Expr *E) {
 return getApproximateType(VD->getInit());
 }
   }
+  if (const auto *UO = llvm::dyn_cast(E)) {
+if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) {

zyn0217 wrote:

nit: We 
[don't](https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements)
 usually wrap a single statement with braces.

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


[clang] [clang][CodeComplete] Handle deref operator in getApproximateType (PR #86466)

2024-03-25 Thread Younan Zhang via cfe-commits

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


[clang] [llvm] [mlir] [OpenMP] Migrate GPU Reductions CodeGen from Clang to OMPIRBuilder (PR #80343)

2024-03-25 Thread Akash Banerjee via cfe-commits

TIFitis wrote:

@jdoerfert @jsjodin polite ping for review.

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


[clang] [analyzer] Set and display CSA analysis entry points as notes on debugging (PR #84823)

2024-03-25 Thread via cfe-commits

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


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


[clang] e1d4ddb - Reapply "[analyzer] Accept C library functions from the `std` namespace" again (#85791)

2024-03-25 Thread via cfe-commits

Author: NagyDonat
Date: 2024-03-25T12:43:51+01:00
New Revision: e1d4ddb0c68f69001d7de43d9c678f4d73c1ecba

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

LOG: Reapply "[analyzer] Accept C library functions from the `std` namespace" 
again (#85791)

This reapplies 80ab8234ac309418637488b97e0a62d8377b2ecf again, after
fixing a name collision warning in the unit tests (see the revert commit
13ccaf9b9d4400bb128b35ff4ac733e4afc3ad1c for details).

In addition to the previously applied changes, this commit also clarifies the
code in MallocChecker that distinguishes POSIX "getline()" and C++ standard
library "std::getline()" (which are two completely different functions). Note
that "std::getline()" was (accidentally) handled correctly even without this
clarification; but it's better to explicitly handle and test this corner case.

-

Co-authored-by: Balazs Benics 

Added: 
clang/test/Analysis/getline-cpp.cpp
clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
clang/test/Analysis/Inputs/system-header-simulator-cxx.h
clang/unittests/StaticAnalyzer/CMakeLists.txt
llvm/utils/gn/secondary/clang/unittests/StaticAnalyzer/BUILD.gn

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 3432d2648633c2..b4e1636130ca7c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -41,12 +41,8 @@ class CallDescription {
 ///  - We also accept calls where the number of arguments or parameters is
 ///greater than the specified value.
 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
-/// Note that functions whose declaration context is not a TU (e.g.
-/// methods, functions in namespaces) are not accepted as C library
-/// functions.
-/// FIXME: If I understand it correctly, this discards calls where C++ code
-/// refers a C library function through the namespace `std::` via headers
-/// like .
+/// (This mode only matches functions that are declared either directly
+/// within a TU or in the namespace `std`.)
 CLibrary,
 
 /// Matches "simple" functions that are not methods. (Static methods are

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index c2d96f59260906..88fb42b6625aa4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -394,8 +394,10 @@ class MallocChecker
  const CallEvent &Call, CheckerContext 
&C)>;
 
   const CallDescriptionMap PreFnMap{
-  {{{"getline"}, 3}, &MallocChecker::preGetdelim},
-  {{{"getdelim"}, 4}, &MallocChecker::preGetdelim},
+  // NOTE: the following CallDescription also matches the C++ standard
+  // library function std::getline(); the callback will filter it out.
+  {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::preGetdelim},
+  {{CDM::CLibrary, {"getdelim"}, 4}, &MallocChecker::preGetdelim},
   };
 
   const CallDescriptionMap FreeingMemFnMap{
@@ -446,8 +448,11 @@ class MallocChecker
std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
   {{{"g_realloc_n"}, 3}, &MallocChecker::checkReallocN},
   {{{"g_try_realloc_n"}, 3}, &MallocChecker::checkReallocN},
-  {{{"getline"}, 3}, &MallocChecker::checkGetdelim},
-  {{{"getdelim"}, 4}, &MallocChecker::checkGetdelim},
+
+  // NOTE: the following CallDescription also matches the C++ standard
+  // library function std::getline(); the callback will filter it out.
+  {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::checkGetdelim},
+  {{CDM::CLibrary, {"getdelim"}, 4}, &MallocChecker::checkGetdelim},
   };
 
   bool isMemCall(const CallEvent &Call) const;
@@ -1435,9 +1440,17 @@ void MallocChecker::checkGMallocN0(const CallEvent &Call,
   C.addTransition(State);
 }
 
+static bool isFromStdNamespace(const CallEvent &Call) {
+  const Decl *FD = Call.getDecl();
+  assert(FD && "a CallDescription cannot match a call without a Decl");
+  return FD->isInStdNamespace();
+}
+
 void MallocChecker::preGetdelim(const CallEvent &Call,
 CheckerContext &C) const {
-  if (!Call.isGlobalCFunction())
+  // Discard calls to the C++ standard library function std::getline(), which
+  // is completely unrelated to the POSIX getline() tha

[clang] [llvm] Reapply "[analyzer] Accept C library functions from the `std` namespace" again (PR #85791)

2024-03-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy ,NagyDonat
 ,NagyDonat 
Message-ID:
In-Reply-To: 


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


[clang] [clang-tools-extra] [compiler-rt] [flang] [lld] [lldb] [llvm] [mlir] [openmp] [pstl] Finally formalise our defacto line-ending policy (PR #86318)

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

https://github.com/AaronBallman commented:

The changes seem reasonable to me, but there are test failures in 
`llvm/utils/lit/tests` that could perhaps be related to your changes.

I think .natvis files should be CRLF (those are used with Visual Studio for 
debug visualizers).

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


[clang] [X86_64] fix SSE type error in vaarg. (PR #86377)

2024-03-25 Thread Longsheng Mou via cfe-commits


@@ -21,3 +21,18 @@ empty empty_record_test(int z, ...) {
   __builtin_va_start(list, z);
   return __builtin_va_arg(list, empty);
 }
+

CoTinker wrote:

done

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


[clang] Fix printing of templated records. (PR #86339)

2024-03-25 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/86339

>From ab7d280abf053b67b716e0723e2e70876e639810 Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat 
Date: Fri, 22 Mar 2024 13:55:44 -0700
Subject: [PATCH 1/2] Fix printing of templated records.

---
 clang/lib/AST/TypePrinter.cpp   |  5 -
 clang/unittests/AST/DeclPrinterTest.cpp | 21 +
 2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 7032ff2f18468c..d9504f9dcb3899 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2303,11 +2303,6 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 } else {
   if (!FirstArg)
 OS << Comma;
-  if (!Policy.SuppressTagKeyword &&
-  Argument.getKind() == TemplateArgument::Type &&
-  isa(Argument.getAsType()))
-OS << Argument.getAsType().getAsString();
-  else
 // Tries to print the argument with location info if exists.
 printArgument(Arg, Policy, ArgOS,
   TemplateParameterList::shouldIncludeTypeForArgument(
diff --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index e024c41e03b484..f0e360f9caf44a 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1386,6 +1386,27 @@ TEST(DeclPrinter, TestTemplateArgumentList16) {
   ASSERT_TRUE(PrintedDeclCXX11Matches(Code, "NT2", "int NT2 = 5"));
 }
 
+TEST(DeclPrinter, TestCXXRecordDecl17) {
+  ASSERT_TRUE(PrintedDeclCXX98Matches("template struct Z {};"
+  "struct X {};"
+  "Z A;",
+  "A",
+  "Z A"));
+  [](PrintingPolicy &Policy) { Policy.SuppressTagKeyword = false; };
+}
+
+TEST(DeclPrinter, TestCXXRecordDecl18) {
+  ASSERT_TRUE(PrintedDeclCXX98Matches("template struct Z {};"
+  "struct X {};"
+  "Z A;" 
+  "template "
+  "struct Y{};"
+  "Y, 2> B;",
+  "B", 
+  "Y, 2> B"));
+  [](PrintingPolicy &Policy) { Policy.SuppressTagKeyword = false; };
+}
+
 TEST(DeclPrinter, TestFunctionParamUglified) {
   llvm::StringLiteral Code = R"cpp(
 class __c;

>From b1623cab26804c368adfea2eec17663e5a04f8d8 Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat 
Date: Mon, 25 Mar 2024 05:04:47 -0700
Subject: [PATCH 2/2] Fixed format and added tests.

---
 clang/unittests/AST/DeclPrinterTest.cpp | 58 ++---
 1 file changed, 53 insertions(+), 5 deletions(-)

diff --git a/clang/unittests/AST/DeclPrinterTest.cpp 
b/clang/unittests/AST/DeclPrinterTest.cpp
index f0e360f9caf44a..07fa02bd96e25d 100644
--- a/clang/unittests/AST/DeclPrinterTest.cpp
+++ b/clang/unittests/AST/DeclPrinterTest.cpp
@@ -1390,23 +1390,71 @@ TEST(DeclPrinter, TestCXXRecordDecl17) {
   ASSERT_TRUE(PrintedDeclCXX98Matches("template struct Z {};"
   "struct X {};"
   "Z A;",
-  "A",
-  "Z A"));
+  "A", "Z A"));
   [](PrintingPolicy &Policy) { Policy.SuppressTagKeyword = false; };
 }
 
 TEST(DeclPrinter, TestCXXRecordDecl18) {
   ASSERT_TRUE(PrintedDeclCXX98Matches("template struct Z {};"
   "struct X {};"
-  "Z A;" 
+  "Z A;"
   "template "
   "struct Y{};"
   "Y, 2> B;",
-  "B", 
-  "Y, 2> B"));
+  "B", "Y, 2> B"));
   [](PrintingPolicy &Policy) { Policy.SuppressTagKeyword = false; };
 }
 
+TEST(DeclPrinter, TestCXXRecordDecl19) {
+  ASSERT_TRUE(PrintedDeclCXX98Matches("template struct Z {};"
+  "struct X {};"
+  "Z A;"
+  "template "
+  "struct Y{};"
+  "Y, 2> B;",
+  "B", "Y, 2> B"));
+  [](PrintingPolicy &Policy) { Policy.SuppressTagKeyword = true; };
+}
+TEST(DeclPrinter, TestCXXRecordDecl20) {
+  ASSERT_TRUE(PrintedDeclCXX98Matches(
+  "template  class Inner;"
+  "template "
+  "class Inner{Inner(T val){}};"
+  "template  class Outer {"
+  "public:"
+  "struct NestedStruct {"
+  "int nestedValue;"
+  "NestedStruct(int

[clang] Fix printing of templated records. (PR #86339)

2024-03-25 Thread Zahira Ammarguellat via cfe-commits

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


[clang] [FMV] Allow mixing target_version with target_clones. (PR #86493)

2024-03-25 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/86493

The latest ACLE allows it and further clarifies the following
in regards to the combination of the two attributes:

"If the `default` matches with another explicitly provided
 version in the same translation unit, then the compiler can
 emit only one function instead of the two. The explicitly
 provided version shall be preferred."

("default" refers to the default clone here)

https://github.com/ARM-software/acle/pull/310

>From 65bfc47298131d6fb5dfeed722dc3f2d9d85eadd Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Fri, 22 Mar 2024 17:21:13 +
Subject: [PATCH] [FMV] Allow mixing target_version with target_clones.

The latest ACLE allows it and further clarifies the following
in regards to the combination of the two attributes:

"If the `default` matches with another explicitly provided
 version in the same translation unit, then the compiler can
 emit only one function instead of the two. The explicitly
 provided version shall be preferred."

("default" refers to the default clone here)

https://github.com/ARM-software/acle/pull/310
---
 clang/include/clang/Basic/Attr.td |  14 +
 clang/lib/AST/ASTContext.cpp  |  15 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 105 ---
 clang/lib/Sema/SemaDecl.cpp   | 192 
 .../CodeGen/aarch64-mixed-target-attributes.c | 278 ++
 .../test/CodeGen/attr-target-clones-aarch64.c |  94 +++---
 .../CodeGenCXX/attr-target-clones-aarch64.cpp |  28 +-
 clang/test/Sema/attr-target-clones-aarch64.c  |   2 +-
 8 files changed, 539 insertions(+), 189 deletions(-)
 create mode 100644 clang/test/CodeGen/aarch64-mixed-target-attributes.c

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e03e55612645b..318d4e5ac5ba44 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3088,6 +3088,20 @@ def TargetClones : InheritableAttr {
 StringRef getFeatureStr(unsigned Index) const {
   return *(featuresStrs_begin() + Index);
 }
+bool isDefaultVersion(unsigned Index) const {
+  return getFeatureStr(Index) == "default";
+}
+void getFeatures(llvm::SmallVectorImpl &Out,
+ unsigned Index) const {
+  if (isDefaultVersion(Index)) return;
+  StringRef Features = getFeatureStr(Index);
+  SmallVector AttrFeatures;
+  Features.split(AttrFeatures, "+");
+  for (auto &Feature : AttrFeatures) {
+Feature = Feature.trim();
+Out.push_back(Feature);
+  }
+}
 // Given an index into the 'featuresStrs' sequence, compute a unique
 // ID to be used with function name mangling for the associated variant.
 // This mapping is necessary due to a requirement that the mangling ID
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index fcf801adeaf5ef..0b5f20a572a742 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -13676,22 +13676,19 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
   } else if (const auto *TC = FD->getAttr()) {
 std::vector Features;
-StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
 if (Target->getTriple().isAArch64()) {
   // TargetClones for AArch64
-  if (VersionStr != "default") {
-SmallVector VersionFeatures;
-VersionStr.split(VersionFeatures, "+");
-for (auto &VFeature : VersionFeatures) {
-  VFeature = VFeature.trim();
+  llvm::SmallVector Feats;
+  TC->getFeatures(Feats, GD.getMultiVersionIndex());
+  for (StringRef Feat : Feats)
+if (Target->validateCpuSupports(Feat.str()))
   // Use '?' to mark features that came from AArch64 TargetClones.
-  Features.push_back((StringRef{"?"} + VFeature).str());
-}
-  }
+  Features.push_back("?" + Feat.str());
   Features.insert(Features.begin(),
   Target->getTargetOpts().FeaturesAsWritten.begin(),
   Target->getTargetOpts().FeaturesAsWritten.end());
 } else {
+  StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
   if (VersionStr.starts_with("arch="))
 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
   else if (VersionStr != "default")
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index ac81df8cf7adfe..bc7d7ac561113b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3712,7 +3712,8 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
   if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
-  !FD->isTargetVersionMultiVersi

[clang] [FMV] Allow mixing target_version with target_clones. (PR #86493)

2024-03-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Alexandros Lamprineas (labrinea)


Changes

The latest ACLE allows it and further clarifies the following
in regards to the combination of the two attributes:

"If the `default` matches with another explicitly provided
 version in the same translation unit, then the compiler can
 emit only one function instead of the two. The explicitly
 provided version shall be preferred."

("default" refers to the default clone here)

https://github.com/ARM-software/acle/pull/310

---

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


8 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+14) 
- (modified) clang/lib/AST/ASTContext.cpp (+6-9) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+50-55) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+129-63) 
- (added) clang/test/CodeGen/aarch64-mixed-target-attributes.c (+278) 
- (modified) clang/test/CodeGen/attr-target-clones-aarch64.c (+47-47) 
- (modified) clang/test/CodeGenCXX/attr-target-clones-aarch64.cpp (+14-14) 
- (modified) clang/test/Sema/attr-target-clones-aarch64.c (+1-1) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e03e55612645b..318d4e5ac5ba44 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3088,6 +3088,20 @@ def TargetClones : InheritableAttr {
 StringRef getFeatureStr(unsigned Index) const {
   return *(featuresStrs_begin() + Index);
 }
+bool isDefaultVersion(unsigned Index) const {
+  return getFeatureStr(Index) == "default";
+}
+void getFeatures(llvm::SmallVectorImpl &Out,
+ unsigned Index) const {
+  if (isDefaultVersion(Index)) return;
+  StringRef Features = getFeatureStr(Index);
+  SmallVector AttrFeatures;
+  Features.split(AttrFeatures, "+");
+  for (auto &Feature : AttrFeatures) {
+Feature = Feature.trim();
+Out.push_back(Feature);
+  }
+}
 // Given an index into the 'featuresStrs' sequence, compute a unique
 // ID to be used with function name mangling for the associated variant.
 // This mapping is necessary due to a requirement that the mangling ID
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index fcf801adeaf5ef..0b5f20a572a742 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -13676,22 +13676,19 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
   } else if (const auto *TC = FD->getAttr()) {
 std::vector Features;
-StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
 if (Target->getTriple().isAArch64()) {
   // TargetClones for AArch64
-  if (VersionStr != "default") {
-SmallVector VersionFeatures;
-VersionStr.split(VersionFeatures, "+");
-for (auto &VFeature : VersionFeatures) {
-  VFeature = VFeature.trim();
+  llvm::SmallVector Feats;
+  TC->getFeatures(Feats, GD.getMultiVersionIndex());
+  for (StringRef Feat : Feats)
+if (Target->validateCpuSupports(Feat.str()))
   // Use '?' to mark features that came from AArch64 TargetClones.
-  Features.push_back((StringRef{"?"} + VFeature).str());
-}
-  }
+  Features.push_back("?" + Feat.str());
   Features.insert(Features.begin(),
   Target->getTargetOpts().FeaturesAsWritten.begin(),
   Target->getTargetOpts().FeaturesAsWritten.end());
 } else {
+  StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
   if (VersionStr.starts_with("arch="))
 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
   else if (VersionStr != "default")
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index ac81df8cf7adfe..bc7d7ac561113b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3712,7 +3712,8 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
   if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
-  !FD->isTargetVersionMultiVersion())
+  (!FD->isMultiVersion() ||
+   !FD->getASTContext().getTargetInfo().getTriple().isAArch64()))
 return;
 
   StringRef MangledName = getMangledName(GD);
@@ -3994,10 +3995,11 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 auto *Spec = FD->getAttr();
 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
   EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
-  } else if (FD->isTargetClonesMultiVersion()) {
-auto *Clone = FD->getAttr();
-for (unsigned I = 0; I < Clone->fe

[clang] [FMV] Allow mixing target_version with target_clones. (PR #86493)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 13078cbc3eeb0ae91c370ce0f604f7165b26e0c8 
65bfc47298131d6fb5dfeed722dc3f2d9d85eadd -- 
clang/test/CodeGen/aarch64-mixed-target-attributes.c 
clang/lib/AST/ASTContext.cpp clang/lib/CodeGen/CodeGenModule.cpp 
clang/lib/Sema/SemaDecl.cpp clang/test/CodeGen/attr-target-clones-aarch64.c 
clang/test/CodeGenCXX/attr-target-clones-aarch64.cpp 
clang/test/Sema/attr-target-clones-aarch64.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b1f2749c40..9a286e0b26 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11471,8 +11471,7 @@ static bool 
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
   return false;
 }
 
-static
-void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
+static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
   if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
 return;
 
@@ -11480,8 +11479,8 @@ void patchDefaultTargetVersion(FunctionDecl *From, 
FunctionDecl *To) {
   MultiVersionKind MVKindTo = To->getMultiVersionKind();
 
   if (MVKindTo == MultiVersionKind::None &&
- (MVKindFrom == MultiVersionKind::TargetVersion ||
-  MVKindFrom == MultiVersionKind::TargetClones)) {
+  (MVKindFrom == MultiVersionKind::TargetVersion ||
+   MVKindFrom == MultiVersionKind::TargetClones)) {
 To->setIsMultiVersion();
 To->addAttr(TargetVersionAttr::CreateImplicit(
 To->getASTContext(), "default", To->getSourceRange()));
@@ -11599,8 +11598,7 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   return false;
 }
 
-static bool MultiVersionTypesCompatible(FunctionDecl *Old,
-FunctionDecl *New) {
+static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
   MultiVersionKind OldKind = Old->getMultiVersionKind();
   MultiVersionKind NewKind = New->getMultiVersionKind();
 

``




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


[clang] [FMV] Allow mixing target_version with target_clones. (PR #86493)

2024-03-25 Thread via cfe-commits

github-actions[bot] wrote:



:white_check_mark: With the latest revision this PR passed the Python code 
formatter.

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


[clang] [FMV] Allow mixing target_version with target_clones. (PR #86493)

2024-03-25 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea updated 
https://github.com/llvm/llvm-project/pull/86493

>From dfef9d04c0a65423a051ac00044b39f8911aa731 Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Fri, 22 Mar 2024 17:21:13 +
Subject: [PATCH] [FMV] Allow mixing target_version with target_clones.

The latest ACLE allows it and further clarifies the following
in regards to the combination of the two attributes:

"If the `default` matches with another explicitly provided
 version in the same translation unit, then the compiler can
 emit only one function instead of the two. The explicitly
 provided version shall be preferred."

("default" refers to the default clone here)

https://github.com/ARM-software/acle/pull/310
---
 clang/include/clang/Basic/Attr.td |  14 +
 clang/lib/AST/ASTContext.cpp  |  15 +-
 clang/lib/CodeGen/CodeGenModule.cpp   | 105 ---
 clang/lib/Sema/SemaDecl.cpp   | 190 
 .../CodeGen/aarch64-mixed-target-attributes.c | 278 ++
 .../test/CodeGen/attr-target-clones-aarch64.c |  94 +++---
 .../CodeGenCXX/attr-target-clones-aarch64.cpp |  28 +-
 clang/test/Sema/attr-target-clones-aarch64.c  |   2 +-
 8 files changed, 537 insertions(+), 189 deletions(-)
 create mode 100644 clang/test/CodeGen/aarch64-mixed-target-attributes.c

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e03e55612645b..318d4e5ac5ba44 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3088,6 +3088,20 @@ def TargetClones : InheritableAttr {
 StringRef getFeatureStr(unsigned Index) const {
   return *(featuresStrs_begin() + Index);
 }
+bool isDefaultVersion(unsigned Index) const {
+  return getFeatureStr(Index) == "default";
+}
+void getFeatures(llvm::SmallVectorImpl &Out,
+ unsigned Index) const {
+  if (isDefaultVersion(Index)) return;
+  StringRef Features = getFeatureStr(Index);
+  SmallVector AttrFeatures;
+  Features.split(AttrFeatures, "+");
+  for (auto &Feature : AttrFeatures) {
+Feature = Feature.trim();
+Out.push_back(Feature);
+  }
+}
 // Given an index into the 'featuresStrs' sequence, compute a unique
 // ID to be used with function name mangling for the associated variant.
 // This mapping is necessary due to a requirement that the mangling ID
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index fcf801adeaf5ef..0b5f20a572a742 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -13676,22 +13676,19 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
   } else if (const auto *TC = FD->getAttr()) {
 std::vector Features;
-StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
 if (Target->getTriple().isAArch64()) {
   // TargetClones for AArch64
-  if (VersionStr != "default") {
-SmallVector VersionFeatures;
-VersionStr.split(VersionFeatures, "+");
-for (auto &VFeature : VersionFeatures) {
-  VFeature = VFeature.trim();
+  llvm::SmallVector Feats;
+  TC->getFeatures(Feats, GD.getMultiVersionIndex());
+  for (StringRef Feat : Feats)
+if (Target->validateCpuSupports(Feat.str()))
   // Use '?' to mark features that came from AArch64 TargetClones.
-  Features.push_back((StringRef{"?"} + VFeature).str());
-}
-  }
+  Features.push_back("?" + Feat.str());
   Features.insert(Features.begin(),
   Target->getTargetOpts().FeaturesAsWritten.begin(),
   Target->getTargetOpts().FeaturesAsWritten.end());
 } else {
+  StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
   if (VersionStr.starts_with("arch="))
 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
   else if (VersionStr != "default")
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index ac81df8cf7adfe..bc7d7ac561113b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3712,7 +3712,8 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
   if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
-  !FD->isTargetVersionMultiVersion())
+  (!FD->isMultiVersion() ||
+   !FD->getASTContext().getTargetInfo().getTriple().isAArch64()))
 return;
 
   StringRef MangledName = getMangledName(GD);
@@ -3994,10 +3995,11 @@ void 
CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
 auto *Spec = FD->getAttr();
 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
   EmitGlobalFunctionDefinition(GD.getWithMultiVersion

[clang] [clang][dataflow] Bail out if input is Objective-C++. (PR #86479)

2024-03-25 Thread Yitzhak Mandelbaum via cfe-commits

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

Thanks!

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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

https://github.com/AaronBallman commented:

Hopefully @rjmccall or @efriedma-quic can take a look at the codegen bits. I 
did have some questions about other kinds of flow control statements we might 
want to cover.

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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


@@ -2503,6 +2505,26 @@ Stmt *BlockExpr::getBody() {
 // Generic Expression Routines
 
//===--===//
 
+bool Expr::mayBranchOut() const {
+  struct BranchDetector : public RecursiveASTVisitor {
+bool HasBranch = false;
+bool activate() {
+  HasBranch = true;
+  return false;
+}
+// Coroutine suspensions.
+bool VisitCoawaitExpr(CoawaitExpr *) { return activate(); }
+bool VisitCoyieldExpr(CoyieldExpr *) { return activate(); }
+// Control flow in stmt-expressions.
+bool VisitBreakStmt(BreakStmt *) { return activate(); }
+bool VisitReturnStmt(ReturnStmt *) { return activate(); }
+bool VisitGotoStmt(GotoStmt *) { return activate(); }
+  };

AaronBallman wrote:

Should we consider `throw` to be a kind of branching control flow as well?

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


[clang] [codegen] Emit missing cleanups for stmt-expr and coro suspensions [take-2] (PR #85398)

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


@@ -2503,6 +2505,26 @@ Stmt *BlockExpr::getBody() {
 // Generic Expression Routines
 
//===--===//
 
+bool Expr::mayBranchOut() const {
+  struct BranchDetector : public RecursiveASTVisitor {
+bool HasBranch = false;
+bool activate() {
+  HasBranch = true;
+  return false;
+}
+// Coroutine suspensions.
+bool VisitCoawaitExpr(CoawaitExpr *) { return activate(); }
+bool VisitCoyieldExpr(CoyieldExpr *) { return activate(); }
+// Control flow in stmt-expressions.
+bool VisitBreakStmt(BreakStmt *) { return activate(); }

AaronBallman wrote:

Should this also handle continue statements?

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


  1   2   3   4   5   >