[clang] [clang][dataflow] Remove RecordValue.getLog() usage in HTMLLogger (PR #65645)

2023-09-11 Thread via cfe-commits

martinboehme wrote:

Can you add a screenshot of what this looks like after the change?

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


[PATCH] D153769: [clangd] Implement the 'Organize Imports' source action. Fix include-cleaner findings in batch.

2023-09-11 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:752
   auto Action = [File = File.str(), Sel, TweakID = TweakID.str(),
- CB = std::move(CB),
+ CB = std::move(CB), ActionKinds,
  this](Expected InpAST) mutable {

we're capturing `ActionKinds` as a reference, but Action is going to execute 
async. you can instead change the input to be `llvm::ArrayRef 
ActionKinds` and capture it by value with `ActionKinds = ActionKinds.vec()`

nit: even better if you just changed the signature here to look like 
`applyTweak(std::string TweakID, CodeActionInputs Inputs, 
Callback CB)`, as we want to consume all of these by value 
anyways. Then you can just move `TweakID` and `Inputs` into the `Action`.



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:49
+bool OrganizeImports::prepare(const Tweak::Selection &Inputs) {
+  if (std::find(Inputs.RequestedActionKinds.begin(),
+Inputs.RequestedActionKinds.end(),

can we also bail out for ObjC



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:56
+return false;
+  Range PreambleRange;
+  PreambleRange.start =

relying on `MainFileIncludes` for preamble range is not correct in general. we 
can have includes way down inside the main file that'll be part of this vector, 
but not preamble (also it's not sorted explicitly).

we should instead use `ComputePreambleBounds` (nit: we can also store it in 
ParsedAST, instead of relexing the file one more time with each CodeAction 
request)



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:56
+return false;
+  Range PreambleRange;
+  PreambleRange.start =

kadircet wrote:
> relying on `MainFileIncludes` for preamble range is not correct in general. 
> we can have includes way down inside the main file that'll be part of this 
> vector, but not preamble (also it's not sorted explicitly).
> 
> we should instead use `ComputePreambleBounds` (nit: we can also store it in 
> ParsedAST, instead of relexing the file one more time with each CodeAction 
> request)
Having a comment for reason would also be helpful, something like `To 
accommodate clients without knowledge of source actions, we trigger without 
checking code action kinds when inside the preamble region`.



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:63
+offsetToPosition(Inputs.Code, Inputs.SelectionEnd)};
+  return SelectionRange.start <= PreambleRange.end &&
+ PreambleRange.start <= SelectionRange.end;

we should also make sure that `RequestedActionKinds` is empty in this case. 
Because we don't want to offer a code action of kind Source, if user is 
explicitly asking for some other kind(s).



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:72
+  for (const auto *Inc : Findings.UnusedIncludes)
+if (auto Err = Replacements.add(
+tooling::Replacement{MainFilePath, UINT_MAX, 1, Inc->Written}))

nit: insertions of Replacements with offset `UINT_MAX` can't fail. so you just 
wrap this inside `llvm::cantFail` instead.



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:87
+ SM.getFileEntryForID(SM.getMainFileID())});
+if (auto Err = Replacements.add(tooling::Replacement{
+MainFilePath, UINT_MAX, 0, "#include " + Spelling}))

same here for never failing



Comment at: clang-tools-extra/clangd/refactor/tweaks/OrganizeImports.cpp:92
+
+  if (Replacements.empty())
+return Tweak::Effect{"No edits to apply.", {}};

i think we should perform this check on `Final` instead (as replacements can 
still go empty after cleanups, and empty set of replacements will result in an 
empty set anyways)



Comment at: 
clang-tools-extra/clangd/unittests/tweaks/OrganizeImportsTests.cpp:19
+
+TEST_F(OrganizeImportsTest, All) {
+  Header = "void foo();";

can you also add some availability tests ?



Comment at: clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp:73
+Tweak::Selection S(Index, AST, Range.Begin, Range.End, std::move(ST),
+   FS, {std::string{CodeAction::SOURCE_KIND}});
+if (auto T = prepareTweak(TweakID, S, nullptr)) {

ATM this is passing SOURCE_KIND for all tweaks, which is conceptually wrong. 
can you instead take this in as a parameter?

for `TweakTest::apply`, we can default it to be an empty vector, and just 
update `OrganizeImportsTests` to pass `{CodeAction::SOURCE_KIND}`;
for `TweakTest::isAvailable`, we can update `EXPECT_AVAILABLE_` to pass in `{}` 
and call `isAvailable` directly in `OrganizeImportsTest

[clang] [clang][bpf] Fix invalid RUN lines in stack protector warning test (PR #65251)

2023-09-11 Thread David Spickett via cfe-commits

DavidSpickett wrote:

@eddyz87 ping!

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


[clang-tools-extra] 26f9e49 - [clangd] Delete deprecated enumerateTweaks endpoint

2023-09-11 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-09-11T09:09:12+02:00
New Revision: 26f9e49d9c92255f7e6e0420eb1d549a023bbcb5

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

LOG: [clangd] Delete deprecated enumerateTweaks endpoint

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index dce6bfc04ce6dd5..13d788162817fb4 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -704,38 +704,6 @@ void ClangdServer::codeAction(const CodeActionInputs 
&Params,
 Transient);
 }
 
-void ClangdServer::enumerateTweaks(
-PathRef File, Range Sel, llvm::unique_function Filter,
-Callback> CB) {
-  auto Action = [Sel, CB = std::move(CB), Filter = std::move(Filter),
- FeatureModules(this->FeatureModules)](
-Expected InpAST) mutable {
-if (!InpAST)
-  return CB(InpAST.takeError());
-auto Selections = tweakSelection(Sel, *InpAST, /*FS=*/nullptr);
-if (!Selections)
-  return CB(Selections.takeError());
-std::vector Res;
-// Don't allow a tweak to fire more than once across ambiguous selections.
-llvm::DenseSet PreparedTweaks;
-auto DeduplicatingFilter = [&](const Tweak &T) {
-  return Filter(T) && !PreparedTweaks.count(T.id());
-};
-for (const auto &Sel : *Selections) {
-  for (auto &T : prepareTweaks(*Sel, DeduplicatingFilter, FeatureModules)) 
{
-Res.push_back({T->id(), T->title(), T->kind()});
-PreparedTweaks.insert(T->id());
-TweakAvailable.record(1, T->id());
-  }
-}
-
-CB(std::move(Res));
-  };
-
-  WorkScheduler->runWithAST("EnumerateTweaks", File, std::move(Action),
-Transient);
-}
-
 void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
   Callback CB) {
   // Tracks number of times a tweak has been attempted.

diff  --git a/clang-tools-extra/clangd/ClangdServer.h 
b/clang-tools-extra/clangd/ClangdServer.h
index 2bc8f02ff38a4bd..a416602251428b0 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -386,13 +386,6 @@ class ClangdServer {
   void codeAction(const CodeActionInputs &Inputs,
   Callback CB);
 
-  /// Enumerate the code tweaks available to the user at a specified point.
-  /// Tweaks where Filter returns false will not be checked or included.
-  /// Deprecated, use codeAction instead.
-  void enumerateTweaks(PathRef File, Range Sel,
-   llvm::unique_function Filter,
-   Callback> CB);
-
   /// Apply the code tweak with a specified \p ID.
   void applyTweak(PathRef File, Range Sel, StringRef ID,
   Callback CB);



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


[clang] b908123 - [clang-format][NFC] Minor cleanup of token annotator and test cases

2023-09-11 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-09-11T00:18:57-07:00
New Revision: b908123c3c1934c03b5183318a47d321fb796260

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

LOG: [clang-format][NFC] Minor cleanup of token annotator and test cases

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 2bb6565193cec83..e925bee44cd0c6a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -137,7 +137,7 @@ class AnnotatingParser {
   bool parseAngle() {
 if (!CurrentToken || !CurrentToken->Previous)
   return false;
-if (NonTemplateLess.count(CurrentToken->Previous))
+if (NonTemplateLess.count(CurrentToken->Previous) > 0)
   return false;
 
 const FormatToken &Previous = *CurrentToken->Previous; // The '<'.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 96c2dbf11eecdd4..4f72166bdce2d73 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10656,8 +10656,8 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
   verifyFormat("f(aa\n"
"  .template operator()());",
getLLVMStyleWithColumns(35));
-  verifyFormat("bool_constant");
-  verifyFormat("bool_constant");
+  verifyFormat("bool_constant;");
+  verifyFormat("bool_constant;");
 
   verifyFormat("if (std::tuple_size_v > 0)");
 



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


[PATCH] D64087: [clang] Correct source locations for instantiations of out-of-line defaulted special member functions. (PR25683)

2023-09-11 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.
This revision is now accepted and ready to land.

LGTM (assuming rebase goes well)
@tahonermann ping folks in the future, and apologies for taking... 4 years!


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64087/new/

https://reviews.llvm.org/D64087

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


[clang] 00add6e - [Driver] Remove duplicate -e on DragonFly (#65867)

2023-09-11 Thread via cfe-commits

Author: Brad Smith
Date: 2023-09-11T03:21:44-04:00
New Revision: 00add6ed24a0f625f28c1cc27bb8579001d5fa7a

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

LOG: [Driver] Remove duplicate -e on DragonFly (#65867)

62281227bf7ca48d0101e4c9d11f71600208c7df was commited, but I noticed one
spot was missed in the DragonFly Driver.

Added: 


Modified: 
clang/lib/Driver/ToolChains/DragonFly.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 900be9e305c902..46f98f9efca233 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -117,7 +117,7 @@ void dragonfly::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   }
 
   Args.AddAllArgs(CmdArgs,
-  {options::OPT_L, options::OPT_T_Group, options::OPT_e});
+  {options::OPT_L, options::OPT_T_Group});
 
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
 



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


[clang] [Driver] Remove duplicate -e on DragonFly (PR #65867)

2023-09-11 Thread Brad Smith via cfe-commits

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

https://github.com/martinboehme updated 
https://github.com/llvm/llvm-project/pull/65319:

>From 28ac8d2b627915e84ec4e7a14e435316aa895587 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Mon, 11 Sep 2023 07:21:56 +
Subject: [PATCH] [clang][dataflow] Merge `RecordValue`s with different
 locations correctly.

Now that prvalue expressions map directly to values (see
https://reviews.llvm.org/D158977), it's no longer guaranteed that `RecordValue`s
associated with the same expression will always have the same storage location.

In other words, D158977 invalidated the assertion in `mergeDistinctValues()`.
The newly added test causes this assertion to fail without the other changes in
the patch.

This patch fixes the issue. However, the real fix will be to eliminate the
`StorageLocation` from `RecordValue` entirely.
---
 .../FlowSensitive/DataflowEnvironment.cpp | 25 +++
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 69 +++
 2 files changed, 82 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f5eb469e7bb3d4e..e13f880896fc071 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -125,18 +125,19 @@ static Value *mergeDistinctValues(QualType Type, Value 
&Val1,
 
   Value *MergedVal = nullptr;
   if (auto *RecordVal1 = dyn_cast(&Val1)) {
-[[maybe_unused]] auto *RecordVal2 = cast(&Val2);
-
-// Values to be merged are always associated with the same location in
-// `LocToVal`. The location stored in `RecordVal` should therefore also
-// be the same.
-assert(&RecordVal1->getLoc() == &RecordVal2->getLoc());
-
-// `RecordVal1` and `RecordVal2` may have different properties associated
-// with them. Create a new `RecordValue` without any properties so that we
-// soundly approximate both values. If a particular analysis needs to merge
-// properties, it should do so in `DataflowAnalysis::merge()`.
-MergedVal = &MergedEnv.create(RecordVal1->getLoc());
+auto *RecordVal2 = cast(&Val2);
+
+if (&RecordVal1->getLoc() == &RecordVal2->getLoc())
+  // `RecordVal1` and `RecordVal2` may have different properties associated
+  // with them. Create a new `RecordValue` with the same location but
+  // without any properties so that we soundly approximate both values. If 
a
+  // particular analysis needs to merge properties, it should do so in
+  // `DataflowAnalysis::merge()`.
+  MergedVal = &MergedEnv.create(RecordVal1->getLoc());
+else
+  // If the locations for the two records are different, need to create a
+  // completely new value.
+  MergedVal = MergedEnv.createValue(Type);
   } else {
 MergedVal = MergedEnv.createValue(Type);
   }
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index a318d9ab7391aa1..6e37011a052c5e4 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -96,6 +96,75 @@ TEST_F(EnvironmentTest, CreateValueRecursiveType) {
   EXPECT_THAT(PV, NotNull());
 }
 
+TEST_F(EnvironmentTest, JoinRecords) {
+  using namespace ast_matchers;
+
+  std::string Code = R"cc(
+struct S {};
+// Need to use the type somewhere so that the `QualType` gets created;
+S s;
+  )cc";
+
+  auto Unit =
+  tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results =
+  match(qualType(hasDeclaration(recordDecl(hasName("S".bind("SType"),
+Context);
+  const QualType *TyPtr = selectFirst("SType", Results);
+  ASSERT_THAT(TyPtr, NotNull());
+  QualType Ty = *TyPtr;
+  ASSERT_FALSE(Ty.isNull());
+
+  auto *ConstructExpr = CXXConstructExpr::CreateEmpty(Context, 0);
+  ConstructExpr->setType(Ty);
+  ConstructExpr->setValueKind(VK_PRValue);
+
+  // Two different `RecordValue`s with the same location are joined into a
+  // third `RecordValue` with that same location.
+  {
+Environment Env1(DAContext);
+auto &Val1 = *cast(Env1.createValue(Ty));
+RecordStorageLocation &Loc = Val1.getLoc();
+Env1.setValue(*ConstructExpr, Val1);
+
+Environment Env2(DAContext);
+auto &Val2 = Env2.create(Loc);
+Env2.setValue(Loc, Val2);
+Env2.setValue(*ConstructExpr, Val2);
+
+Environment::ValueModel Model;
+Environment EnvJoined = Environment::join(Env1, Env2, Model);
+auto *JoinedVal = cast(EnvJoined.getValue(*ConstructExpr));
+EXPECT_NE(JoinedVal, &Val1);
+EXPECT_NE(JoinedVal, &Val2);
+EXPECT_EQ(&JoinedVal->getLoc(), &Loc);
+  }
+
+  // Two different `RecordValue`s with different locations are joined into a
+  /

[clang] 90db419 - [clang][AArch64] Add --print-supported-extensions support (#65466)

2023-09-11 Thread via cfe-commits

Author: David Spickett
Date: 2023-09-11T08:25:02+01:00
New Revision: 90db4193f82937bff68c8f8a1481320f245f04ff

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

LOG: [clang][AArch64] Add --print-supported-extensions support (#65466)

This follows the RISC-V work done in
4b40ced4e5ba10b841516b3970e7699ba8ded572.

This uses AArch64's target parser instead. We just list the names,
without the "+" on them, which matches RISC-V's format.

```
$ ./bin/clang -target aarch64-linux-gnu --print-supported-extensions
clang version 18.0.0 (https://github.com/llvm/llvm-project.git 
154da8aec20719c82235a6957aa6e461f5a5e030)
Target: aarch64-unknown-linux-gnu
Thread model: posix
InstalledDir: <...>
All available -march extensions for AArch64

aes
b16b16
bf16
brbe
crc
crypto
cssc
<...>
```

Since our extensions don't have versions in the same way there's just
one column with the name in.

Any extension without a feature name (including the special "none") is
not listed as those cannot be passed to -march, they're just for the
backend. For example the MTE extension can be added with "+memtag" but
MTE2 and MTE3 do not have feature names so they cannot be added to
-march.

This does not attempt to tackle the fact that clang allows invalid
combinations of AArch64 extensions, it simply lists the possible
options. It's still up to the user to ask for something sensible.

Equally, this has no context of what CPU is being selected. Neither does
the RISC-V option, the user has to be aware of that.

I've added a target parser test, and a high level clang test that checks
RISC-V and AArch64 work and that Intel, that doesn't support this, shows
the correct error.

Added: 
clang/test/Driver/print-supported-extensions.c

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/tools/driver/cc1_main.cpp
llvm/include/llvm/TargetParser/AArch64TargetParser.h
llvm/lib/TargetParser/AArch64TargetParser.cpp
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 635c40f1a9278ed..a5f5ca29053b43b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5271,7 +5271,7 @@ def print_supported_cpus : Flag<["-", "--"], 
"print-supported-cpus">,
   MarshallingInfoFlag>;
 def print_supported_extensions : Flag<["-", "--"], 
"print-supported-extensions">,
   Visibility<[ClangOption, CC1Option, CLOption]>,
-  HelpText<"Print supported extensions for RISC-V">,
+  HelpText<"Print supported -march extensions (RISC-V and AArch64 only)">,
   MarshallingInfoFlag>;
 def : Flag<["-"], "mcpu=help">, Alias;
 def : Flag<["-"], "mtune=help">, Alias;

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 9d05549f671e29d..ba723eac2a7ee74 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4284,7 +4284,8 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
 // and quits.
 if (Arg *A = Args.getLastArg(Opt)) {
   if (Opt == options::OPT_print_supported_extensions &&
-  !C.getDefaultToolChain().getTriple().isRISCV()) {
+  !C.getDefaultToolChain().getTriple().isRISCV() &&
+  !C.getDefaultToolChain().getTriple().isAArch64()) {
 C.getDriver().Diag(diag::err_opt_not_valid_on_target)
 << "--print-supported-extensions";
 return;

diff  --git a/clang/test/Driver/print-supported-extensions.c 
b/clang/test/Driver/print-supported-extensions.c
new file mode 100644
index 000..2cbd2d95816c22d
--- /dev/null
+++ b/clang/test/Driver/print-supported-extensions.c
@@ -0,0 +1,14 @@
+// Test that --print-supported-extensions lists supported -march extensions
+// on supported architectures, and errors on unsupported architectures.
+
+// RUN: %if aarch64-registered-target %{ %clang --target=aarch64-linux-gnu \
+// RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
AARCH64 %}
+// AARCH64: All available -march extensions for AArch64
+
+// RUN: %if aarch64-registered-target %{ %clang --target=riscv64-linux-gnu \
+// RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
RISCV %}
+// RISCV: All available -march extensions for RISC-V
+
+// RUN: %if x86-registered-target %{ not %clang --target=x86_64-linux-gnu \
+// RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix X86 
%}
+// X86: error: option '--print-supported-extensions' cannot be specified on 
this target
\ No newline at end of file

diff  --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index ab886d0adc7e5cf..ed68a11d0191fc9 100644
--- a/clang

[clang] [clang][AArch64] Add --print-supported-extensions support (PR #65466)

2023-09-11 Thread David Spickett via cfe-commits

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits


@@ -121,18 +121,18 @@ static Value *mergeDistinctValues(QualType Type, Value 
&Val1,
 
   Value *MergedVal = nullptr;
   if (auto *RecordVal1 = dyn_cast(&Val1)) {
-[[maybe_unused]] auto *RecordVal2 = cast(&Val2);
-
-// Values to be merged are always associated with the same location in
-// `LocToVal`. The location stored in `RecordVal` should therefore also
-// be the same.
-assert(&RecordVal1->getLoc() == &RecordVal2->getLoc());
-
-// `RecordVal1` and `RecordVal2` may have different properties associated
-// with them. Create a new `RecordValue` without any properties so that we
-// soundly approximate both values. If a particular analysis needs to merge
-// properties, it should do so in `DataflowAnalysis::merge()`.
-MergedVal = &MergedEnv.create(RecordVal1->getLoc());
+auto *RecordVal2 = cast(&Val2);
+
+if (&RecordVal1->getLoc() == &RecordVal2->getLoc())
+  // `RecordVal1` and `RecordVal2` may have different properties associated
+  // with them. Create a new `RecordValue` without any properties so that 
we
+  // soundly approximate both values. If a particular analysis needs to
+  // merge properties, it should do so in `DataflowAnalysis::merge()`.

martinboehme wrote:

I like the suggestion -- done!

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


[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

llvmbot wrote:

@llvm/pr-subscribers-clang


Changes

Now that prvalue expressions map directly to values (see
https://reviews.llvm.org/D158977), it's no longer guaranteed that `RecordValue`s
associated with the same expression will always have the same storage location.

In other words, D158977 invalidated the assertion in `mergeDistinctValues()`.
The newly added test causes this assertion to fail without the other changes in
the patch.

This patch fixes the issue. However, the real fix will be to eliminate the
`StorageLocation` from `RecordValue` entirely.

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

2 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+13-12) 
- (modified) clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
(+69) 



diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f5eb469e7bb3d4e..e13f880896fc071 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -125,18 +125,19 @@ static Value *mergeDistinctValues(QualType Type, Value 
&Val1,
 
   Value *MergedVal = nullptr;
   if (auto *RecordVal1 = dyn_cast(&Val1)) {
-[[maybe_unused]] auto *RecordVal2 = cast(&Val2);
-
-// Values to be merged are always associated with the same location in
-// `LocToVal`. The location stored in `RecordVal` should therefore also
-// be the same.
-assert(&RecordVal1->getLoc() == &RecordVal2->getLoc());
-
-// `RecordVal1` and `RecordVal2` may have different properties associated
-// with them. Create a new `RecordValue` without any properties so that we
-// soundly approximate both values. If a particular analysis needs to merge
-// properties, it should do so in `DataflowAnalysis::merge()`.
-MergedVal = &MergedEnv.create(RecordVal1->getLoc());
+auto *RecordVal2 = cast(&Val2);
+
+if (&RecordVal1->getLoc() == &RecordVal2->getLoc())
+  // `RecordVal1` and `RecordVal2` may have different properties associated
+  // with them. Create a new `RecordValue` with the same location but
+  // without any properties so that we soundly approximate both values. If 
a
+  // particular analysis needs to merge properties, it should do so in
+  // `DataflowAnalysis::merge()`.
+  MergedVal = &MergedEnv.create(RecordVal1->getLoc());
+else
+  // If the locations for the two records are different, need to create a
+  // completely new value.
+  MergedVal = MergedEnv.createValue(Type);
   } else {
 MergedVal = MergedEnv.createValue(Type);
   }
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index a318d9ab7391aa1..6e37011a052c5e4 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -96,6 +96,75 @@ TEST_F(EnvironmentTest, CreateValueRecursiveType) {
   EXPECT_THAT(PV, NotNull());
 }
 
+TEST_F(EnvironmentTest, JoinRecords) {
+  using namespace ast_matchers;
+
+  std::string Code = R"cc(
+struct S {};
+// Need to use the type somewhere so that the `QualType` gets created;
+S s;
+  )cc";
+
+  auto Unit =
+  tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results =
+  match(qualType(hasDeclaration(recordDecl(hasName("S".bind("SType"),
+Context);
+  const QualType *TyPtr = selectFirst("SType", Results);
+  ASSERT_THAT(TyPtr, NotNull());
+  QualType Ty = *TyPtr;
+  ASSERT_FALSE(Ty.isNull());
+
+  auto *ConstructExpr = CXXConstructExpr::CreateEmpty(Context, 0);
+  ConstructExpr->setType(Ty);
+  ConstructExpr->setValueKind(VK_PRValue);
+
+  // Two different `RecordValue`s with the same location are joined into a
+  // third `RecordValue` with that same location.
+  {
+Environment Env1(DAContext);
+auto &Val1 = *cast(Env1.createValue(Ty));
+RecordStorageLocation &Loc = Val1.getLoc();
+Env1.setValue(*ConstructExpr, Val1);
+
+Environment Env2(DAContext);
+auto &Val2 = Env2.create(Loc);
+Env2.setValue(Loc, Val2);
+Env2.setValue(*ConstructExpr, Val2);
+
+Environment::ValueModel Model;
+Environment EnvJoined = Environment::join(Env1, Env2, Model);
+auto *JoinedVal = cast(EnvJoined.getValue(*ConstructExpr));
+EXPECT_NE(JoinedVal, &Val1);
+EXPECT_NE(JoinedVal, &Val2);
+EXPECT_EQ(&JoinedVal->getLoc(), &Loc);
+  }
+
+  // Two different `RecordValue`s with different locations are joined into a
+  // third `RecordValue` with a location different from the other two.
+  {
+Environment Env1(DAContext);
+auto &Val1 = *cast(Env1.createValue(Ty));
+Env1.setValue(*ConstructExpr, Val1

[clang] [clang][dataflow] Merge `RecordValue`s with different locations correctly. (PR #65319)

2023-09-11 Thread via cfe-commits

martinboehme wrote:

(Sorry, rebased to head inadvertently -- still getting used to the new process. 
Will use fixup commits in the future.)

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


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-11 Thread via cfe-commits

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


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-11 Thread via cfe-commits

cor3ntin wrote:

@Fznamznon 

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


[clang] 2d670fa - [clang][AArch64] Fix supported extensions test case

2023-09-11 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2023-09-11T07:50:52Z
New Revision: 2d670fab4c099a3c8e7c257a100f5a34df598ac4

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

LOG: [clang][AArch64] Fix supported extensions test case

Added in 90db4193f82937bff68c8f8a1481320f245f04ff.
Typo in the if, should have been "riscv-...".

Added: 


Modified: 
clang/test/Driver/print-supported-extensions.c

Removed: 




diff  --git a/clang/test/Driver/print-supported-extensions.c 
b/clang/test/Driver/print-supported-extensions.c
index 2cbd2d95816c22d..dcb4328726ab577 100644
--- a/clang/test/Driver/print-supported-extensions.c
+++ b/clang/test/Driver/print-supported-extensions.c
@@ -5,7 +5,7 @@
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
AARCH64 %}
 // AARCH64: All available -march extensions for AArch64
 
-// RUN: %if aarch64-registered-target %{ %clang --target=riscv64-linux-gnu \
+// RUN: %if riscv-registered-target %{ %clang --target=riscv64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
RISCV %}
 // RISCV: All available -march extensions for RISC-V
 



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


[clang] [clang][dataflow][NFC] Delete unused function. (PR #65602)

2023-09-11 Thread via cfe-commits

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


[clang] 2757085 - [clang][dataflow][NFC] Delete unused function. (#65602)

2023-09-11 Thread via cfe-commits

Author: martinboehme
Date: 2023-09-11T09:54:50+02:00
New Revision: 2757085e90823431cbaf96e5cc93cf7a73b8bdbd

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

LOG: [clang][dataflow][NFC] Delete unused function. (#65602)

I'm not sure why we had this originally, but the function seems to have
a pretty
onerous contract anyway for a function that is externally available, so
it seems
better not to keep it around.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index 88a33d19f7d8f61..67c323dbf45e1b2 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
@@ -132,25 +132,6 @@ struct TypeErasedDataflowAnalysisState {
   }
 };
 
-/// Transfers the state of a basic block by evaluating each of its elements in
-/// the context of `Analysis` and the states of its predecessors that are
-/// available in `BlockStates`. `PostVisitCFG` (if provided) will be applied to
-/// each element in the block, after it is evaluated.
-///
-/// Requirements:
-///
-///   All predecessors of `Block` except those with loop back edges must have
-///   already been transferred. States in `BlockStates` that are set to
-///   `std::nullopt` represent basic blocks that are not evaluated yet.
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG = nullptr);
-
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. Indices of
 /// the returned vector correspond to basic block IDs. Returns an error if the

diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 626b57b43755ec7..900aa97e9f6de64 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -495,18 +495,6 @@ transferCFGBlock(const CFGBlock &Block, AnalysisContext 
&AC,
   return State;
 }
 
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG) {
-  AnalysisContext AC(CFCtx, Analysis, InitEnv, BlockStates);
-  return transferCFGBlock(Block, AC, PostVisitCFG);
-}
-
 llvm::Expected>>
 runTypeErasedDataflowAnalysis(
 const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis,



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


[clang-tools-extra] 64366d4 - [clangd] Rollforward include-cleaner library usage in symbol collector.

2023-09-11 Thread Viktoriia Bakalova via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-09-11T07:57:35Z
New Revision: 64366d4935d3c56ce5906a321edb2e91d4f886bc

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

LOG: [clangd] Rollforward include-cleaner library usage in symbol collector.

Differential Revision: https://reviews.llvm.org/D156659

Added: 


Modified: 
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/index/SymbolCollector.h
clang-tools-extra/clangd/unittests/FileIndexTests.cpp
clang-tools-extra/clangd/unittests/IndexActionTests.cpp
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index e843413601f5a29..699370fe1adf3af 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -821,25 +821,45 @@ void SymbolCollector::setIncludeLocation(const Symbol &S, 
SourceLocation DefLoc,
   // Use the expansion location to get the #include header since this is
   // where the symbol is exposed.
   IncludeFiles[S.ID] = SM.getDecomposedExpansionLoc(DefLoc).first;
+
+  // We update providers for a symbol with each occurence, as SymbolCollector
+  // might run while parsing, rather than at the end of a translation unit.
+  // Hence we see more and more redecls over time.
+  auto [It, Inserted] = SymbolProviders.try_emplace(S.ID);
+  auto Headers =
+  include_cleaner::headersForSymbol(Sym, SM, Opts.PragmaIncludes);
+  if (Headers.empty())
+return;
+
+  auto *HeadersIter = Headers.begin();
+  include_cleaner::Header H = *HeadersIter;
+  while (HeadersIter != Headers.end() &&
+ H.kind() == include_cleaner::Header::Physical &&
+ !tooling::isSelfContainedHeader(H.physical(), SM,
+ PP->getHeaderSearchInfo())) {
+H = *HeadersIter;
+HeadersIter++;
+  }
+  It->second = H;
 }
 
 llvm::StringRef getStdHeader(const Symbol *S, const LangOptions &LangOpts) {
   tooling::stdlib::Lang Lang = tooling::stdlib::Lang::CXX;
-if (LangOpts.C11)
-  Lang = tooling::stdlib::Lang::C;
-else if(!LangOpts.CPlusPlus)
-  return "";
-
-if (S->Scope == "std::" && S->Name == "move") {
-  if (!S->Signature.contains(','))
-return "";
-  return "";
-}
-   
-if (auto StdSym = tooling::stdlib::Symbol::named(S->Scope, S->Name, Lang))
- if (auto Header = StdSym->header())
-   return Header->name();
+  if (LangOpts.C11)
+Lang = tooling::stdlib::Lang::C;
+  else if(!LangOpts.CPlusPlus)
 return "";
+
+  if (S->Scope == "std::" && S->Name == "move") {
+if (!S->Signature.contains(','))
+  return "";
+return "";
+  }
+
+  if (auto StdSym = tooling::stdlib::Symbol::named(S->Scope, S->Name, Lang))
+if (auto Header = StdSym->header())
+  return Header->name();
+  return "";
 }
 
 void SymbolCollector::finish() {
@@ -865,13 +885,16 @@ void SymbolCollector::finish() {
 }
   }
   llvm::DenseMap FileToContainsImportsOrObjC;
+  llvm::DenseMap HeaderSpelling;
   // Fill in IncludeHeaders.
   // We delay this until end of TU so header guards are all resolved.
-  for (const auto &[SID, FID] : IncludeFiles) {
+  for (const auto &[SID, OptionalProvider] : SymbolProviders) {
 const Symbol *S = Symbols.find(SID);
 if (!S)
   continue;
+assert(IncludeFiles.find(SID) != IncludeFiles.end());
 
+const auto FID = IncludeFiles.at(SID);
 // Determine if the FID is #include'd or #import'ed.
 Symbol::IncludeDirective Directives = Symbol::Invalid;
 auto CollectDirectives = shouldCollectIncludePath(S->SymInfo.Kind);
@@ -891,20 +914,61 @@ void SymbolCollector::finish() {
 if (Directives == Symbol::Invalid)
   continue;
 
-// FIXME: Use the include-cleaner library instead.
-llvm::StringRef IncludeHeader = getStdHeader(S, ASTCtx->getLangOpts());
-if (IncludeHeader.empty())
-  IncludeHeader = HeaderFileURIs->getIncludeHeader(FID);
+// Use the include location-based logic for Objective-C symbols.
+if (Directives & Symbol::Import) {
+  llvm::StringRef IncludeHeader = getStdHeader(S, ASTCtx->getLangOpts());
+  if (IncludeHeader.empty())
+IncludeHeader = HeaderFileURIs->getIncludeHeader(FID);
+
+  if (!IncludeHeader.empty()) {
+auto NewSym = *S;
+NewSym.IncludeHeaders.push_back({IncludeHeader, 1, Directives});
+Symbols.insert(NewSym);
+  }
+  // FIXME: use providers from include-cleaner library once it's polished
+  // for Objective-C.
+  continue;
+}
+
+assert(Directives == Symbol::Include);
+// For #include's, use the providers computed by the include-cleaner
+// library.
+

[PATCH] D156659: [clangd] Rollforward include-cleaner library usage in symbol collector.

2023-09-11 Thread Viktoriia Bakalova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG64366d4935d3: [clangd] Rollforward include-cleaner library 
usage in symbol collector. (authored by VitaNuo).

Changed prior to commit:
  https://reviews.llvm.org/D156659?vs=556135&id=556396#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156659/new/

https://reviews.llvm.org/D156659

Files:
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/IndexActionTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp

Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -14,6 +14,7 @@
 #include "index/SymbolCollector.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
@@ -1554,6 +1555,8 @@
 // Move overloads have special handling.
 template  T&& move(_T&& __value);
 template  _O move(_I, _I, _O);
+template  _O move(
+  _T&&, _O, _O, _I);
   }
   )cpp",
   /*Main=*/"");
@@ -1565,7 +1568,8 @@
 includeHeader("")),
   // Parameter names are demangled.
   AllOf(labeled("move(T &&value)"), includeHeader("")),
-  AllOf(labeled("move(I, I, O)"), includeHeader("";
+  AllOf(labeled("move(I, I, O)"), includeHeader("")),
+  AllOf(labeled("move(T &&, O, O, I)"), includeHeader("";
 }
 
 TEST_F(SymbolCollectorTest, IWYUPragma) {
@@ -1592,7 +1596,7 @@
  includeHeader("\"the/good/header.h\"";
 }
 
-TEST_F(SymbolCollectorTest, DISABLED_IWYUPragmaExport) {
+TEST_F(SymbolCollectorTest, IWYUPragmaExport) {
   CollectorOpts.CollectIncludePath = true;
   const std::string Header = R"cpp(#pragma once
 #include "exporter.h"
@@ -1978,6 +1982,24 @@
   qName("A"), hasKind(clang::index::SymbolKind::Concept;
 }
 
+TEST_F(SymbolCollectorTest, IncludeHeaderForwardDecls) {
+  CollectorOpts.CollectIncludePath = true;
+  const std::string Header = R"cpp(#pragma once 
+struct Foo;
+#include "full.h"
+)cpp";
+  auto FullFile = testPath("full.h");
+  InMemoryFileSystem->addFile(FullFile, 0,
+  llvm::MemoryBuffer::getMemBuffer(R"cpp(
+#pragma once 
+struct Foo {};)cpp"));
+  runSymbolCollector(Header, /*Main=*/"",
+ /*ExtraArgs=*/{"-I", testRoot()});
+  EXPECT_THAT(Symbols, UnorderedElementsAre(AllOf(
+   qName("Foo"),
+   includeHeader(URI::create(FullFile).toString()
+  << *Symbols.begin();
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/IndexActionTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexActionTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexActionTests.cpp
@@ -8,11 +8,15 @@
 
 #include "Headers.h"
 #include "TestFS.h"
+#include "URI.h"
 #include "index/IndexAction.h"
 #include "index/Serialization.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Tooling.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -40,6 +44,11 @@
   return toUri(Path) == URI;
 }
 
+MATCHER_P(includeHeader, P, "") {
+  return (arg.IncludeHeaders.size() == 1) &&
+ (arg.IncludeHeaders.begin()->IncludeHeader == P);
+}
+
 ::testing::Matcher
 includesAre(const std::vector &Includes) {
   return ::testing::Field(&IncludeGraphNode::DirectIncludes,
@@ -312,6 +321,26 @@
   EXPECT_THAT(*IndexFile.Symbols, testing::Contains(hasName("Bar")));
   EXPECT_THAT(*IndexFile.Symbols, Not(testing::Contains(hasName("Baz";
 }
+
+TEST_F(IndexActionTest, SymbolFromCC) {
+  std::string MainFilePath = testPath("main.cpp");
+  addFile(MainFilePath, R"cpp(
+ #include "main.h"
+ void foo() {}
+ )cpp");
+  addFile(testPath("main.h"), R"cpp(
+ #pragma once
+ void foo();
+ )cpp");
+  Opts.FileFilter = [](const SourceManager &SM, FileID F) {
+return !SM.getFileEntryRefForID(F)->getName().endswith("main.h");
+  };
+  IndexFileIn IndexFile = runIndexingAction(MainFilePath, {"-std=c++14"});
+  EXPECT_THAT(*IndexFile.Symbols,
+  UnorderedElementsAre(AllOf(
+  hasName("foo"),
+  includeHeader(URI::create(testPath("main.h")).toString();
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-to

[clang] Extension: allow recursive macros (PR #65851)

2023-09-11 Thread via cfe-commits

https://github.com/kelbon updated 
https://github.com/llvm/llvm-project/pull/65851:

>From 2f807b312baef8c6038c2452b84232acb6d6d2c2 Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Sat, 9 Sep 2023 17:51:15 +0400
Subject: [PATCH 1/3] add define2 pp directive

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Lex/MacroInfo.h  | 19 +--
 clang/include/clang/Lex/Preprocessor.h   |  2 +-
 clang/lib/Basic/IdentifierTable.cpp  |  2 ++
 clang/lib/Format/WhitespaceManager.cpp   |  2 +-
 clang/lib/Lex/MacroInfo.cpp  |  3 ++-
 clang/lib/Lex/PPDirectives.cpp   | 16 +++-
 7 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 45ebc200b168986..f059d809823ab42 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -115,6 +115,7 @@ PPKEYWORD(__include_macros)
 
 // C99 6.10.3 - Macro Replacement.
 PPKEYWORD(define)
+PPKEYWORD(define2)
 PPKEYWORD(undef)
 
 // C99 6.10.4 - Line Control.
diff --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 00c1c3866bbd9ca..4f0c8e987610e50 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -102,6 +102,10 @@ class MacroInfo {
   /// like \#define A A.
   bool IsDisabled : 1;
 
+  // True if 'define2' used,
+  // ignores 'IsDisabled' and enables expansion anyway
+  bool AllowRecurse : 1;
+
   /// True if this macro is either defined in the main file and has
   /// been used, or if it is not defined in the main file.
   ///
@@ -278,18 +282,13 @@ class MacroInfo {
   /// Return true if this macro is enabled.
   ///
   /// In other words, that we are not currently in an expansion of this macro.
-  bool isEnabled() const { return !IsDisabled; }
-
-  void EnableMacro() {
-assert(IsDisabled && "Cannot enable an already-enabled macro!");
-IsDisabled = false;
-  }
+  bool isEnabled() const { return AllowRecurse || !IsDisabled; }
+  void setAllowRecursive(bool Allow) { AllowRecurse = Allow; }
+  bool isAllowRecurse() const { return AllowRecurse; }
 
-  void DisableMacro() {
-assert(!IsDisabled && "Cannot disable an already-disabled macro!");
-IsDisabled = true;
-  }
+  void EnableMacro() { IsDisabled = false; }
 
+  void DisableMacro() { IsDisabled = true; }
   /// Determine whether this macro was used for a header guard.
   bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
 
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 9efe439bc5f2192..de121ce82fd1d7b 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2754,7 +2754,7 @@ class Preprocessor {
   void replayPreambleConditionalStack();
 
   // Macro handling.
-  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
+  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard, 
bool AllowRecurse);
   void HandleUndefDirective();
 
   // Conditional Inclusion.
diff --git a/clang/lib/Basic/IdentifierTable.cpp 
b/clang/lib/Basic/IdentifierTable.cpp
index afb30268f2973ce..4de3565c8c6d9a8 100644
--- a/clang/lib/Basic/IdentifierTable.cpp
+++ b/clang/lib/Basic/IdentifierTable.cpp
@@ -433,6 +433,8 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   unsigned Len = getLength();
   if (Len < 2) return tok::pp_not_keyword;
   const char *Name = getNameStart();
+  if (std::string_view(Name, Len) == "define2")
+return tok::pp_define2;
   switch (HASH(Len, Name[0], Name[2])) {
   default: return tok::pp_not_keyword;
   CASE( 2, 'i', '\0', if);
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index b7bd8d27dc976b1..d8ab76d6761553e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -743,7 +743,7 @@ void WhitespaceManager::alignConsecutiveMacros() {
 if (!Current || Current->isNot(tok::identifier))
   return false;
 
-if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
+if (!Current->Previous || !Current->Previous->isOneOf(tok::pp_define, 
tok::pp_define2))
   return false;
 
 // For a macro function, 0 spaces are required between the
diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index 39bb0f44eff25ba..9c3619c7c909304 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -50,7 +50,7 @@ static_assert(MacroInfoSizeChecker::AsExpected,
 MacroInfo::MacroInfo(SourceLocation DefLoc)
 : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
   IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
-  HasCommaPasting(false), IsDisabled(false), IsUsed(false),
+  HasCommaPasting(false), IsDisabled(false), AllowRecurse(false), 
IsUsed(false),
   IsAllowRedefinitionsW

[clang-tools-extra] 94b1435 - [clangd] allow extracting to variable for lambda expressions

2023-09-11 Thread Nathan Ridge via cfe-commits

Author: Julian Schmidt
Date: 2023-09-11T04:03:38-04:00
New Revision: 94b14355e2ef819fc56916e5d154be4f3aefda1c

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

LOG: [clangd] allow extracting to variable for lambda expressions

Support for extracting lambda expressions, e.g. extracting a lambda from a 
callexpr (e.g. algorithms/ranges) to a named variable.

Reviewed By: nridge

Differential Revision: https://reviews.llvm.org/D141757

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
index cdf2c6b988cf9b4..1e4edc6d6b4bb39 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
@@ -12,8 +12,11 @@
 #include "SourceCode.h"
 #include "refactor/Tweak.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/LambdaCapture.h"
 #include "clang/AST/OperationKinds.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
@@ -74,10 +77,52 @@ computeReferencedDecls(const clang::Expr *Expr) {
   public:
 std::vector ReferencedDecls;
 bool VisitDeclRefExpr(DeclRefExpr *DeclRef) { // NOLINT
+  // Stop the call operator of lambdas from being marked as a referenced
+  // DeclRefExpr in immediately invoked lambdas.
+  if (const auto *const Method =
+  llvm::dyn_cast(DeclRef->getDecl());
+  Method != nullptr && Method->getParent()->isLambda()) {
+return true;
+  }
   ReferencedDecls.push_back(DeclRef->getDecl());
   return true;
 }
+
+// Local variables declared inside of the selected lambda cannot go out of
+// scope. The DeclRefExprs that are important are the variables captured,
+// the DeclRefExprs inside the initializers of init-capture variables,
+// variables mentioned in trailing return types, constraints and explicit
+// defaulted template parameters.
+bool TraverseLambdaExpr(LambdaExpr *LExpr) {
+  for (const auto &[Capture, Initializer] :
+   llvm::zip(LExpr->captures(), LExpr->capture_inits())) {
+TraverseLambdaCapture(LExpr, &Capture, Initializer);
+  }
+
+  if (clang::Expr *const RequiresClause =
+  LExpr->getTrailingRequiresClause()) {
+TraverseStmt(RequiresClause);
+  }
+
+  for (auto *const TemplateParam : LExpr->getExplicitTemplateParameters())
+TraverseDecl(TemplateParam);
+
+  if (auto *const CallOperator = LExpr->getCallOperator()) {
+TraverseType(CallOperator->getDeclaredReturnType());
+
+for (auto *const Param : CallOperator->parameters()) {
+  TraverseParmVarDecl(Param);
+}
+
+for (auto *const Attr : CallOperator->attrs()) {
+  TraverseAttr(Attr);
+}
+  }
+
+  return true;
+}
   };
+
   FindDeclRefsVisitor Visitor;
   Visitor.TraverseStmt(const_cast(cast(Expr)));
   return Visitor.ReferencedDecls;
@@ -152,10 +197,16 @@ const clang::Stmt 
*ExtractionContext::computeInsertionPoint() const {
   auto CanExtractOutside =
   [](const SelectionTree::Node *InsertionPoint) -> bool {
 if (const clang::Stmt *Stmt = InsertionPoint->ASTNode.get()) {
-  // Allow all expressions except LambdaExpr since we don't want to extract
-  // from the captures/default arguments of a lambda
-  if (isa(Stmt))
-return !isa(Stmt);
+  if (isa(Stmt)) {
+// Do not allow extraction from the initializer of a defaulted 
parameter
+// to a local variable (e.g. a function-local lambda).
+if (InsertionPoint->Parent->ASTNode.get() != nullptr) {
+  return false;
+}
+
+return true;
+  }
+
   // We don't yet allow extraction from switch/case stmt as we would need 
to
   // jump over the switch stmt even if there is a CompoundStmt inside the
   // switch. And there are other Stmts which we don't care about (e.g.
@@ -240,7 +291,7 @@ struct ParsedBinaryOperator {
 SelectedOperands.clear();
 
 if (const BinaryOperator *Op =
-llvm::dyn_cast_or_null(N.ASTNode.get())) {
+llvm::dyn_cast_or_null(N.ASTNode.get())) {
   Kind = Op->getOpcode();
   ExprLoc = Op->getExprLoc();
   SelectedOperands = N.Children;
@@ -255,7 +306,7 @@ struct ParsedBinaryOperator {
   Kind = BinaryOperator::getOverloadedOpcode(Op->getOperator());
   ExprLoc = Op->getExprLoc(

[PATCH] D141757: [clangd] allow extracting to variable for lambda expressions

2023-09-11 Thread Nathan Ridge via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG94b14355e2ef: [clangd] allow extracting to variable for 
lambda expressions (authored by 5chmidti, committed by nridge).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D141757/new/

https://reviews.llvm.org/D141757

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
  clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
  clang-tools-extra/docs/ReleaseNotes.rst

Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -66,6 +66,11 @@
 Code completion
 ^^^
 
+Code actions
+
+
+- The extract variable tweak gained support for extracting lambda expressions to a variable.
+
 Signature help
 ^^
 
Index: clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
@@ -98,6 +98,7 @@
   return [[t]].bar([[t]].z);
 }
 void v() { return; }
+
 // function default argument
 void f(int b = [[1]]) {
   // empty selection
@@ -131,10 +132,80 @@
   goto label;
   label:
 a = [[1]];
+
+  // lambdas: captures
+  int x = 0;
+  [ [[=]] ](){};
+  [ [[&]] ](){};
+  [ [[x]] ](){};
+  [ [[&x]] ](){};
+  [y = [[x]] ](){};
+  [ [[y = x]] ](){};
+
+  // lambdas: default args, cannot extract into function-local scope
+  [](int x = [[10]]){};
+  [](auto h = [[ [i = [](){}](){} ]]) {};
+
+  // lambdas: default args
+  // Extracting from capture initializers is usually fine,
+  // but not if the capture itself is nested inside a default argument
+  [](auto h = [i = [[ [](){} ]]](){}) {};
+  [](auto h = [i = [[ 42 ]]](){}) {};
+
+  // lambdas: scope
+  if (int a = 1)
+if ([[ [&](){ return a + 1; } ]]() == 4)
+  a = a + 1;
+
+  for (int c = 0; [[ [&]() { return c < b; } ]](); ++c) {
+  }
+  for (int c = 0; [[ [&]() { return c < b; } () ]]; ++c) {
+  }
+
+  // lambdas: scope with structured binding
+  struct Coordinates {
+int x{};
+int y{};
+  };
+  Coordinates c{};
+  if (const auto [x, y] = c; x > y)
+auto f = [[ [&]() { return x + y; } ]];
+
+  // lambdas: referencing outside variables that block extraction
+  //  in trailing return type or in a decltype used
+  //  by a parameter
+  if (int a = 1)
+if ([[ []() -> decltype(a) { return 1; } ]] () == 4)
+  a = a + 1;
+  if (int a = 1)
+if ([[ [](int x = decltype(a){}) { return 1; } ]] () == 4)
+  a = a + 1;
+  if (int a = 1)
+if ([[ [](decltype(a) x) { return 1; } ]] (42) == 4)
+  a = a + 1;
 }
   )cpp";
   EXPECT_UNAVAILABLE(UnavailableCases);
 
+  ExtraArgs = {"-std=c++20"};
+  const char *UnavailableCasesCXX20 = R"cpp(
+template 
+concept Constraint = requires (T t) { true; };
+void foo() {
+  // lambdas: referencing outside variables that block extraction
+  //  in requires clause or defaulted explicit template parameters
+  if (int a = 1)
+if ([[ [](auto b) requires (Constraint && Constraint) { return true; } ]] (a))
+  a = a + 1;
+
+  if (int a = 1)
+if ([[ [](T b) { return true; } ]] (a))
+  a = a + 1;
+}
+  )cpp";
+  EXPECT_UNAVAILABLE(UnavailableCasesCXX20);
+  ExtraArgs.clear();
+
   // vector of pairs of input and output strings
   std::vector> InputOutputs = {
   // extraction from variable declaration/assignment
@@ -282,6 +353,219 @@
  void f() {
auto placeholder = S(2) + S(3) + S(4); S x = S(1) + placeholder + S(5);
  })cpp"},
+  // lambda expressions
+  {R"cpp(template  void f(T) {}
+void f2() {
+  f([[ [](){ return 42; }]]);
+}
+)cpp",
+   R"cpp(template  void f(T) {}
+void f2() {
+  auto placeholder = [](){ return 42; }; f( placeholder);
+}
+)cpp"},
+  {R"cpp(template  void f(T) {}
+void f2() {
+  f([x = [[40 + 2]] ](){ return 42; });
+}
+)cpp",
+   R"cpp(template  void f(T) {}
+void f2() {
+  auto placeholder = 40 + 2; f([x = placeholder ](){ return 42; });
+}
+)cpp"},
+  {R"cpp(auto foo(int

[clang-tools-extra] [clangd] Forward --target to system include extraction (PR #65824)

2023-09-11 Thread Nathan Ridge via cfe-commits

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


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


[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

2023-09-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 556399.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152504/new/

https://reviews.llvm.org/D152504

Files:
  clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
  clang/lib/Analysis/ThreadSafety.cpp
  clang/lib/Analysis/ThreadSafetyCommon.cpp
  clang/test/Sema/warn-thread-safety-analysis.c

Index: clang/test/Sema/warn-thread-safety-analysis.c
===
--- clang/test/Sema/warn-thread-safety-analysis.c
+++ clang/test/Sema/warn-thread-safety-analysis.c
@@ -22,6 +22,8 @@
 #define SHARED_LOCKS_REQUIRED(...) \
   __attribute__ ((shared_locks_required(__VA_ARGS__)))
 #define NO_THREAD_SAFETY_ANALYSIS  __attribute__ ((no_thread_safety_analysis))
+#define CLEANUP(A) __attribute__ ((cleanup(A)))
+
 
 // Define the mutex struct.
 // Simplified only for test purpose.
@@ -72,6 +74,17 @@
   return *p;
 }
 
+void cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);
+}
+
+void broken_cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);
+  Bar_fun1(6); // expected-warning {{calling function 'Bar_fun1' requires holding mutex 'mu1' exclusively}}
+}
+
 int main(void) {
 
   Foo_fun1(1); // expected-warning{{calling function 'Foo_fun1' requires holding mutex 'mu2'}} \
@@ -127,6 +140,21 @@
 // expected-note@-1{{mutex released here}}
   mutex_shared_unlock(&mu1);// expected-warning {{releasing mutex 'mu1' that was not held}}
 
+  /// Cleanup functions
+  {
+mutex_exclusive_lock(&mu1);
+int CLEANUP(cleanup_int) i;
+
+Bar_fun1(3);
+  }
+  Bar_fun1(4); // expected-warning {{calling function 'Bar_fun1' requires holding mutex 'mu1' exclusively}}
+
+
+  {
+mutex_exclusive_lock(&mu1);
+int CLEANUP(broken_cleanup_int) i2;
+  }
+
   return 0;
 }
 
Index: clang/lib/Analysis/ThreadSafetyCommon.cpp
===
--- clang/lib/Analysis/ThreadSafetyCommon.cpp
+++ clang/lib/Analysis/ThreadSafetyCommon.cpp
@@ -110,7 +110,8 @@
 /// \param D   The declaration to which the attribute is attached.
 /// \param DeclExp An expression involving the Decl to which the attribute
 ///is attached.  E.g. the call to a function.
-/// \param SelfS-expression to substitute for a \ref CXXThisExpr.
+/// \param SelfS-expression to substitute for a \ref CXXThisExpr in a call,
+///or argument to a cleanup function.
 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
const NamedDecl *D,
const Expr *DeclExp,
@@ -144,7 +145,11 @@
 
   if (Self) {
 assert(!Ctx.SelfArg && "Ambiguous self argument");
-Ctx.SelfArg = Self;
+assert(isa(D) && "Self argument requires function");
+if (isa(D))
+  Ctx.SelfArg = Self;
+else
+  Ctx.FunArgs = Self;
 
 // If the attribute has no arguments, then assume the argument is "this".
 if (!AttrExp)
@@ -312,8 +317,14 @@
   ? (cast(D)->getCanonicalDecl() == Canonical)
   : (cast(D)->getCanonicalDecl() == Canonical)) {
 // Substitute call arguments for references to function parameters
-assert(I < Ctx->NumArgs);
-return translate(Ctx->FunArgs[I], Ctx->Prev);
+if (const auto *const *FunArgs =
+Ctx->FunArgs.dyn_cast()) {
+  assert(I < Ctx->NumArgs);
+  return translate(FunArgs[I], Ctx->Prev);
+}
+
+assert(I == 0);
+return Ctx->FunArgs.get();
   }
 }
 // Map the param back to the param of the original function declaration
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2414,6 +2414,15 @@
 AD.getTriggerStmt()->getEndLoc());
   break;
 }
+
+case CFGElement::CleanupFunction: {
+  const CFGCleanupFunction &CF = BI.castAs();
+  LocksetBuilder.handleCall(/*Exp=*/nullptr, CF.getFunctionDecl(),
+SxBuilder.createVariable(CF.getVarDecl()),
+CF.getVarDecl()->getLocation());
+  break;
+}
+
 case CFGElement::TemporaryDtor: {
   auto TD = BI.castAs();
 
Index: clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
===
--- clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
+++ clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
@@ -361,7 +361,7 @@
 unsigned NumArgs = 0;
 
 // Function arguments
-const Expr *const *FunArgs = nullptr;
+llvm::PointerUnion FunArgs = nullptr;
 
 // is Self

[clang-tools-extra] 4af340a - [clangd] Forward --target to system include extraction (#65824)

2023-09-11 Thread via cfe-commits

Author: Matthew Mirvish
Date: 2023-09-11T04:11:37-04:00
New Revision: 4af340a6afb971c2f79d19b3575c7831f6949503

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

LOG: [clangd] Forward --target to system include extraction (#65824)

Some clang multilib configurations (such as the one currently used in
the [beta ARM LLVM
toolchain](https://github.com/ARM-software/LLVM-embedded-toolchain-for-Arm))
wind up only reporting the C++ include paths properly if they get passed
the correct target. This patch ensures the `--target` (or `-target`)
arguments are correctly sent to the queried driver.

Added: 


Modified: 
clang-tools-extra/clangd/SystemIncludeExtractor.cpp
clang-tools-extra/clangd/test/system-include-extractor.test

Removed: 




diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index ac99b220f6bd3f0..88df5b04ccb09f3 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -87,12 +87,13 @@ struct DriverArgs {
   std::string Lang;
   std::string Sysroot;
   std::string ISysroot;
+  std::string Target;
 
   bool operator==(const DriverArgs &RHS) const {
 return std::tie(Driver, StandardIncludes, StandardCXXIncludes, Lang,
-Sysroot, ISysroot) ==
+Sysroot, ISysroot, Target) ==
std::tie(RHS.Driver, RHS.StandardIncludes, RHS.StandardCXXIncludes,
-RHS.Lang, RHS.Sysroot, ISysroot);
+RHS.Lang, RHS.Sysroot, RHS.ISysroot, RHS.Target);
   }
 
   DriverArgs(const tooling::CompileCommand &Cmd, llvm::StringRef File) {
@@ -130,6 +131,11 @@ struct DriverArgs {
   ISysroot = Cmd.CommandLine[I + 1];
 else
   ISysroot = Arg.str();
+  } else if (Arg.consume_front("--target=")) {
+Target = Arg.str();
+  } else if (Arg.consume_front("-target")) {
+if (Arg.empty() && I + 1 < E)
+  Target = Cmd.CommandLine[I + 1];
   }
 }
 
@@ -167,6 +173,8 @@ struct DriverArgs {
   Args.append({"--sysroot", Sysroot});
 if (!ISysroot.empty())
   Args.append({"-isysroot", ISysroot});
+if (!Target.empty())
+  Args.append({"-target", Target});
 return Args;
   }
 

diff  --git a/clang-tools-extra/clangd/test/system-include-extractor.test 
b/clang-tools-extra/clangd/test/system-include-extractor.test
index 2a2c900316a9161..66882e424bb9216 100644
--- a/clang-tools-extra/clangd/test/system-include-extractor.test
+++ b/clang-tools-extra/clangd/test/system-include-extractor.test
@@ -17,6 +17,7 @@
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot /isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"-target arm-linux-gnueabihf"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
@@ -36,7 +37,7 @@
 
 # Generate a compile_commands.json that will query the mock driver we've
 # created. Which should add a.h and b.h into include search path.
-# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp 
-nostdinc --sysroot /my/sysroot/path -isysroot/isysroot", "file": 
"the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp 
--target=arm-linux-gnueabihf -nostdinc --sysroot /my/sysroot/path 
-isysroot/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # RUN: sed -e "s|INPUT_DIR|%/t.dir|g" %s > %t.test.1
 # On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
@@ -74,7 +75,7 @@
 {"jsonrpc":"2.0","method":"exit"}
 
 # Generate a 
diff erent compile_commands.json which does not point to the mock driver
-# RUN: echo '[{"directory": "%/t.dir", "command": "gcc the-file.cpp -nostdinc 
--sysroot /my/sysroot/path -isysroot/isysroot", "file": "the-file.cpp"}]' > 
%t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "gcc the-file.cpp 
--target=arm-linux-gnueabihf -nostdinc --sysroot /my/sysroot/path 
-isysroot/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # Generate a clangd config file which points to the mock driver instead
 # RUN: echo 'CompileFlags:' > %t.dir/.clangd



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

[clang-tools-extra] [clangd] Forward --target to system include extraction (PR #65824)

2023-09-11 Thread Nathan Ridge via cfe-commits

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


[PATCH] D155978: [SPIRV] Add SPIR-V logical triple.

2023-09-11 Thread Nathan Gauër via Phabricator via cfe-commits
Keenuts added a comment.

> Either I could push the patch for you (adding you as an author) or preferably 
> you could gain commit access yourself for this and future patches.

Thanks, got commit access. Running tests again and merging this.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155978/new/

https://reviews.llvm.org/D155978

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


[PATCH] D138546: Clangd: Preserve target flags in system includes extractor

2023-09-11 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

This can be closed, as the change has been made in 
https://github.com/llvm/llvm-project/pull/65824


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138546/new/

https://reviews.llvm.org/D138546

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread Kinuko Yasuda via cfe-commits

https://github.com/kinu created https://github.com/llvm/llvm-project/pull/65932:

No one seems to be using transferBlock() in TypeErasedDataflowAnalysis, it is 
likely a remnant of old code


>From dc808e4edccdd8d405660729713dd169c87daf71 Mon Sep 17 00:00:00 2001
From: Kinuko Yasuda 
Date: Fri, 8 Sep 2023 21:47:25 +
Subject: [PATCH] [clang][dataflow] Remove unused function: transferBlock()

No one seems to be using transferBlock() in TypeErasedDataflowAnalysis, it is
likely a remnant of old code
---
 .../TypeErasedDataflowAnalysis.h  | 19 ---
 .../TypeErasedDataflowAnalysis.cpp| 12 
 2 files changed, 31 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index 88a33d19f7d8f61..67c323dbf45e1b2 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
@@ -132,25 +132,6 @@ struct TypeErasedDataflowAnalysisState {
   }
 };
 
-/// Transfers the state of a basic block by evaluating each of its elements in
-/// the context of `Analysis` and the states of its predecessors that are
-/// available in `BlockStates`. `PostVisitCFG` (if provided) will be applied to
-/// each element in the block, after it is evaluated.
-///
-/// Requirements:
-///
-///   All predecessors of `Block` except those with loop back edges must have
-///   already been transferred. States in `BlockStates` that are set to
-///   `std::nullopt` represent basic blocks that are not evaluated yet.
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG = nullptr);
-
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. Indices of
 /// the returned vector correspond to basic block IDs. Returns an error if the
diff --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 626b57b43755ec7..900aa97e9f6de64 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -495,18 +495,6 @@ transferCFGBlock(const CFGBlock &Block, AnalysisContext 
&AC,
   return State;
 }
 
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG) {
-  AnalysisContext AC(CFCtx, Analysis, InitEnv, BlockStates);
-  return transferCFGBlock(Block, AC, PostVisitCFG);
-}
-
 llvm::Expected>>
 runTypeErasedDataflowAnalysis(
 const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis,

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread Kinuko Yasuda via cfe-commits

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread via cfe-commits

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


[clang] [clang][dataflow] Remove unused function: transferBlock() (PR #65932)

2023-09-11 Thread via cfe-commits

llvmbot wrote:

@llvm/pr-subscribers-clang


Changes

No one seems to be using transferBlock() in TypeErasedDataflowAnalysis, it is 
likely a remnant of old code

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

2 Files Affected:

- (modified) 
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h (-19) 
- (modified) clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
(-12) 



diff --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index 88a33d19f7d8f61..67c323dbf45e1b2 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
@@ -132,25 +132,6 @@ struct TypeErasedDataflowAnalysisState {
   }
 };
 
-/// Transfers the state of a basic block by evaluating each of its elements in
-/// the context of `Analysis` and the states of its predecessors that are
-/// available in `BlockStates`. `PostVisitCFG` (if provided) will be applied to
-/// each element in the block, after it is evaluated.
-///
-/// Requirements:
-///
-///   All predecessors of `Block` except those with loop back edges must have
-///   already been transferred. States in `BlockStates` that are set to
-///   `std::nullopt` represent basic blocks that are not evaluated yet.
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG = nullptr);
-
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. Indices of
 /// the returned vector correspond to basic block IDs. Returns an error if the
diff --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 626b57b43755ec7..900aa97e9f6de64 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -495,18 +495,6 @@ transferCFGBlock(const CFGBlock &Block, AnalysisContext 
&AC,
   return State;
 }
 
-TypeErasedDataflowAnalysisState transferBlock(
-const ControlFlowContext &CFCtx,
-llvm::ArrayRef> BlockStates,
-const CFGBlock &Block, const Environment &InitEnv,
-TypeErasedDataflowAnalysis &Analysis,
-std::function
-PostVisitCFG) {
-  AnalysisContext AC(CFCtx, Analysis, InitEnv, BlockStates);
-  return transferCFGBlock(Block, AC, PostVisitCFG);
-}
-
 llvm::Expected>>
 runTypeErasedDataflowAnalysis(
 const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis,




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


[PATCH] D155978: [SPIRV] Add SPIR-V logical triple.

2023-09-11 Thread Nathan Gauër via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG53b6a169e453: [SPIR-V] Add SPIR-V logical triple. (authored 
by Keenuts).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155978/new/

https://reviews.llvm.org/D155978

Files:
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/SPIR.cpp
  clang/lib/Basic/Targets/SPIR.h
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/TargetParser/Triple.h
  llvm/lib/TargetParser/Triple.cpp
  llvm/unittests/TargetParser/TripleTest.cpp

Index: llvm/unittests/TargetParser/TripleTest.cpp
===
--- llvm/unittests/TargetParser/TripleTest.cpp
+++ llvm/unittests/TargetParser/TripleTest.cpp
@@ -319,6 +319,132 @@
   EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
   EXPECT_EQ(Triple::UnknownOS, T.getOS());
 
+  T = Triple("spirv-unknown-shadermodel-pixel");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Pixel, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-vertex");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Vertex, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-geometry");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Geometry, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-library");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Library, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-raygeneration");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::RayGeneration, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-intersection");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Intersection, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-anyhit");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::AnyHit, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-closesthit");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::ClosestHit, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-miss");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Miss, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-callable");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Callable, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-mesh");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Mesh, T.getEnvironment());
+
+  T = Triple("spirv-unknown-shadermodel-amplification");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Amplification, T.getEnvironment());
+
+  T = Triple("spirv1.0-unknown-shadermodel-compute");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v10, T.getSubArch());
+  EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
+  EXPECT_EQ(Triple::ShaderModel, T.getOS());
+  EXPECT_EQ(Triple::Compute, T.getEnvironment());
+
+  T = Triple("spirv1.1-unknown-shadermodel-compute");
+  EXPECT_EQ(Triple::spirv, T.getArch());
+  EXPECT_EQ(Triple::SPIRVSubArch_v11, T.getSubArch());
+  EXPECT_EQ(Triple::U

[clang] 53b6a16 - [SPIR-V] Add SPIR-V logical triple.

2023-09-11 Thread Nathan Gauër via cfe-commits

Author: Nathan Gauër
Date: 2023-09-11T10:15:24+02:00
New Revision: 53b6a169e453a2a91d3713ca16fa089853c670a8

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

LOG: [SPIR-V] Add SPIR-V logical triple.

Clang implements SPIR-V with both Physical32 and Physical64 addressing
models. This commit adds a new triple value for the Logical
addressing model.

Differential Revision: https://reviews.llvm.org/D155978

Added: 


Modified: 
clang/lib/Basic/Targets.cpp
clang/lib/Basic/Targets/SPIR.cpp
clang/lib/Basic/Targets/SPIR.h
clang/lib/Frontend/CompilerInvocation.cpp
llvm/include/llvm/TargetParser/Triple.h
llvm/lib/TargetParser/Triple.cpp
llvm/unittests/TargetParser/TripleTest.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 2afffc463d18be1..69576dbc458d9a1 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -665,6 +665,9 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple &Triple,
   return nullptr;
 return std::make_unique(Triple, Opts);
   }
+  case llvm::Triple::spirv: {
+return std::make_unique(Triple, Opts);
+  }
   case llvm::Triple::spirv32: {
 if (os != llvm::Triple::UnknownOS ||
 Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)

diff  --git a/clang/lib/Basic/Targets/SPIR.cpp 
b/clang/lib/Basic/Targets/SPIR.cpp
index 09d482a8b9ef594..dc920177d3a9107 100644
--- a/clang/lib/Basic/Targets/SPIR.cpp
+++ b/clang/lib/Basic/Targets/SPIR.cpp
@@ -33,19 +33,24 @@ void SPIR64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
   DefineStd(Builder, "SPIR64", Opts);
 }
 
+void BaseSPIRVTargetInfo::getTargetDefines(const LangOptions &Opts,
+   MacroBuilder &Builder) const {
+  DefineStd(Builder, "SPIRV", Opts);
+}
+
 void SPIRVTargetInfo::getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
-  DefineStd(Builder, "SPIRV", Opts);
+  BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
 }
 
 void SPIRV32TargetInfo::getTargetDefines(const LangOptions &Opts,
  MacroBuilder &Builder) const {
-  SPIRVTargetInfo::getTargetDefines(Opts, Builder);
+  BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
   DefineStd(Builder, "SPIRV32", Opts);
 }
 
 void SPIRV64TargetInfo::getTargetDefines(const LangOptions &Opts,
  MacroBuilder &Builder) const {
-  SPIRVTargetInfo::getTargetDefines(Opts, Builder);
+  BaseSPIRVTargetInfo::getTargetDefines(Opts, Builder);
   DefineStd(Builder, "SPIRV64", Opts);
 }

diff  --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index a7ea03e7a5dd32b..9ab2b7c60936392 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -93,10 +93,6 @@ class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public 
TargetInfo {
   : TargetInfo(Triple) {
 assert((Triple.isSPIR() || Triple.isSPIRV()) &&
"Invalid architecture for SPIR or SPIR-V.");
-assert(getTriple().getOS() == llvm::Triple::UnknownOS &&
-   "SPIR(-V) target must use unknown OS");
-assert(getTriple().getEnvironment() == llvm::Triple::UnknownEnvironment &&
-   "SPIR(-V) target must use unknown environment type");
 TLSSupported = false;
 VLASupported = false;
 LongWidth = LongAlign = 64;
@@ -284,31 +280,53 @@ class LLVM_LIBRARY_VISIBILITY SPIR64TargetInfo : public 
SPIRTargetInfo {
 MacroBuilder &Builder) const override;
 };
 
-class LLVM_LIBRARY_VISIBILITY SPIRVTargetInfo : public BaseSPIRTargetInfo {
+class LLVM_LIBRARY_VISIBILITY BaseSPIRVTargetInfo : public BaseSPIRTargetInfo {
 public:
-  SPIRVTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
+  BaseSPIRVTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
   : BaseSPIRTargetInfo(Triple, Opts) {
 assert(Triple.isSPIRV() && "Invalid architecture for SPIR-V.");
-assert(getTriple().getOS() == llvm::Triple::UnknownOS &&
-   "SPIR-V target must use unknown OS");
-assert(getTriple().getEnvironment() == llvm::Triple::UnknownEnvironment &&
-   "SPIR-V target must use unknown environment type");
+  }
+
+  bool hasFeature(StringRef Feature) const override {
+return Feature == "spirv";
   }
 
   void getTargetDefines(const LangOptions &Opts,
 MacroBuilder &Builder) const override;
+};
 
-  bool hasFeature(StringRef Feature) const override {
-return Feature == "spirv";
+class LLVM_LIBRARY_VISIBILITY SPIRVTargetInfo : public BaseSPIRVTargetInfo {
+public:
+  SPIRVTargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
+  : BaseSPIRVTargetInfo(Triple, 

[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread Owen Pan via cfe-commits

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

Fixes #65877.

>From 86b83692a9f13b8c608190f6abc3111719583730 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 11 Sep 2023 01:00:24 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating '&&' enclosed in '<'
 and '>'

Fixes #65877.
---
 clang/lib/Format/TokenAnnotator.cpp   | 7 +--
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e925bee44cd0c6a..142168e074bbc27 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2598,9 +2598,12 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&(" is quite unlikely to be two successive unary "&".
-if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
+// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
+// unary "&".
+if (Tok.is(tok::ampamp) &&
+NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
   return TT_BinaryOperator;
+}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 434852983712940..be025dab86fafa5 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -280,6 +280,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[12], tok::ampamp, TT_BinaryOperator);
   EXPECT_TOKEN(Tokens[27], tok::ampamp, TT_BinaryOperator);
 
+  Tokens = annotate("foo = *i < *j && *j > *k;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::less, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[7], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[10], tok::greater, TT_BinaryOperator);
+
   FormatStyle Style = getLLVMStyle();
   Style.TypeNames.push_back("MYI");
   Tokens = annotate("if (MYI *p{nullptr})", Style);

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


[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread via cfe-commits

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


[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread via cfe-commits

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


[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread via cfe-commits

llvmbot wrote:

@llvm/pr-subscribers-clang


Changes

Fixes #65877.
--
Full diff: https://github.com/llvm/llvm-project/pull/65933.diff

2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+5-2) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+6) 



diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e925bee44cd0c6..142168e074bbc2 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2598,9 +2598,12 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&(" is quite unlikely to be two successive unary "&".
-if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
+// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
+// unary "&".
+if (Tok.is(tok::ampamp) &&
+NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
   return TT_BinaryOperator;
+}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 43485298371294..be025dab86fafa 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -280,6 +280,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[12], tok::ampamp, TT_BinaryOperator);
   EXPECT_TOKEN(Tokens[27], tok::ampamp, TT_BinaryOperator);
 
+  Tokens = annotate("foo = *i < *j && *j > *k;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::less, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[7], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[10], tok::greater, TT_BinaryOperator);
+
   FormatStyle Style = getLLVMStyle();
   Style.TypeNames.push_back("MYI");
   Tokens = annotate("if (MYI *p{nullptr})", Style);




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


[clang] [clang-format] Fix a bug in annotating '&&' enclosed in '<' and '>' (PR #65933)

2023-09-11 Thread via cfe-commits

llvmbot wrote:

@llvm/pr-subscribers-clang-format


Changes

Fixes #65877.
--
Full diff: https://github.com/llvm/llvm-project/pull/65933.diff

2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+5-2) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+6) 



diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e925bee44cd0c6a..142168e074bbc27 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2598,9 +2598,12 @@ class AnnotatingParser {
 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
-// "&&(" is quite unlikely to be two successive unary "&".
-if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
+// "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
+// unary "&".
+if (Tok.is(tok::ampamp) &&
+NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
   return TT_BinaryOperator;
+}
 
 // This catches some cases where evaluation order is used as control flow:
 //   aaa && aaa->f();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 434852983712940..be025dab86fafa5 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -280,6 +280,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[12], tok::ampamp, TT_BinaryOperator);
   EXPECT_TOKEN(Tokens[27], tok::ampamp, TT_BinaryOperator);
 
+  Tokens = annotate("foo = *i < *j && *j > *k;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::less, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[7], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[10], tok::greater, TT_BinaryOperator);
+
   FormatStyle Style = getLLVMStyle();
   Style.TypeNames.push_back("MYI");
   Tokens = annotate("if (MYI *p{nullptr})", Style);




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


[PATCH] D150647: [WIP][analyzer] Fix EnumCastOutOfRangeChecker C++17 handling

2023-09-11 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 abandoned this revision.
gamesh411 added a comment.

This is no longer relevant, as the fix already went in (D153954 
).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D150647/new/

https://reviews.llvm.org/D150647

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


[clang] [clang-format] Fix a bug in annotating `&&` enclosed in `<` and `>` (PR #65933)

2023-09-11 Thread Owen Pan via cfe-commits

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


[PATCH] D158156: [analyzer] Add C++ array delete checker

2023-09-11 Thread Discookie via Phabricator via cfe-commits
Discookie updated this revision to Diff 556402.
Discookie marked 8 inline comments as done.
Discookie added a comment.

Added a test for taking last upcast only for the note tag. For now the visitor 
matches all explicit casts, because there are too many edge cases to count for 
now wrt. explicit upcasting.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158156/new/

https://reviews.llvm.org/D158156

Files:
  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

Index: clang/www/analyzer/alpha_checks.html
===
--- clang/www/analyzer/alpha_checks.html
+++ clang/www/analyzer/alpha_checks.html
@@ -330,6 +330,27 @@
 
 
 
+
+alpha.cplusplus.ArrayDelete
+(C++)
+Reports destructions of arrays of polymorphic objects that are destructed as
+their base class
+
+
+
+Base *create() {
+  Base *x = new Derived[10]; // note: conversion from derived to base
+ //   happened here
+  return x;
+}
+
+void sink(Base *x) {
+  delete[] x; // warn: Deleting an array of polymorphic objects is undefined
+}
+
+
+
+
 
 alpha.cplusplus.DeleteWithNonVirtualDtor
 (C++)
Index: clang/test/Analysis/ArrayDelete.cpp
===
--- /dev/null
+++ clang/test/Analysis/ArrayDelete.cpp
@@ -0,0 +1,100 @@
+// RUN: %clang_cc1 -analyze -analyzer-checker=alpha.cplusplus.ArrayDelete -std=c++11 -verify -analyzer-output=text %s
+
+struct Base {
+virtual ~Base() = default;
+};
+
+struct Derived : public Base {};
+
+struct DoubleDerived : public Derived {};
+
+Derived *get();
+
+Base *create() {
+Base *b = new Derived[3]; // expected-note{{Conversion from derived to base happened here}}
+return b;
+}
+
+void sink(Base *b) {
+delete[] b; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+}
+
+void sink_cast(Base *b) {
+delete[] reinterpret_cast(b); // no-warning
+}
+
+void sink_derived(Derived *d) {
+delete[] d; // no-warning
+}
+
+void same_function() {
+Base *sd = new Derived[10]; // expected-note{{Conversion from derived to base happened here}}
+delete[] sd; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+Base *dd = new DoubleDerived[10]; // expected-note{{Conversion from derived to base happened here}}
+delete[] dd; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+}
+
+void different_function() {
+Base *assigned = get(); // expected-note{{Conversion from derived to base happened here}}
+delete[] assigned; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+Base *indirect;
+indirect = get(); // expected-note{{Conversion from derived to base happened here}}
+delete[] indirect; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+Base *created = create(); // expected-note{{Calling 'create'}}
+// expected-note@-1{{Returning from 'create'}}
+delete[] created; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+Base *sb = new Derived[10]; // expected-note{{Conversion from derived to base happened here}}
+sink(sb); // expected-note{{Calling 'sink'}}
+}
+
+void safe_function() {
+Derived *d = new Derived[10];
+delete[] d; // no-warning
+
+Base *b = new Derived[10];
+delete[] reinterpret_cast(b); // no-warning
+
+Base *sb = new Derived[10];
+sink_cast(sb); // no-warning
+
+Derived *sd = new Derived[10];
+sink_derived(sd); // no-warning
+}
+
+void multiple_derived() {
+Base *b = new DoubleDerived[10]; // expected-note{{Conversion from derived to base happened here}}
+delete[] b; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+// FIXME: Currently all explicit casts are reported as derived-to-base casts.
+Base *b2 = new DoubleDerived[10];
+Derived *d2 = reinterpret_cast(b2); // expected-note{{Conversion from derived to base happened here}}
+delete[] d2; // expected-warning{{Deleting an array of polymorphic objects is undefined}}
+// expected-note@-1{{Deleting an array of polymorphic objects is undefined}}
+
+Derived *d3 = new DoubleD

[PATCH] D158156: [analyzer] Add C++ array delete checker

2023-09-11 Thread Discookie via Phabricator via cfe-commits
Discookie added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:1793-1803
+.. code-block:: cpp
+
+ Base *create() {
+   Base *x = new Derived[10]; // note: conversion from derived to base
+  //   happened here
+   return x;
+ }

donat.nagy wrote:
> steakhal wrote:
> > Discookie wrote:
> > > steakhal wrote:
> > > > Make sure in the example the `create` is related (e.g. called/used).
> > > > Also, refrain from using `sink` in the docs. It's usually used in the 
> > > > context of taint analysis.
> > > Changed the example - should I change the DeleteWithNonVirtualDtor 
> > > example as well? That has the same issues as you said here.
> > I have no opinion. You could.
> I think you should definitely update it, for the sake of consistency and just 
> improving things whenever we can. This commit already touches the code of 
> that checker, there is no point in leaving bad documentation behind us...
Updated.



Comment at: clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp:126
+
+  if (!DerivedClass->isDerivedFrom(BaseClass))
+return;

steakhal wrote:
> Is this transitive?
> 
> BTW inheritance can only be expressed if the class is a definition, right?
> Thus passing this should imply has definition.
It's transitive indeed.

I thought there were some presumptions about hasDefinition() in 
isDerivedFrom(), but apparently not, and it didn't cause any crashes either. 
Removed the redundant checks.



Comment at: clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp:192
+
+  const Stmt *S = N->getStmtForDiagnostics();
+  if (!S)

steakhal wrote:
> Aren't you actually interested in 
> N->getLocation().getAs().getStmt()?
> 
> The diag stmt can be fuzzy, but the PP is exact.
As far as I can tell, getStmtForDiagnostics() does exactly that, but with a bit 
more edge case handling and a couple fallbacks.



Comment at: clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp:196
+
+  const auto *CastE = dyn_cast(S);
+  if (!CastE)

steakhal wrote:
> If you dyncast to ImplicitCastExpr, couldn't you have done it here?
I'm interested in all cast expressions, not just implicit ones. There can also 
be explicit upcasts as well.



Comment at: clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp:202
+  // Explicit casts can have different CastKinds.
+  if (const auto *ImplCastE = dyn_cast(CastE)) {
+if (ImplCastE->getCastKind() != CK_DerivedToBase)

steakhal wrote:
> How do you know that that this castexpr corresponds to the region for which 
> you report the bug? To mez this might be some unrelated castexpr.
> I was expecting the offending memregion being passed to the visitor, that it 
> can check against.
We know it's the one we are looking for, because the checker marked it 
interesting earlier. Not sure how memregion equality check would differ from 
taking isInteresting(), but it can be changed to that if needed.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158156/new/

https://reviews.llvm.org/D158156

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


[clang-tools-extra] 13e5faf - [clangd] Fix buildbot breakages from stemming from 64366d4935d3c56ce5906a321edb2e91d4f886bc

2023-09-11 Thread Viktoriia Bakalova via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-09-11T08:30:06Z
New Revision: 13e5fafb5548caf52fc067ec443604d20bf60684

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

LOG: [clangd] Fix buildbot breakages from stemming from 
64366d4935d3c56ce5906a321edb2e91d4f886bc

Added: 


Modified: 
clang-tools-extra/clangd/index/SymbolCollector.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 699370fe1adf3af..8fe1146bc2752c3 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -943,7 +943,7 @@ void SymbolCollector::finish() {
 // FIXME: Get rid of this once include-cleaner has support for system
 // headers.
 if (auto Canonical =
-HeaderFileURIs->mapCanonical(H.physical()->getName());
+HeaderFileURIs->mapCanonical(H.physical().getName());
 !Canonical.empty())
   SpellingIt->second = Canonical;
 // For physical files, prefer URIs as spellings might change
@@ -951,7 +951,7 @@ void SymbolCollector::finish() {
 else if (tooling::isSelfContainedHeader(H.physical(), SM,
 PP->getHeaderSearchInfo()))
   SpellingIt->second =
-  HeaderFileURIs->toURI(H.physical()->getLastRef());
+  HeaderFileURIs->toURI(H.physical());
   } else {
 SpellingIt->second = include_cleaner::spellHeader(
 {H, PP->getHeaderSearchInfo(),



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


[clang] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

https://github.com/jmmartinez created 
https://github.com/llvm/llvm-project/pull/65938:

Addressing remarks after merge of D159257

* Add comment
* Remove irrelevant CHECKs from test
* Simplify function
* Use llvm::sort before setting target-features as it is done in CodeGenModeule

From bd46d855b4cc10ac3085833ff1395245d787a1ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Juan=20Manuel=20MARTINEZ=20CAAMA=C3=91O?= 
Date: Mon, 11 Sep 2023 11:00:34 +0200
Subject: [PATCH] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures

Addressing remarks after merge of D159257

* Add comment
* Remove irrelevant CHECKs from test
* Simplify function
* Use llvm::sort before setting target-features as it is done in
CodeGenModeule
---
 clang/lib/CodeGen/CGCall.cpp  | 47 +--
 clang/test/CodeGen/link-builtin-bitcode.c |  8 ++--
 2 files changed, 22 insertions(+), 33 deletions(-)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e15a4634b1d041b..3fe8d0a7cf49e16 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2001,52 +2001,41 @@ static void getTrivialDefaultFunctionAttributes(
   }
 }
 
+/// Merges `target-features` from \TargetOpts and \F, and sets the result in
+/// \FuncAttr
+/// * features from \F are always kept
+/// * a feature from \TargetOpts is kept if itself and its opposite are absent
+/// from \F
 static void
 overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr,
const llvm::Function &F,
const TargetOptions &TargetOpts) {
   auto FFeatures = F.getFnAttribute("target-features");
 
-  llvm::StringSet<> IncompatibleFeatureNames;
+  llvm::StringSet<> MergedNames;
   SmallVector MergedFeatures;
   MergedFeatures.reserve(TargetOpts.Features.size());
 
-  if (FFeatures.isValid()) {
-const auto &TFeatures = TargetOpts.FeatureMap;
-for (StringRef Feature : llvm::split(FFeatures.getValueAsString(), ',')) {
+  auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
+for (StringRef Feature : FeatureRange) {
   if (Feature.empty())
 continue;
-
-  bool EnabledForFunc = Feature.starts_with("+");
-  assert(EnabledForFunc || Feature.starts_with("-"));
-
+  assert(Feature[0] == '+' || Feature[0] == '-');
   StringRef Name = Feature.drop_front(1);
-  auto TEntry = TFeatures.find(Name);
-
-  // Preserves features that are incompatible (either set to something
-  // different or missing) from the target features
-  bool MissingFromTarget = TEntry == TFeatures.end();
-  bool EnabledForTarget = !MissingFromTarget && TEntry->second;
-  bool Incompatible = EnabledForTarget != EnabledForFunc;
-  if (MissingFromTarget || Incompatible) {
+  bool Merged = !MergedNames.insert(Name).second;
+  if (!Merged)
 MergedFeatures.push_back(Feature);
-if (Incompatible)
-  IncompatibleFeatureNames.insert(Name);
-  }
 }
-  }
+  };
 
-  for (StringRef Feature : TargetOpts.Features) {
-if (Feature.empty())
-  continue;
-StringRef Name = Feature.drop_front(1);
-if (IncompatibleFeatureNames.contains(Name))
-  continue;
-MergedFeatures.push_back(Feature);
-  }
+  if (FFeatures.isValid())
+AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
+  AddUnmergedFeatures(TargetOpts.Features);
 
-  if (!MergedFeatures.empty())
+  if (!MergedFeatures.empty()) {
+llvm::sort(MergedFeatures);
 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
+  }
 }
 
 void CodeGen::mergeDefaultFunctionDefinitionAttributes(
diff --git a/clang/test/CodeGen/link-builtin-bitcode.c 
b/clang/test/CodeGen/link-builtin-bitcode.c
index fe60a9746f1c85f..d4818cc28717312 100644
--- a/clang/test/CodeGen/link-builtin-bitcode.c
+++ b/clang/test/CodeGen/link-builtin-bitcode.c
@@ -43,7 +43,7 @@ int bar() { return no_attr() + attr_in_target() + 
attr_not_in_target() + attr_in
 // CHECK-LABEL: @attr_incompatible
 // CHECK-SAME: () #[[ATTR_INCOMPATIBLE:[0-9]+]] {
 
-// CHECK: attributes #[[ATTR_BAR]] = { noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx90a" 
"target-features"="+16-bit-insts,+atomic-buffer-global-pk-add-f16-insts,+atomic-fadd-rtn-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot3-insts,+dot4-insts,+dot5-insts,+dot6-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+gfx90a-insts,+mai-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
 }
-// CHECK: attributes #[[ATTR_COMPATIBLE]] = { convergent noinline nounwind 
optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx90a" 
"target-features"="+16-bit-insts,+atomic-buffer-global-pk-add-f16-insts,+atomic-fadd-rtn-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot3-insts,+dot4-insts,+dot5-insts,+dot6-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+gfx90

[clang] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [NFC][Clang] overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [NFC][Clang] Address reviews about overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread Juan Manuel Martinez Caamaño via cfe-commits

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


[clang] [NFC][Clang] Address reviews about overrideFunctionFeaturesWithTargetFeatures (PR #65938)

2023-09-11 Thread via cfe-commits

llvmbot wrote:

@llvm/pr-subscribers-clang


Changes

Addressing remarks after merge of D159257

* Add comment
* Remove irrelevant CHECKs from test
* Simplify function
* Use llvm::sort before setting target-features as it is done in CodeGenModeule
--
Full diff: https://github.com/llvm/llvm-project/pull/65938.diff

2 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (+18-29) 
- (modified) clang/test/CodeGen/link-builtin-bitcode.c (+4-4) 



diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e15a4634b1d041b..3fe8d0a7cf49e16 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2001,52 +2001,41 @@ static void getTrivialDefaultFunctionAttributes(
   }
 }
 
+/// Merges `target-features` from \TargetOpts and \F, and sets the result in
+/// \FuncAttr
+/// * features from \F are always kept
+/// * a feature from \TargetOpts is kept if itself and its opposite are absent
+/// from \F
 static void
 overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr,
const llvm::Function &F,
const TargetOptions &TargetOpts) {
   auto FFeatures = F.getFnAttribute("target-features");
 
-  llvm::StringSet<> IncompatibleFeatureNames;
+  llvm::StringSet<> MergedNames;
   SmallVector MergedFeatures;
   MergedFeatures.reserve(TargetOpts.Features.size());
 
-  if (FFeatures.isValid()) {
-const auto &TFeatures = TargetOpts.FeatureMap;
-for (StringRef Feature : llvm::split(FFeatures.getValueAsString(), ',')) {
+  auto AddUnmergedFeatures = [&](auto &&FeatureRange) {
+for (StringRef Feature : FeatureRange) {
   if (Feature.empty())
 continue;
-
-  bool EnabledForFunc = Feature.starts_with("+");
-  assert(EnabledForFunc || Feature.starts_with("-"));
-
+  assert(Feature[0] == '+' || Feature[0] == '-');
   StringRef Name = Feature.drop_front(1);
-  auto TEntry = TFeatures.find(Name);
-
-  // Preserves features that are incompatible (either set to something
-  // different or missing) from the target features
-  bool MissingFromTarget = TEntry == TFeatures.end();
-  bool EnabledForTarget = !MissingFromTarget && TEntry->second;
-  bool Incompatible = EnabledForTarget != EnabledForFunc;
-  if (MissingFromTarget || Incompatible) {
+  bool Merged = !MergedNames.insert(Name).second;
+  if (!Merged)
 MergedFeatures.push_back(Feature);
-if (Incompatible)
-  IncompatibleFeatureNames.insert(Name);
-  }
 }
-  }
+  };
 
-  for (StringRef Feature : TargetOpts.Features) {
-if (Feature.empty())
-  continue;
-StringRef Name = Feature.drop_front(1);
-if (IncompatibleFeatureNames.contains(Name))
-  continue;
-MergedFeatures.push_back(Feature);
-  }
+  if (FFeatures.isValid())
+AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(), ','));
+  AddUnmergedFeatures(TargetOpts.Features);
 
-  if (!MergedFeatures.empty())
+  if (!MergedFeatures.empty()) {
+llvm::sort(MergedFeatures);
 FuncAttr.addAttribute("target-features", llvm::join(MergedFeatures, ","));
+  }
 }
 
 void CodeGen::mergeDefaultFunctionDefinitionAttributes(
diff --git a/clang/test/CodeGen/link-builtin-bitcode.c 
b/clang/test/CodeGen/link-builtin-bitcode.c
index fe60a9746f1c85f..d4818cc28717312 100644
--- a/clang/test/CodeGen/link-builtin-bitcode.c
+++ b/clang/test/CodeGen/link-builtin-bitcode.c
@@ -43,7 +43,7 @@ int bar() { return no_attr() + attr_in_target() + 
attr_not_in_target() + attr_in
 // CHECK-LABEL: @attr_incompatible
 // CHECK-SAME: () #[[ATTR_INCOMPATIBLE:[0-9]+]] {
 
-// CHECK: attributes #[[ATTR_BAR]] = { noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx90a" 
"target-features"="+16-bit-insts,+atomic-buffer-global-pk-add-f16-insts,+atomic-fadd-rtn-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot3-insts,+dot4-insts,+dot5-insts,+dot6-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+gfx90a-insts,+mai-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
 }
-// CHECK: attributes #[[ATTR_COMPATIBLE]] = { convergent noinline nounwind 
optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx90a" 
"target-features"="+16-bit-insts,+atomic-buffer-global-pk-add-f16-insts,+atomic-fadd-rtn-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot3-insts,+dot4-insts,+dot5-insts,+dot6-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+gfx90a-insts,+gws,+image-insts,+mai-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
 }
-// CHECK: attributes #[[ATTR_EXTEND]] = { convergent noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx90a" 
"target-features"="+extended-image-insts,+16-bit-insts,+atomic-buffer-global-pk-add-f16-insts,+atomic-fadd-rtn-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot3-insts,+dot4-ins

[clang] [update_cc_test_checks] Use lit's shell to run commands (PR #65333)

2023-09-11 Thread Thomas Preud'homme via cfe-commits


@@ -34,29 +35,22 @@
 }
 
 
-def get_line2func_list(args, clang_args):
+def get_line2func_list(clang_cmd: Command):
 ret = collections.defaultdict(list)
 # Use clang's JSON AST dump to get the mangled name
-json_dump_args = [args.clang] + clang_args + ["-fsyntax-only", "-o", "-"]
+json_dump_args = clang_cmd.args + ["-fsyntax-only", "-o", "/dev/null"]

RoboTux wrote:

Ok

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


[PATCH] D159206: [Clang] Propagate target-features if compatible when using mlink-builtin-bitcode

2023-09-11 Thread Juan Manuel Martinez Caamaño via Phabricator via cfe-commits
jmmartinez added a comment.

@yaxunl I've addressed your remarks on a GitHub PR: 
https://github.com/llvm/llvm-project/pull/65938

Thanks for the remarks! It made me realize that I could simplify the code a lot.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159206/new/

https://reviews.llvm.org/D159206

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


[clang] [clang][dataflow] Remove RecordValue.getLog() usage in HTMLLogger (PR #65645)

2023-09-11 Thread Kinuko Yasuda via cfe-commits

kinu wrote:

Here's the screenshot for a simple code snippet
![Btp9XprWFz4w2yQ 
(1)](https://github.com/llvm/llvm-project/assets/860295/bfd29ab5-ac44-418b-8649-365cfacae2c9)
'Without the patch' image is almost identical

You can see some more screenshots here:
https://docs.google.com/document/d/1gJqU5g7HCUifDUJBb5NzSBC0K-9W4nyZ3zxtpbTUDdk/view


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


[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-09-11 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

ping~


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153701/new/

https://reviews.llvm.org/D153701

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


[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits

https://github.com/DonatNagyE requested changes to this pull request.


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


[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits


@@ -1333,7 +1333,15 @@ void StmtProfiler::VisitPredefinedExpr(const 
PredefinedExpr *S) {
 void StmtProfiler::VisitIntegerLiteral(const IntegerLiteral *S) {
   VisitExpr(S);
   S->getValue().Profile(ID);
-  ID.AddInteger(S->getType()->castAs()->getKind());
+
+  int FoldingSetID = 0;
+
+  if (S->getType()->isBitIntType())
+FoldingSetID = S->getValue().getSExtValue();
+  else
+FoldingSetID = S->getType()->castAs()->getKind();
+
+  ID.AddInteger(FoldingSetID);

DonatNagyE wrote:

You're right, it's better to add a boolean to distinguish between the two cases 
and reduce the chance of collisions. 

Also note that `S->getValue().getSExtValue()` represents the _value_ of the 
integer literal, which is redundant with`S->getValue().Profile(ID)` on an 
earlier line. Instead of it, you need to provide information that uniquely 
identifies the _type_ of the literal -- and `BitIntType` has a `Profile` 
method, which is the canonical solution for this. 

Combining these two suggestions, I'd write something like the following:
```c++
QualType T = S->getType();
if (auto BitIntT = T->getAs()) {
  ID.AddBoolean(true);
  BitIntT->Profile(ID)
} else {
  ID.AddBoolean(false);
  ID.AddInteger(T->castAs()->getKind());
}
```
(disclaimer: untested code, try it out before running it)

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


[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits

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


[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits


@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s bugprone-inc-dec-in-conditions %t
+
+#define foo(x) \
+  ({   \
+_BitInt(5) y = x;  \
+16777215wb ?: ++y; \
+  })
+
+_BitInt(8) v_401_0() { 0 && foo(0); }

DonatNagyE wrote:

Perhaps eliminate the macro definition and replace this function body with
```
if (0) {
  // block defined in the macro
}
```
because the current code seems to be "unnatural" for the untrained eye. (If I 
understand it correctly, this transformation would produce an equivalent 
testcase. If not, then explain why do you need the gcc statement expression.) 

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


[clang] Extension: allow recursive macros (PR #65851)

2023-09-11 Thread via cfe-commits

https://github.com/kelbon updated 
https://github.com/llvm/llvm-project/pull/65851:

>From 2f807b312baef8c6038c2452b84232acb6d6d2c2 Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Sat, 9 Sep 2023 17:51:15 +0400
Subject: [PATCH 1/5] add define2 pp directive

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Lex/MacroInfo.h  | 19 +--
 clang/include/clang/Lex/Preprocessor.h   |  2 +-
 clang/lib/Basic/IdentifierTable.cpp  |  2 ++
 clang/lib/Format/WhitespaceManager.cpp   |  2 +-
 clang/lib/Lex/MacroInfo.cpp  |  3 ++-
 clang/lib/Lex/PPDirectives.cpp   | 16 +++-
 7 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 45ebc200b168986..f059d809823ab42 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -115,6 +115,7 @@ PPKEYWORD(__include_macros)
 
 // C99 6.10.3 - Macro Replacement.
 PPKEYWORD(define)
+PPKEYWORD(define2)
 PPKEYWORD(undef)
 
 // C99 6.10.4 - Line Control.
diff --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 00c1c3866bbd9ca..4f0c8e987610e50 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -102,6 +102,10 @@ class MacroInfo {
   /// like \#define A A.
   bool IsDisabled : 1;
 
+  // True if 'define2' used,
+  // ignores 'IsDisabled' and enables expansion anyway
+  bool AllowRecurse : 1;
+
   /// True if this macro is either defined in the main file and has
   /// been used, or if it is not defined in the main file.
   ///
@@ -278,18 +282,13 @@ class MacroInfo {
   /// Return true if this macro is enabled.
   ///
   /// In other words, that we are not currently in an expansion of this macro.
-  bool isEnabled() const { return !IsDisabled; }
-
-  void EnableMacro() {
-assert(IsDisabled && "Cannot enable an already-enabled macro!");
-IsDisabled = false;
-  }
+  bool isEnabled() const { return AllowRecurse || !IsDisabled; }
+  void setAllowRecursive(bool Allow) { AllowRecurse = Allow; }
+  bool isAllowRecurse() const { return AllowRecurse; }
 
-  void DisableMacro() {
-assert(!IsDisabled && "Cannot disable an already-disabled macro!");
-IsDisabled = true;
-  }
+  void EnableMacro() { IsDisabled = false; }
 
+  void DisableMacro() { IsDisabled = true; }
   /// Determine whether this macro was used for a header guard.
   bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
 
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 9efe439bc5f2192..de121ce82fd1d7b 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2754,7 +2754,7 @@ class Preprocessor {
   void replayPreambleConditionalStack();
 
   // Macro handling.
-  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
+  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard, 
bool AllowRecurse);
   void HandleUndefDirective();
 
   // Conditional Inclusion.
diff --git a/clang/lib/Basic/IdentifierTable.cpp 
b/clang/lib/Basic/IdentifierTable.cpp
index afb30268f2973ce..4de3565c8c6d9a8 100644
--- a/clang/lib/Basic/IdentifierTable.cpp
+++ b/clang/lib/Basic/IdentifierTable.cpp
@@ -433,6 +433,8 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   unsigned Len = getLength();
   if (Len < 2) return tok::pp_not_keyword;
   const char *Name = getNameStart();
+  if (std::string_view(Name, Len) == "define2")
+return tok::pp_define2;
   switch (HASH(Len, Name[0], Name[2])) {
   default: return tok::pp_not_keyword;
   CASE( 2, 'i', '\0', if);
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index b7bd8d27dc976b1..d8ab76d6761553e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -743,7 +743,7 @@ void WhitespaceManager::alignConsecutiveMacros() {
 if (!Current || Current->isNot(tok::identifier))
   return false;
 
-if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
+if (!Current->Previous || !Current->Previous->isOneOf(tok::pp_define, 
tok::pp_define2))
   return false;
 
 // For a macro function, 0 spaces are required between the
diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index 39bb0f44eff25ba..9c3619c7c909304 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -50,7 +50,7 @@ static_assert(MacroInfoSizeChecker::AsExpected,
 MacroInfo::MacroInfo(SourceLocation DefLoc)
 : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
   IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
-  HasCommaPasting(false), IsDisabled(false), IsUsed(false),
+  HasCommaPasting(false), IsDisabled(false), AllowRecurse(false), 
IsUsed(false),
   IsAllowRedefinitionsW

[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits

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


[clang] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-11 Thread via cfe-commits

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


[PATCH] D148654: Modify BoundsSan to improve debuggability

2023-09-11 Thread Oskar Wirga via Phabricator via cfe-commits
oskarwirga added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:47
 #include "llvm/Transforms/Utils/SanitizerStats.h"
 
 #include 

vitalybuka wrote:
> this file and BoundsChecking.cpp belong to different patches
Just to be clear on terms here, these changes should be two different commits?



Comment at: clang/lib/CodeGen/CGExpr.cpp:56
+static llvm::cl::opt ClSanitizeDebugDeoptimization(
+"sanitizer-de-opt-traps", llvm::cl::Optional,
+llvm::cl::desc("Deoptimize traps for sanitizers"), llvm::cl::init(false));

vitalybuka wrote:
> this applies only to fsanitize=undefined, and does not apply to llvm level 
> sanitizers, like msan, asan
> we need better name: maybe ubsan-unique-traps
> 
> BTW do we want this as frontend flag?
Good point, as for being a frontend flag I don't feel strongly one way or the 
other, not sure how useful this is outside of my use-case. 



Comment at: clang/lib/CodeGen/CGExpr.cpp:3581
 
-  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
-  (CurCodeDecl && CurCodeDecl->hasAttr())) {
+  if (!ClSanitizeDebugDeoptimization &&
+  CGM.getCodeGenOpts().OptimizationLevel && TrapBB &&

vitalybuka wrote:
> so here we have two problems?
> 1. OptimizationLevel > 0 clang creates only one TrapBB per  check type
> 2. even if we create multiple bb here, branch-folder will merge them later
> 
Yeah exactly, despite my best efforts to come up with an existing way to fix 
this issue, because the ubsantrap intrinsic ends up being an instruction in 
MIR, it loses any function attributes we tack on now. 



Comment at: clang/lib/CodeGen/CGExpr.cpp:3597-3599
+llvm::ConstantInt::get(CGM.Int8Ty, ClSanitizeDebugDeoptimization
+   ? TrapBB->getParent()->size()
+   : CheckHandlerID));

vitalybuka wrote:
>   (TrapBB->getParent()->size() * 
> 0x1 + CheckHandlerID)
> 
Why `* 0x1` ?



Comment at: llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp:196
+  CallInst *TrapCall =
+  IRB.CreateCall(F, ConstantInt::get(IRB.getInt8Ty(), Fn->size()));
+  TrapCall->setDoesNotReturn();

vitalybuka wrote:
> why Fn->size(), to make a counter?
> 
> 
I was looking for a way to create a more or less unique value without creating 
a global iterator. It doesn't have to be this, I just thought that the fn->size 
would be increasing as checks go in so it would give a unique value per check. 



Comment at: llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp:202
+} else {
+  if (TrapBB && SingleTrapBB)
+return TrapBB;

vitalybuka wrote:
> can you please create a test where bounds-checking-single-trap=0 and 
> setCannotMerge produce invalid result.
Can do!



Comment at: llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp:189
   auto GetTrapBB = [&TrapBB](BuilderTy &IRB) {
-if (TrapBB && SingleTrapBB)
-  return TrapBB;
-
-Function *Fn = IRB.GetInsertBlock()->getParent();
-// FIXME: This debug location doesn't make a lot of sense in the
-// `SingleTrapBB` case.
-auto DebugLoc = IRB.getCurrentDebugLocation();
-IRBuilder<>::InsertPointGuard Guard(IRB);
-TrapBB = BasicBlock::Create(Fn->getContext(), "trap", Fn);
-IRB.SetInsertPoint(TrapBB);
-
-auto *F = Intrinsic::getDeclaration(Fn->getParent(), Intrinsic::trap);
-CallInst *TrapCall = IRB.CreateCall(F, {});
-TrapCall->setDoesNotReturn();
-TrapCall->setDoesNotThrow();
-TrapCall->setDebugLoc(DebugLoc);
-IRB.CreateUnreachable();
-
+if (DebugTrapBB) {
+  Function *Fn = IRB.GetInsertBlock()->getParent();

vitalybuka wrote:
> smeenai wrote:
> > oskarwirga wrote:
> > > nlopes wrote:
> > > > this seems like code duplication. This pass already has the single-trap 
> > > > flag to exactly control if you get a single trap BB or one per check 
> > > > for better debug info.
> > > Unfortunately, even with the single trap flag it gets optimized out in 
> > > later passes because the machine code emitted is the exact same 
> > I believe we end up tail merging the trap instructions. A previous 
> > iteration of this patch attempted to use the `nomerge` attribute to 
> > directly avoid the tail merging, but that only works for function calls, 
> > not for the `trap` instruction ultimately emitted here.
> branches of `if (DebugTrapBB) ` condition has a lot of code duplication, can 
> you try to imrove?
Yes, I will address all your comments in a new patch on github, thank you for 
your feedback I appreciate it :) 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148654/new/

https://reviews.llvm.org/D148654

_

[clang] 87461d6 - [clang][Interp] Implement __builtin_offsetof

2023-09-11 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-09-11T12:03:47+02:00
New Revision: 87461d669684668f02362f77807f313187667329

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

LOG: [clang][Interp] Implement __builtin_offsetof

Differential Revision: https://reviews.llvm.org/D156400

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/InterpBuiltin.cpp
clang/lib/AST/Interp/Opcodes.td
clang/test/AST/Interp/literals.cpp
clang/test/SemaCXX/class-layout.cpp
clang/test/SemaCXX/offsetof-0x.cpp
clang/test/SemaCXX/offsetof.cpp

Removed: 
clang/test/AST/Interp/class-layout.cpp



diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6a492c4c907cde0..4f89cbec76e7930 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1453,6 +1453,41 @@ bool ByteCodeExprGen::VisitSourceLocExpr(const 
SourceLocExpr *E) {
   return true;
 }
 
+template 
+bool ByteCodeExprGen::VisitOffsetOfExpr(const OffsetOfExpr *E) {
+  unsigned N = E->getNumComponents();
+  if (N == 0)
+return false;
+
+  for (unsigned I = 0; I != N; ++I) {
+const OffsetOfNode &Node = E->getComponent(I);
+if (Node.getKind() == OffsetOfNode::Array) {
+  const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
+  PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
+
+  if (DiscardResult) {
+if (!this->discard(ArrayIndexExpr))
+  return false;
+continue;
+  }
+
+  if (!this->visit(ArrayIndexExpr))
+return false;
+  // Cast to Sint64.
+  if (IndexT != PT_Sint64) {
+if (!this->emitCast(IndexT, PT_Sint64, E))
+  return false;
+  }
+}
+  }
+
+  if (DiscardResult)
+return true;
+
+  PrimType T = classifyPrim(E->getType());
+  return this->emitOffsetOf(T, E, E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 470d43a5d4c77e3..47a3f75f13459d0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -105,6 +105,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   bool VisitSourceLocExpr(const SourceLocExpr *E);
+  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 5006f72fe7237f5..d33c22ad60f9c02 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -181,6 +181,10 @@ bool Interpret(InterpState &S, APValue &Result);
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call);
 
+/// Interpret an offsetof operation.
+bool InterpretOffsetOf(InterpState &S, CodePtr OpPC, const OffsetOfExpr *E,
+   llvm::ArrayRef ArrayIndices, int64_t &Result);
+
 enum class ArithOp { Add, Sub };
 
 
//===--===//
@@ -1839,6 +1843,21 @@ inline bool InvalidCast(InterpState &S, CodePtr OpPC, 
CastKind Kind) {
   return false;
 }
 
+template ::T>
+inline bool OffsetOf(InterpState &S, CodePtr OpPC, const OffsetOfExpr *E) {
+  llvm::SmallVector ArrayIndices;
+  for (size_t I = 0; I != E->getNumExpressions(); ++I)
+ArrayIndices.emplace_back(S.Stk.pop());
+
+  int64_t Result;
+  if (!InterpretOffsetOf(S, OpPC, E, ArrayIndices, Result))
+return false;
+
+  S.Stk.push(T::from(Result));
+
+  return true;
+}
+
 
//===--===//
 // Read opcode arguments
 
//===--===//

diff  --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index c607368f3b65824..4536e335bf1a162 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -8,6 +8,7 @@
 #include "Boolean.h"
 #include "Interp.h"
 #include "PrimType.h"
+#include "clang/AST/RecordLayout.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/TargetInfo.h"
 
@@ -519,5 +520,79 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
   return false;
 }
 
+bool InterpretOffsetOf(InterpState &S, CodePtr OpPC, const OffsetOfExpr *E,
+   llvm::ArrayRef ArrayIndices,
+   int64_t &IntResult) {
+  CharUnits 

[PATCH] D156400: [clang][Interp] Implement __builtin_offsetof

2023-09-11 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG87461d669684: [clang][Interp] Implement __builtin_offsetof 
(authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D156400?vs=556339&id=556406#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156400/new/

https://reviews.llvm.org/D156400

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpBuiltin.cpp
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/class-layout.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/SemaCXX/class-layout.cpp
  clang/test/SemaCXX/offsetof-0x.cpp
  clang/test/SemaCXX/offsetof.cpp

Index: clang/test/SemaCXX/offsetof.cpp
===
--- clang/test/SemaCXX/offsetof.cpp
+++ clang/test/SemaCXX/offsetof.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10.0.0 -fsyntax-only -verify %s -Winvalid-offsetof -std=c++98
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10.0.0 -fsyntax-only -verify %s -Winvalid-offsetof -std=c++98 -fexperimental-new-constant-interpreter
 
 struct NonPOD {
   virtual void f();
Index: clang/test/SemaCXX/offsetof-0x.cpp
===
--- clang/test/SemaCXX/offsetof-0x.cpp
+++ clang/test/SemaCXX/offsetof-0x.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10.0.0 -fsyntax-only -std=c++11 -verify %s -Winvalid-offsetof
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10.0.0 -fsyntax-only -std=c++11 -verify %s -Winvalid-offsetof -fexperimental-new-constant-interpreter
 
 struct NonPOD {
   virtual void f();
Index: clang/test/SemaCXX/class-layout.cpp
===
--- clang/test/SemaCXX/class-layout.cpp
+++ clang/test/SemaCXX/class-layout.cpp
@@ -14,6 +14,25 @@
 // RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base
 // RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
 
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98 -Wno-inaccessible-base -Wno-c++11-extensions
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-apple-darwin%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-scei-ps4%s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-sie-ps5 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=6 -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=16 -DCLANG_ABI_COMPAT=16
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+
+
+
+
 // expected-no-di

[clang] 4b5fe9c - [clang][Interp] Check floating results for NaNs

2023-09-11 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-09-11T12:21:36+02:00
New Revision: 4b5fe9c42d94905a6f940e50958c56ed2d47a2cc

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

LOG: [clang][Interp] Check floating results for NaNs

Differential Revision: https://reviews.llvm.org/D156506

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/floats.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index de6ab4a145a1422..67fc11d9c9bf9c1 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -495,13 +495,25 @@ bool CheckPotentialReinterpretCast(InterpState &S, 
CodePtr OpPC,
   return false;
 }
 
-bool CheckFloatResult(InterpState &S, CodePtr OpPC, APFloat::opStatus Status) {
+bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result,
+  APFloat::opStatus Status) {
+  const SourceInfo &E = S.Current->getSource(OpPC);
+
+  // [expr.pre]p4:
+  //   If during the evaluation of an expression, the result is not
+  //   mathematically defined [...], the behavior is undefined.
+  // FIXME: C++ rules require us to not conform to IEEE 754 here.
+  if (Result.isNan()) {
+S.CCEDiag(E, diag::note_constexpr_float_arithmetic)
+<< /*NaN=*/true << S.Current->getRange(OpPC);
+return S.noteUndefinedBehavior();
+  }
+
   // In a constant context, assume that any dynamic rounding mode or FP
   // exception state matches the default floating-point environment.
   if (S.inConstantContext())
 return true;
 
-  const SourceInfo &E = S.Current->getSource(OpPC);
   FPOptions FPO = E.asExpr()->getFPFeaturesInEffect(S.Ctx.getLangOpts());
 
   if ((Status & APFloat::opInexact) &&

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index d33c22ad60f9c02..b109f2bda17bfb1 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -172,7 +172,8 @@ bool CheckDivRem(InterpState &S, CodePtr OpPC, const T 
&LHS, const T &RHS) {
 
 /// Checks if the result of a floating-point operation is valid
 /// in the current context.
-bool CheckFloatResult(InterpState &S, CodePtr OpPC, APFloat::opStatus Status);
+bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result,
+  APFloat::opStatus Status);
 
 /// Interpreter entry point.
 bool Interpret(InterpState &S, APValue &Result);
@@ -304,7 +305,7 @@ inline bool Addf(InterpState &S, CodePtr OpPC, 
llvm::RoundingMode RM) {
   Floating Result;
   auto Status = Floating::add(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -322,7 +323,7 @@ inline bool Subf(InterpState &S, CodePtr OpPC, 
llvm::RoundingMode RM) {
   Floating Result;
   auto Status = Floating::sub(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -340,7 +341,7 @@ inline bool Mulf(InterpState &S, CodePtr OpPC, 
llvm::RoundingMode RM) {
   Floating Result;
   auto Status = Floating::mul(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 /// 1) Pops the RHS from the stack.
 /// 2) Pops the LHS from the stack.
@@ -443,7 +444,7 @@ inline bool Divf(InterpState &S, CodePtr OpPC, 
llvm::RoundingMode RM) {
   Floating Result;
   auto Status = Floating::div(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 
//===--===//
@@ -622,7 +623,7 @@ bool IncDecFloatHelper(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 
   Ptr.deref() = Result;
 
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 inline bool Incf(InterpState &S, CodePtr OpPC, llvm::RoundingMode RM) {
@@ -1525,7 +1526,7 @@ bool CastIntegralFloating(InterpState &S, CodePtr OpPC,
   auto Status = Floating::fromIntegral(FromAP, *Sem, RM, Result);
   S.Stk.push(Result);
 
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -1550,7 +1551,7 @@ bool CastFloatingIntegral(InterpState &S, CodePtr OpPC) {
 }
 
 S.Stk.push(T(Result));
-return CheckFloatResult(S, OpPC, Status);
+return CheckFloatResult(S, OpPC, F, Status);
   }
 }
 

diff  --git a/clang/test/AST/Interp/floats.cpp 
b/clang/test/AST/Interp/floats.cpp
index a3b058e1eafb399..e17167f5bf6dbbf 100644
--- a/clang/test/AST/Interp/floats.cp

[PATCH] D156506: [clang][Interp] Check floating results for NaNs

2023-09-11 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4b5fe9c42d94: [clang][Interp] Check floating results for 
NaNs (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D156506?vs=545023&id=556407#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156506/new/

https://reviews.llvm.org/D156506

Files:
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/test/AST/Interp/floats.cpp

Index: clang/test/AST/Interp/floats.cpp
===
--- clang/test/AST/Interp/floats.cpp
+++ clang/test/AST/Interp/floats.cpp
@@ -202,3 +202,18 @@
   static_assert(!(inf < nan), "");
   static_assert(!(inf > nan), "");
 }
+
+namespace nan {
+  constexpr double nan = __builtin_nan("");
+  static_assert(nan);
+
+  constexpr double D1 = 1 + nan; // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{produces a NaN}} \
+ // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{produces a NaN}}
+
+  constexpr double D2 = __builtin_inf() / __builtin_inf(); // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{produces a NaN}} \
+   // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{produces a NaN}}
+}
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -172,7 +172,8 @@
 
 /// Checks if the result of a floating-point operation is valid
 /// in the current context.
-bool CheckFloatResult(InterpState &S, CodePtr OpPC, APFloat::opStatus Status);
+bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result,
+  APFloat::opStatus Status);
 
 /// Interpreter entry point.
 bool Interpret(InterpState &S, APValue &Result);
@@ -304,7 +305,7 @@
   Floating Result;
   auto Status = Floating::add(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -322,7 +323,7 @@
   Floating Result;
   auto Status = Floating::sub(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -340,7 +341,7 @@
   Floating Result;
   auto Status = Floating::mul(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 /// 1) Pops the RHS from the stack.
 /// 2) Pops the LHS from the stack.
@@ -443,7 +444,7 @@
   Floating Result;
   auto Status = Floating::div(LHS, RHS, RM, &Result);
   S.Stk.push(Result);
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 //===--===//
@@ -622,7 +623,7 @@
 
   Ptr.deref() = Result;
 
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 inline bool Incf(InterpState &S, CodePtr OpPC, llvm::RoundingMode RM) {
@@ -1525,7 +1526,7 @@
   auto Status = Floating::fromIntegral(FromAP, *Sem, RM, Result);
   S.Stk.push(Result);
 
-  return CheckFloatResult(S, OpPC, Status);
+  return CheckFloatResult(S, OpPC, Result, Status);
 }
 
 template ::T>
@@ -1550,7 +1551,7 @@
 }
 
 S.Stk.push(T(Result));
-return CheckFloatResult(S, OpPC, Status);
+return CheckFloatResult(S, OpPC, F, Status);
   }
 }
 
Index: clang/lib/AST/Interp/Interp.cpp
===
--- clang/lib/AST/Interp/Interp.cpp
+++ clang/lib/AST/Interp/Interp.cpp
@@ -495,13 +495,25 @@
   return false;
 }
 
-bool CheckFloatResult(InterpState &S, CodePtr OpPC, APFloat::opStatus Status) {
+bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result,
+  APFloat::opStatus Status) {
+  const SourceInfo &E = S.Current->getSource(OpPC);
+
+  // [expr.pre]p4:
+  //   If during the evaluation of an expression, the result is not
+  //   mathematically defined [...], the behavior is undefined.
+  // FIXME: C++ rules require us to not conform to IEEE 754 here.
+  if (Result.isNan()) {
+S.CCEDiag(E, diag::note_constexpr_float_arithmetic)
+<< /*NaN=*/true << S.Current->getRange(OpPC);
+return S.noteUndefinedBehavior();
+  }
+
   // In a constant context, assume that any dynamic rounding mode or FP
   // exception state matches the default fl

[clang] Extension: allow recursive macros (PR #65851)

2023-09-11 Thread via cfe-commits

https://github.com/kelbon updated 
https://github.com/llvm/llvm-project/pull/65851:

>From 2f807b312baef8c6038c2452b84232acb6d6d2c2 Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Sat, 9 Sep 2023 17:51:15 +0400
Subject: [PATCH 1/6] add define2 pp directive

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Lex/MacroInfo.h  | 19 +--
 clang/include/clang/Lex/Preprocessor.h   |  2 +-
 clang/lib/Basic/IdentifierTable.cpp  |  2 ++
 clang/lib/Format/WhitespaceManager.cpp   |  2 +-
 clang/lib/Lex/MacroInfo.cpp  |  3 ++-
 clang/lib/Lex/PPDirectives.cpp   | 16 +++-
 7 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 45ebc200b168986..f059d809823ab42 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -115,6 +115,7 @@ PPKEYWORD(__include_macros)
 
 // C99 6.10.3 - Macro Replacement.
 PPKEYWORD(define)
+PPKEYWORD(define2)
 PPKEYWORD(undef)
 
 // C99 6.10.4 - Line Control.
diff --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 00c1c3866bbd9ca..4f0c8e987610e50 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -102,6 +102,10 @@ class MacroInfo {
   /// like \#define A A.
   bool IsDisabled : 1;
 
+  // True if 'define2' used,
+  // ignores 'IsDisabled' and enables expansion anyway
+  bool AllowRecurse : 1;
+
   /// True if this macro is either defined in the main file and has
   /// been used, or if it is not defined in the main file.
   ///
@@ -278,18 +282,13 @@ class MacroInfo {
   /// Return true if this macro is enabled.
   ///
   /// In other words, that we are not currently in an expansion of this macro.
-  bool isEnabled() const { return !IsDisabled; }
-
-  void EnableMacro() {
-assert(IsDisabled && "Cannot enable an already-enabled macro!");
-IsDisabled = false;
-  }
+  bool isEnabled() const { return AllowRecurse || !IsDisabled; }
+  void setAllowRecursive(bool Allow) { AllowRecurse = Allow; }
+  bool isAllowRecurse() const { return AllowRecurse; }
 
-  void DisableMacro() {
-assert(!IsDisabled && "Cannot disable an already-disabled macro!");
-IsDisabled = true;
-  }
+  void EnableMacro() { IsDisabled = false; }
 
+  void DisableMacro() { IsDisabled = true; }
   /// Determine whether this macro was used for a header guard.
   bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
 
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 9efe439bc5f2192..de121ce82fd1d7b 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2754,7 +2754,7 @@ class Preprocessor {
   void replayPreambleConditionalStack();
 
   // Macro handling.
-  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard);
+  void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterHeaderGuard, 
bool AllowRecurse);
   void HandleUndefDirective();
 
   // Conditional Inclusion.
diff --git a/clang/lib/Basic/IdentifierTable.cpp 
b/clang/lib/Basic/IdentifierTable.cpp
index afb30268f2973ce..4de3565c8c6d9a8 100644
--- a/clang/lib/Basic/IdentifierTable.cpp
+++ b/clang/lib/Basic/IdentifierTable.cpp
@@ -433,6 +433,8 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   unsigned Len = getLength();
   if (Len < 2) return tok::pp_not_keyword;
   const char *Name = getNameStart();
+  if (std::string_view(Name, Len) == "define2")
+return tok::pp_define2;
   switch (HASH(Len, Name[0], Name[2])) {
   default: return tok::pp_not_keyword;
   CASE( 2, 'i', '\0', if);
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index b7bd8d27dc976b1..d8ab76d6761553e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -743,7 +743,7 @@ void WhitespaceManager::alignConsecutiveMacros() {
 if (!Current || Current->isNot(tok::identifier))
   return false;
 
-if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
+if (!Current->Previous || !Current->Previous->isOneOf(tok::pp_define, 
tok::pp_define2))
   return false;
 
 // For a macro function, 0 spaces are required between the
diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index 39bb0f44eff25ba..9c3619c7c909304 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -50,7 +50,7 @@ static_assert(MacroInfoSizeChecker::AsExpected,
 MacroInfo::MacroInfo(SourceLocation DefLoc)
 : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
   IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
-  HasCommaPasting(false), IsDisabled(false), IsUsed(false),
+  HasCommaPasting(false), IsDisabled(false), AllowRecurse(false), 
IsUsed(false),
   IsAllowRedefinitionsW

[PATCH] D154581: [clang][Interp] Track existing InitMaps in InterpState

2023-09-11 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Ping


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154581/new/

https://reviews.llvm.org/D154581

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


[clang-tools-extra] [clang-tidy] Avoid checking magic numbers if _BitInt (PR #65888)

2023-09-11 Thread via cfe-commits

DonatNagyE wrote:

LGTM as a temporary measure. Perhaps add a TODO note which asks for a more 
through solution; but you can also merge this as it is now.

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


[clang] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in riscv_vector.td (PR #65944)

2023-09-11 Thread Ying Chen via cfe-commits

https://github.com/punkyc created 
https://github.com/llvm/llvm-project/pull/65944:

Fix index typos, s.t. indexes in comments be same with riscv-v-spec doc. 

>From 01a0763aa8c624834c5f6a98df22e75f3f5ae96b Mon Sep 17 00:00:00 2001
From: Ying Chen 
Date: Mon, 11 Sep 2023 18:36:22 +0800
Subject: [PATCH] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in 
 riscv_vector.td

---
 clang/include/clang/Basic/riscv_vector.td | 168 +++---
 1 file changed, 84 insertions(+), 84 deletions(-)

diff --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index 9b941e1cca85014..6f9f4ce0dd1916b 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -1601,8 +1601,8 @@ defm : RVVIndexedSegStoreTuple<"vsuxseg">;
 defm : RVVIndexedSegStoreTuple<"vsoxseg">;
 }
 
-// 12. Vector Integer Arithmetic Instructions
-// 12.1. Vector Single-Width Integer Add and Subtract
+// 11. Vector Integer Arithmetic Instructions
+// 11.1. Vector Single-Width Integer Add and Subtract
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vadd : RVVIntBinBuiltinSet;
 defm vsub : RVVIntBinBuiltinSet;
@@ -1612,7 +1612,7 @@ defm vrsub : RVVOutOp1BuiltinSet<"vrsub", "csil",
 }
 defm vneg_v : RVVPseudoUnaryBuiltin<"vrsub", "csil">;
 
-// 12.2. Vector Widening Integer Add/Subtract
+// 11.2. Vector Widening Integer Add/Subtract
 // Widening unsigned integer add/subtract, 2*SEW = SEW +/- SEW
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vwaddu : RVVUnsignedWidenBinBuiltinSet;
@@ -1632,7 +1632,7 @@ defm vwcvtu_x_x_v : RVVPseudoVWCVTBuiltin<"vwaddu", 
"vwcvtu_x", "csi",
 defm vwcvt_x_x_v : RVVPseudoVWCVTBuiltin<"vwadd", "vwcvt_x", "csi",
  [["w", "wv"]]>;
 
-// 12.3. Vector Integer Extension
+// 11.3. Vector Integer Extension
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 let Log2LMUL = [-3, -2, -1, 0, 1, 2] in {
   def vsext_vf2 : RVVIntExt<"vsext", "w", "wv", "csi">;
@@ -1648,7 +1648,7 @@ let Log2LMUL = [-3, -2, -1, 0] in {
 }
 }
 
-// 12.4. Vector Integer Add-with-Carry / Subtract-with-Borrow Instructions
+// 11.4. Vector Integer Add-with-Carry / Subtract-with-Borrow Instructions
 let HasMasked = false, MaskedPolicyScheme = NonePolicy in {
   let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vadc : RVVCarryinBuiltinSet;
@@ -1660,7 +1660,7 @@ let HasMasked = false, MaskedPolicyScheme = NonePolicy in 
{
   defm vmsbc : RVVIntMaskOutBuiltinSet;
 }
 
-// 12.5. Vector Bitwise Logical Instructions
+// 11.5. Vector Bitwise Logical Instructions
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vand : RVVIntBinBuiltinSet;
 defm vxor : RVVIntBinBuiltinSet;
@@ -1668,13 +1668,13 @@ defm vor : RVVIntBinBuiltinSet;
 }
 defm vnot_v : RVVPseudoVNotBuiltin<"vxor", "csil">;
 
-// 12.6. Vector Single-Width Bit Shift Instructions
+// 11.6. Vector Single-Width Bit Shift Instructions
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vsll : RVVShiftBuiltinSet;
 defm vsrl : RVVUnsignedShiftBuiltinSet;
 defm vsra : RVVSignedShiftBuiltinSet;
 
-// 12.7. Vector Narrowing Integer Right Shift Instructions
+// 11.7. Vector Narrowing Integer Right Shift Instructions
 defm vnsrl : RVVUnsignedNShiftBuiltinSet;
 defm vnsra : RVVSignedNShiftBuiltinSet;
 }
@@ -1682,7 +1682,7 @@ defm vncvt_x_x_w : RVVPseudoVNCVTBuiltin<"vnsrl", 
"vncvt_x", "csi",
  [["v", "vw"],
   ["Uv", "UvUw"]]>;
 
-// 12.8. Vector Integer Comparison Instructions
+// 11.8. Vector Integer Comparison Instructions
 let MaskedPolicyScheme = HasPassthruOperand,
 HasTailPolicy = false in {
 defm vmseq : RVVIntMaskOutBuiltinSet;
@@ -1697,14 +1697,14 @@ defm vmsgeu : RVVUnsignedMaskOutBuiltinSet;
 defm vmsge : RVVSignedMaskOutBuiltinSet;
 }
 
-// 12.9. Vector Integer Min/Max Instructions
+// 11.9. Vector Integer Min/Max Instructions
 let UnMaskedPolicyScheme = HasPassthruOperand in {
 defm vminu : RVVUnsignedBinBuiltinSet;
 defm vmin : RVVSignedBinBuiltinSet;
 defm vmaxu : RVVUnsignedBinBuiltinSet;
 defm vmax : RVVSignedBinBuiltinSet;
 
-// 12.10. Vector Single-Width Integer Multiply Instructions
+// 11.10. Vector Single-Width Integer Multiply Instructions
 defm vmul : RVVIntBinBuiltinSet;
 defm vmulh : RVVSignedBinBuiltinSet;
 defm vmulhu : RVVUnsignedBinBuiltinSet;
@@ -1712,14 +1712,14 @@ defm vmulhsu : RVVOutOp1BuiltinSet<"vmulhsu", "csil",
[["vv", "v", "vvUv"],
 ["vx", "v", "vvUe"]]>;
 
-// 12.11. Vector Integer Divide Instructions
+// 11.11. Vector Integer Divide Instructions
 defm vdivu : RVVUnsignedBinBuiltinSet;
 defm vdiv : RVVSignedBinBuiltinSet;
 defm vremu : RVVUnsignedBinBuiltinSet;
 defm vrem : RVVSignedBinBuiltinSet;
 }
 
-// 12.12. Vector Widening Integer Multiply Instructions
+// 11.12. Vector Widening Integer Multiply Instructions
 let Log2LMUL = [-3, -2, -1, 0

[clang] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in riscv_vector.td (PR #65944)

2023-09-11 Thread Ying Chen via cfe-commits

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


[clang] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in riscv_vector.td (PR #65944)

2023-09-11 Thread via cfe-commits

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


[clang] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in riscv_vector.td (PR #65944)

2023-09-11 Thread via cfe-commits

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


[clang] [NFC][Clang][RISCV] Fix index typos of riscv-v-spec doc in riscv_vector.td (PR #65944)

2023-09-11 Thread via cfe-commits

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


[clang] [AMDGPU] Remove Code Object V2 (PR #65715)

2023-09-11 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

> Is this dropping read support?

Yes, it's dropping everything

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


[clang] [AMDGPU] Remove Code Object V2 (PR #65715)

2023-09-11 Thread Pierre van Houtryve via cfe-commits

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


[PATCH] D140538: [Clang][CodeGen] Use poison instead of undef for dummy values in CGExpr [NFC]

2023-09-11 Thread Manuel Brito via Phabricator via cfe-commits
ManuelJBrito updated this revision to Diff 556416.
ManuelJBrito removed a reviewer: libc++abi.
ManuelJBrito added a comment.
This revision is now accepted and ready to land.

Remove changes to demangle test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D140538/new/

https://reviews.llvm.org/D140538

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprComplex.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3774,8 +3774,8 @@
   /// Create a check that a scalar RValue is non-null.
   llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
 
-  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
-  RValue GetUndefRValue(QualType Ty);
+  /// GetPoisonRValue - Get an appropriate 'poison' rvalue for the given type.
+  RValue GetPoisonRValue(QualType Ty);
 
   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
   /// and issue an ErrorUnsupported style diagnostic (using the
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -1630,7 +1630,7 @@
   CGF.ErrorUnsupported(E, "scalar expression");
   if (E->getType()->isVoidType())
 return nullptr;
-  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
+  return llvm::PoisonValue::get(CGF.ConvertType(E->getType()));
 }
 
 Value *
@@ -4958,7 +4958,7 @@
   // If EmitVAArg fails, emit an error.
   if (!ArgPtr.isValid()) {
 CGF.ErrorUnsupported(VE, "va_arg expression");
-return llvm::UndefValue::get(ArgTy);
+return llvm::PoisonValue::get(ArgTy);
   }
 
   // FIXME Volatility.
Index: clang/lib/CodeGen/CGExprComplex.cpp
===
--- clang/lib/CodeGen/CGExprComplex.cpp
+++ clang/lib/CodeGen/CGExprComplex.cpp
@@ -415,7 +415,7 @@
   CGF.ErrorUnsupported(E, "complex expression");
   llvm::Type *EltTy =
 CGF.ConvertType(getComplexType(E->getType())->getElementType());
-  llvm::Value *U = llvm::UndefValue::get(EltTy);
+  llvm::Value *U = llvm::PoisonValue::get(EltTy);
   return ComplexPairTy(U, U);
 }
 
@@ -1275,7 +1275,7 @@
 CGF.ErrorUnsupported(E, "complex va_arg expression");
 llvm::Type *EltTy =
   CGF.ConvertType(E->getType()->castAs()->getElementType());
-llvm::Value *U = llvm::UndefValue::get(EltTy);
+llvm::Value *U = llvm::PoisonValue::get(EltTy);
 return ComplexPairTy(U, U);
   }
 
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -1176,7 +1176,7 @@
   return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
 }
 
-RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
+RValue CodeGenFunction::GetPoisonRValue(QualType Ty) {
   if (Ty->isVoidType())
 return RValue::get(nullptr);
 
@@ -1184,7 +1184,7 @@
   case TEK_Complex: {
 llvm::Type *EltTy =
   ConvertType(Ty->castAs()->getElementType());
-llvm::Value *U = llvm::UndefValue::get(EltTy);
+llvm::Value *U = llvm::PoisonValue::get(EltTy);
 return RValue::getComplex(std::make_pair(U, U));
   }
 
@@ -1197,7 +1197,7 @@
   }
 
   case TEK_Scalar:
-return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
+return RValue::get(llvm::PoisonValue::get(ConvertType(Ty)));
   }
   llvm_unreachable("bad evaluation kind");
 }
@@ -1205,7 +1205,7 @@
 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
   const char *Name) {
   ErrorUnsupported(E, Name);
-  return GetUndefRValue(E->getType());
+  return GetPoisonRValue(E->getType());
 }
 
 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
@@ -1214,7 +1214,7 @@
   llvm::Type *ElTy = ConvertType(E->getType());
   llvm::Type *Ty = llvm::PointerType::getUnqual(ElTy);
   return MakeAddrLValue(
-  Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
+  Address(llvm::PoisonValue::get(Ty), ElTy, CharUnits::One()), E->getType());
 }
 
 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -5712,7 +5712,7 @@
 EnsureInsertPoint();
 
 // Return a reasonable RValue.
-return GetUndefRValue(RetTy);
+return GetPoisonRValue(RetTy);
   }
 
   // If this is a musttail call, return immediately. We do not branch to the
@@ -5730,7 +5730,7 @@
   Builder.CreateRet(CI);
 Builder.ClearInsertionPoint();
 EnsureInsertPo

[clang] [include-mapping] Python fixes (PR #65401)

2023-09-11 Thread Haojian Wu via cfe-commits

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


[clang] [include-mapping] Python fixes (PR #65401)

2023-09-11 Thread Haojian Wu via cfe-commits

https://github.com/hokein commented:

thanks, the change looks reasonable.

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


[clang] [include-mapping] Python fixes (PR #65401)

2023-09-11 Thread Haojian Wu via cfe-commits




hokein wrote:

can you also update this file to use `python3`?

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


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-11 Thread via cfe-commits

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


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-11 Thread via cfe-commits


@@ -598,6 +598,12 @@ SVal SValBuilder::evalIntegralCast(ProgramStateRef state, 
SVal val,
   APSIntType ToType(getContext().getTypeSize(castTy),
 castTy->isUnsignedIntegerType());
   llvm::APSInt ToTypeMax = ToType.getMaxValue();
+  // With the introduction of _BitInt(), integral types can be
+  // > 64 bits. So check for this and skip the size checks
+  // falling back to making a non loc return type.
+  if (ToTypeMax.getSignificantBits() > 64) {
+return makeNonLoc(se, originalTy, castTy);
+  }
   NonLoc ToTypeMaxVal =
   makeIntVal(ToTypeMax.isUnsigned() ? ToTypeMax.getZExtValue()

DonatNagyE wrote:

The root cause of this issue is an unnecessary back-and-forth conversion. The 
`nonloc::ConcreteInt` that we construct here will use an `APSInt` to represent 
its value, so there is no real need to convert our `APSInt` to an `uint64_t` 
which will be used to construct a new `APSInt`.

Instead of adding a special case early return, simply switch to using the method
```c++
nonloc::ConcreteInt makeIntVal(const llvm::APSInt& integer);
```
which significantly simplifies this part of the code and eliminates the crash 
on huge values.

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


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-11 Thread via cfe-commits

https://github.com/DonatNagyE requested changes to this pull request.

I agree that it would be useful to systematically check the use of the `APSInt 
-> uint64_t` conversions, because it's likely that there are other ones that 
can lead to crashes.

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


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-11 Thread via cfe-commits


@@ -0,0 +1,11 @@
+ // RUN: %clang_analyze_cc1 -analyzer-checker=core \
+ // RUN:   -analyzer-checker=debug.ExprInspection \
+ // RUN:   -verify %s
+
+// Don't crash when using _BitInt()
+// expected-no-diagnostics
+_BitInt(256) a;
+_BitInt(129) b;
+void c() {
+  b = a;
+}

DonatNagyE wrote:

Do I understand it correctly that the old code was also crashing on `__int128`? 
(No action needed, I'm just curious.)

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


[clang] Replace llvm.memcpy et al's i1 isVolatile with i8 VolFlags (PR #65748)

2023-09-11 Thread via cfe-commits

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


  1   2   3   4   5   6   7   >