[PATCH] D151051: [clang-tidy] Optimize misc-confusable-identifiers

2023-05-26 Thread serge via Phabricator via cfe-commits
serge-sans-paille accepted this revision.
serge-sans-paille added a comment.
This revision is now accepted and ready to land.

Memoizing the calls to getPrimaryContext()... LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151051

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


[PATCH] D148489: [clangd] Implement configs to stop clangd produce a certain semantic tokens

2023-05-26 Thread Nathan Ridge via Phabricator via cfe-commits
nridge accepted this revision.
nridge added a comment.

Thanks, LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148489

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


[clang] 52d3255 - [Clang][RISCV] Add description for test case . NFC

2023-05-26 Thread via cfe-commits

Author: eopXD
Date: 2023-05-26T00:22:48-07:00
New Revision: 52d3255704187c3e60de8657d6ece7ab73e07b68

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

LOG: [Clang][RISCV] Add description for test case . NFC

Added: 


Modified: 
clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-tuple-type.c

Removed: 




diff  --git 
a/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-tuple-type.c 
b/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-tuple-type.c
index bd2b2a98ebd14..f4235795a8622 100644
--- a/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-tuple-type.c
+++ b/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-tuple-type.c
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 -triple riscv64 -target-feature +zve32x -disable-O0-optnone 
\
 // RUN:   -emit-llvm %s -o - | opt -S -passes=mem2reg | FileCheck %s 
--check-prefix=AFTER_MEM2REG
 
+// This test case tests the lowering of RVV tuple types into LLVM IR.
 
 #include 
 



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


[clang-tools-extra] 6feaa54 - [clangd] Implement configs to stop clangd produce a certain semantic tokens

2023-05-26 Thread Nathan Ridge via cfe-commits

Author: Qingyuan Zheng
Date: 2023-05-26T03:25:35-04:00
New Revision: 6feaa5416bf63f9609478d4458485c7306506e26

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

LOG: [clangd] Implement configs to stop clangd produce a certain semantic tokens

This patch introduces the following configurations to .clangd:

```
SemanticTokens:
DisabledKinds: [ ... ]
DisabledModifiers: [ ... ]
```

Based on the config, clangd would stop producing a certain type of semantic 
tokens from the source file.

Fixes https://github.com/clangd/clangd/discussions/1598

Reviewed By: nridge

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

Added: 


Modified: 
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/ConfigFragment.h
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/SemanticHighlighting.h
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 15b4b7ef06fef..4c6fad25384a8 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -150,6 +150,13 @@ struct Config {
 // Limit the length of type names in inlay hints. (0 means no limit)
 uint32_t TypeNameLimit = 32;
   } InlayHints;
+
+  struct {
+/// Controls highlighting kinds that are disabled.
+std::vector DisabledKinds;
+/// Controls highlighting modifiers that are disabled.
+std::vector DisabledModifiers;
+  } SemanticTokens;
 };
 
 } // namespace clangd

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index 9bd067666f5f8..832dab54febaf 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -196,6 +196,7 @@ struct FragmentCompiler {
 compile(std::move(F.Completion));
 compile(std::move(F.Hover));
 compile(std::move(F.InlayHints));
+compile(std::move(F.SemanticTokens));
 compile(std::move(F.Style));
   }
 
@@ -618,6 +619,37 @@ struct FragmentCompiler {
   });
   }
 
+  void compile(Fragment::SemanticTokensBlock &&F) {
+if (!F.DisabledKinds.empty()) {
+  std::vector DisabledKinds;
+  for (auto &Kind : F.DisabledKinds)
+DisabledKinds.push_back(std::move(*Kind));
+
+  Out.Apply.push_back(
+  [DisabledKinds(std::move(DisabledKinds))](const Params &, Config &C) 
{
+for (auto &Kind : DisabledKinds) {
+  auto It = llvm::find(C.SemanticTokens.DisabledKinds, Kind);
+  if (It == C.SemanticTokens.DisabledKinds.end())
+C.SemanticTokens.DisabledKinds.push_back(std::move(Kind));
+}
+  });
+}
+if (!F.DisabledModifiers.empty()) {
+  std::vector DisabledModifiers;
+  for (auto &Kind : F.DisabledModifiers)
+DisabledModifiers.push_back(std::move(*Kind));
+
+  Out.Apply.push_back([DisabledModifiers(std::move(DisabledModifiers))](
+  const Params &, Config &C) {
+for (auto &Kind : DisabledModifiers) {
+  auto It = llvm::find(C.SemanticTokens.DisabledModifiers, Kind);
+  if (It == C.SemanticTokens.DisabledModifiers.end())
+C.SemanticTokens.DisabledModifiers.push_back(std::move(Kind));
+}
+  });
+}
+  }
+
   constexpr static llvm::SourceMgr::DiagKind Error = llvm::SourceMgr::DK_Error;
   constexpr static llvm::SourceMgr::DiagKind Warning =
   llvm::SourceMgr::DK_Warning;

diff  --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index c1bac1019641d..fe2f68f5c45bc 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -235,7 +235,6 @@ struct Fragment {
 /// - std::nullopt
 std::optional> UnusedIncludes;
 
-
 /// Enable emitting diagnostics using stale preambles.
 std::optional> AllowStalePreamble;
 
@@ -326,6 +325,15 @@ struct Fragment {
 std::optional> TypeNameLimit;
   };
   InlayHintsBlock InlayHints;
+
+  /// Configures semantic tokens that are produced by clangd.
+  struct SemanticTokensBlock {
+/// Disables clangd to produce semantic tokens for the given kinds.
+std::vector> DisabledKinds;
+/// Disables clangd to assign semantic tokens with the given modifiers.
+std::vector> DisabledModifiers;
+  };
+  SemanticTokensBlock SemanticTokens;
 };
 
 } // namespace config

diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index d16860a1ccf48..4d91062d890fe 100644
--- a/clang-to

[PATCH] D148489: [clangd] Implement configs to stop clangd produce a certain semantic tokens

2023-05-26 Thread Nathan Ridge via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6feaa5416bf6: [clangd] Implement configs to stop clangd 
produce a certain semantic tokens (authored by daiyousei-qz, committed by 
nridge).

Changed prior to commit:
  https://reviews.llvm.org/D148489?vs=525448&id=525967#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148489

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "Annotations.h"
+#include "Config.h"
 #include "Protocol.h"
 #include "SemanticHighlighting.h"
 #include "SourceCode.h"
@@ -1260,6 +1261,17 @@
   EXPECT_EQ(Toks[3].deltaStart, 2u);
   EXPECT_EQ(Toks[3].length, 3u);
 }
+
+TEST(SemanticHighlighting, WithHighlightingFilter) {
+  llvm::StringRef AnnotatedCode = R"cpp(
+int *$Variable[[x]] = new int;
+)cpp";
+  Config Cfg;
+  Cfg.SemanticTokens.DisabledKinds = {"Operator"};
+  Cfg.SemanticTokens.DisabledModifiers = {"Declaration", "Definition"};
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+  checkHighlightings(AnnotatedCode, {}, ~ScopeModifierMask);
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -246,6 +246,23 @@
   EXPECT_EQ(Results[0].InlayHints.DeducedTypes, std::nullopt);
 }
 
+TEST(ParseYAML, SemanticTokens) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+SemanticTokens:
+  DisabledKinds: [ Operator, InactiveCode]
+  DisabledModifiers: Readonly
+  )yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].SemanticTokens.DisabledKinds,
+  ElementsAre(val("Operator"), val("InactiveCode")));
+  EXPECT_THAT(Results[0].SemanticTokens.DisabledModifiers,
+  ElementsAre(val("Readonly")));
+}
+
 TEST(ParseYAML, IncludesIgnoreHeader) {
   CapturedDiags Diags;
   Annotations YAML(R"yaml(
Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -61,6 +61,8 @@
 };
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingKind K);
+std::optional
+highlightingKindFromString(llvm::StringRef Name);
 
 enum class HighlightingModifier {
   Declaration,
@@ -88,6 +90,8 @@
 static_assert(static_cast(HighlightingModifier::LastModifier) < 32,
   "Increase width of modifiers bitfield!");
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingModifier K);
+std::optional
+highlightingModifierFromString(llvm::StringRef Name);
 
 // Contains all information needed for the highlighting a token.
 struct HighlightingToken {
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "SemanticHighlighting.h"
+#include "Config.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
@@ -354,13 +355,57 @@
   return Winner;
 }
 
+/// Filter to remove particular kinds of highlighting tokens and modifiers from
+/// the output.
+class HighlightingFilter {
+public:
+  HighlightingFilter() {
+for (auto &Active : ActiveKindLookup)
+  Active = true;
+
+ActiveModifiersMask = ~0;
+  }
+
+  void disableKind(HighlightingKind Kind) {
+ActiveKindLookup[static_cast(Kind)] = false;
+  }
+
+  void disableModifier(HighlightingModifier Modifier) {
+ActiveModifiersMask &= ~(1 << static_cast(Modifier));
+  }
+
+  bool isHighlightKindActive(HighlightingKind Kind) const {
+return ActiveKindLookup[static_cast(Kind)];
+  }
+
+  uint32_t maskModifiers(uint32_t Modifiers) const {
+return Modifiers & ActiveM

[PATCH] D148489: [clangd] Implement configs to stop clangd produce a certain semantic tokens

2023-05-26 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

I went ahead and merged this.

When you get a chance, could you update 
https://github.com/llvm/clangd-www/pull/85 as well so we can merge that too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148489

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


[PATCH] D147894: [clang-format][doc] SortIncludes documentation: remove contradiction in its description

2023-05-26 Thread Mike Matthews via Phabricator via cfe-commits
michael-g-matthews added a comment.

If this is considered fully approved, would someone with commit access be able 
to commit this on my behalf? This is my first contribution so I do not have 
access. My name and email are Mike Matthews and michael.g.matthe...@gmail.com. 
Thank you!


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

https://reviews.llvm.org/D147894

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


[PATCH] D151190: [clangd] Do not end inactiveRegions range at position 0 of line

2023-05-26 Thread Nathan Ridge via Phabricator via cfe-commits
nridge planned changes to this revision.
nridge added inline comments.



Comment at: clang-tools-extra/clangd/unittests/ClangdTests.cpp:1343
 #undef CMDMACRO
 $inactive3[[#ifdef CMDMACRO
   int inactiveInt2;

daiyousei-qz wrote:
> hokein wrote:
> > While this patch is an improvement, I wonder we should move it further.
> > 
> > Has been thinking about it more, we seem to have some inconsistent behavior 
> > on highlighting the `#if`, `#else`, `#endif` lines:
> > 
> > - in `$inactive1` case, the `#endif` is marked as inactive (IMO, the 
> > highlighting in the editor is confusing, it looks like we're missing a 
> > match `endif`, thus I prefer to mark it as active to correspond to the 
> > active `#if` branch);
> > - in `$inactive3` case, the line `#elif PREAMBLEMACRO > 0` is marked as 
> > inactive, this is inconsistent with `$inactive1` case;
> > 
> > I think it would be nice to have a consistent model. One approach is to 
> > always consider `#if`, `#elif`, `#endif`, `#endif` lines active (in the 
> > implementation side, this would mean we always use the line range 
> > [skipp_range.start.line+1, skipp_range.end.line - 1]).
> > 
> > What do you think about this?
> > 
> > 
> +1. My perspective is that C++ source code is actually a meta-language 
> (preprocessor) that describes generation of C++ language code. That is, 
> `#if`, `#else`, `#endif` and .etc are always in a sense "executed" to 
> generate the actual code. So they shouldn't be marked as inactive.
I agree, what you describe is a nice additional improvement.

I believe it would also resolve the long-standing issue 
https://github.com/clangd/clangd/issues/773.

I will update the patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151190

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


[PATCH] D148489: [clangd] Implement configs to stop clangd produce a certain semantic tokens

2023-05-26 Thread Qingyuan Zheng via Phabricator via cfe-commits
daiyousei-qz added a comment.

Thank you! Since the documentation shouldn't be available until LLVM 17, I'm 
slowly working on it. Let me update the PR in this weekend :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148489

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


[PATCH] D151532: [test] Test ext_vector_type operators with implicit conversions

2023-05-26 Thread Cassie Jones via Phabricator via cfe-commits
porglezomp updated this revision to Diff 525974.
porglezomp added a comment.

Add significantly more variations in this test case. I discovered multiple
inconsistencies while expanding this list out. Filed an issue on GitHub here:
https://github.com/llvm/llvm-project/issues/62949


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151532

Files:
  clang/test/SemaCXX/vector.cpp

Index: clang/test/SemaCXX/vector.cpp
===
--- clang/test/SemaCXX/vector.cpp
+++ clang/test/SemaCXX/vector.cpp
@@ -772,3 +772,193 @@
 }
 #endif
 }
+
+namespace vector_implicit_conversions {
+// Test ext_vector_type builtin operators in the presence of implicit conversions
+
+typedef int __attribute__((ext_vector_type(4))) vec4i;
+
+struct vec4i_wrapper {
+vec4i x;
+
+vec4i_wrapper(const vec4i& val): x(val) {}
+operator vec4i() const { return x; } // expected-note 1+ {{candidate function}}
+};
+
+vec4i_wrapper operator| (const vec4i_wrapper& lhs, const vec4i_wrapper rhs) { return vec4i(lhs) | vec4i(rhs); }
+vec4i_wrapper& operator|= (vec4i_wrapper& lhs, const vec4i_wrapper& rhs) { return lhs = lhs | rhs; } // #oreq_operator
+
+vec4i_wrapper test_compound_assignment_mixed(vec4i_wrapper a, vec4i b) {
+  // These are not accepted because the LHS isn't subject to conversions, so no built-in operators apply here
+  a += b; // expected-error{{no viable overloaded '+='}}
+  a -= b; // expected-error{{no viable overloaded '-='}}
+  a *= b; // expected-error{{no viable overloaded '*='}}
+  a /= b; // expected-error{{no viable overloaded '/='}}
+  a %= b; // expected-error{{no viable overloaded '%='}}
+  a &= b; // expected-error{{no viable overloaded '&='}}
+  // Note: This operator is explicitly defined above, so it is accpted via implicit conversions
+  a |= b;
+  a ^= b; // expected-error{{no viable overloaded '^='}}
+  a >>= b; // expected-error{{no viable overloaded '>>='}}
+  a <<= b; // expected-error{{no viable overloaded '<<='}}
+
+  b += a;
+  b -= a;
+  b *= a;
+  b /= a;
+  // FIXME: Consistency for vector builtin operators with implicit conversions https://github.com/llvm/llvm-project/issues/62949
+  b %= a; // expected-error{{invalid operands to binary expression}}
+  b &= a; // expected-error{{invalid operands to binary expression}}
+  b |= a; // expected-error{{invalid operands to binary expression}}
+  // expected-note@#oreq_operator{{candidate function not viable}}
+  b ^= a; // expected-error{{invalid operands to binary expression}}
+  b >>= a; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+  b <<= a; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+
+  return a;
+}
+
+vec4i_wrapper test_operators_mixed(vec4i_wrapper a, vec4i b) {
+  // The operator overload isn't defined, so this is implicitly:
+  // a = vec4i_wrapper(vec4i(a) + b)
+  a = a + b;
+  a = b + a;
+  a = a - b;
+  a = b - a;
+  a = a * b;
+  a = b * a;
+  a = a / b;
+  a = b / a;
+  // FIXME: Consistency for vector builtin operators with implicit conversions https://github.com/llvm/llvm-project/issues/62949
+  a = a % b; // expected-error{{invalid operands to binary expression}}
+  a = b % a; // expected-error{{invalid operands to binary expression}}
+
+  // Conditionals yield vectors of integers
+  vec4i c;
+  c = a == b;
+  c = b == a;
+  c = a != b;
+  c = b != a;
+  c = a <= b;
+  c = b <= a;
+  c = a >= b;
+  c = b >= a;
+  c = a < b;
+  c = b < a;
+  c = a > b;
+  c = b > a;
+
+  a = a && b; // expected-error{{invalid operands to binary expression}}
+  // expected-error@-1{{cannot convert between vector and non-scalar values}}
+  a = b && a; // expected-error{{invalid operands to binary expression}}
+  // expected-error@-1{{cannot convert between vector and non-scalar values}}
+  a = a || b; // expected-error{{invalid operands to binary expression}}
+  // expected-error@-1{{cannot convert between vector and non-scalar values}}
+  a = b || a; // expected-error{{invalid operands to binary expression}}
+  // expected-error@-1{{cannot convert between vector and non-scalar values}}
+
+  a = a & b; // expected-error{{invalid operands to binary expression}}
+  a = b & a; // expected-error{{invalid operands to binary expression}}
+  // Note: These have a user-defined operator overload which is being selected
+  a = a | b;
+  a = b | a;
+  a = a ^ b; // expected-error{{invalid operands to binary expression}}
+  a = b ^ a; // expected-error{{invalid operands to binary expression}}
+  a = a << b; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+  a = b << a; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+  a = a >> b; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+  a = b >> a; // expected-error{{used type 'vec4i_wrapper' where integer is required}}
+
+  return a;
+}
+
+vec4i_wrapper 

[clang] 7c52520 - [Clang][RISCV] Add test coverage for typedef of RVV intrinsic data types under riscv_vector.h. NFC

2023-05-26 Thread via cfe-commits

Author: eopXD
Date: 2023-05-26T01:27:37-07:00
New Revision: 7c52520c8d0c44230bf5b480d83f8148bdea3232

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

LOG: [Clang][RISCV] Add test coverage for typedef of RVV intrinsic data types 
under riscv_vector.h. NFC

Signed-off by: eop Chen 

Added: 

clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-intrinsic-datatypes.cpp

Modified: 


Removed: 




diff  --git 
a/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-intrinsic-datatypes.cpp
 
b/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-intrinsic-datatypes.cpp
new file mode 100644
index ..5b23204113b8
--- /dev/null
+++ 
b/clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/rvv-intrinsic-datatypes.cpp
@@ -0,0 +1,155 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 2
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +zve32x -O0 -emit-llvm %s 
-o - | FileCheck %s
+
+#include 
+
+// This test case tests the typedef generated under riscv_vector.h
+
+// CHECK-LABEL: define dso_local void @_Z3foov
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[B64:%.*]] = alloca , align 1
+// CHECK-NEXT:[[B32:%.*]] = alloca , align 1
+// CHECK-NEXT:[[B16:%.*]] = alloca , align 1
+// CHECK-NEXT:[[B8:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8MF8:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8MF4:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8MF2:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8M1:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8M2:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8M4:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I8M8:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8MF8:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8MF4:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8MF2:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8M1:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8M2:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8M4:%.*]] = alloca , align 1
+// CHECK-NEXT:[[U8M8:%.*]] = alloca , align 1
+// CHECK-NEXT:[[I16MF4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I16MF2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I16M1:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I16M2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I16M4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I16M8:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16MF4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16MF2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16M1:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16M2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16M4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[U16M8:%.*]] = alloca , align 2
+// CHECK-NEXT:[[I32MF2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[I32M1:%.*]] = alloca , align 4
+// CHECK-NEXT:[[I32M2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[I32M4:%.*]] = alloca , align 4
+// CHECK-NEXT:[[I32M8:%.*]] = alloca , align 4
+// CHECK-NEXT:[[U32MF2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[U32M1:%.*]] = alloca , align 4
+// CHECK-NEXT:[[U32M2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[U32M4:%.*]] = alloca , align 4
+// CHECK-NEXT:[[U32M8:%.*]] = alloca , align 4
+// CHECK-NEXT:[[I64M1:%.*]] = alloca , align 8
+// CHECK-NEXT:[[I64M2:%.*]] = alloca , align 8
+// CHECK-NEXT:[[I64M4:%.*]] = alloca , align 8
+// CHECK-NEXT:[[I64M8:%.*]] = alloca , align 8
+// CHECK-NEXT:[[U64M1:%.*]] = alloca , align 8
+// CHECK-NEXT:[[U64M2:%.*]] = alloca , align 8
+// CHECK-NEXT:[[U64M4:%.*]] = alloca , align 8
+// CHECK-NEXT:[[U64M8:%.*]] = alloca , align 8
+// CHECK-NEXT:[[F16MF4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F16MF2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F16M1:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F16M2:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F16M4:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F16M8:%.*]] = alloca , align 2
+// CHECK-NEXT:[[F32MF2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[F32M1:%.*]] = alloca , align 4
+// CHECK-NEXT:[[F32M2:%.*]] = alloca , align 4
+// CHECK-NEXT:[[F32M4:%.*]] = alloca , align 4
+// CHECK-NEXT:[[F32M8:%.*]] = alloca , align 4
+// CHECK-NEXT:[[F64M1:%.*]] = alloca , align 8
+// CHECK-NEXT:[[F64M2:%.*]] = alloca , align 8
+// CHECK-NEXT:[[F64M4:%.*]] = alloca , align 8
+// CHECK-NEXT:[[F64M8:%.*]] = alloca , align 8
+// CHECK-NEXT:[[I32M1X2:%.*]] = alloca { ,  }, align 4
+// CHECK-NEXT:ret void
+//
+void foo () {
+  vbool64_t b64;
+  vbool32_t b32;
+  vbool16_t b16;
+  vbool8_t b8;
+
+  vint8mf8_t i8mf8;
+  vint8mf4_t i8mf4;
+  vint8mf2_t i8mf2;
+  vint8m1_t i8m1;
+  vint8m2_t i8m2;
+  vint8m4_t i8m4;
+  vint8m8_t

[PATCH] D151325: [analyzer] Differentiate lifetime extended temporaries

2023-05-26 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource updated this revision to Diff 525978.
tomasz-kaminski-sonarsource added a comment.

Fixed formatting to match clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151325

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Regions.def
  clang/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/test/Analysis/lifetime-extended-regions.cpp
  clang/test/Analysis/stack-addr-ps.cpp
  clang/test/Analysis/use-after-move.cpp

Index: clang/test/Analysis/use-after-move.cpp
===
--- clang/test/Analysis/use-after-move.cpp
+++ clang/test/Analysis/use-after-move.cpp
@@ -613,6 +613,14 @@
   }
 }
 
+void lifeTimeExtendTest() {
+  A&& a = A{};
+  A b = std::move(a); // peaceful-note {{Object is moved}}
+
+  a.foo(); // peaceful-warning {{Method called on moved-from object}}
+   // peaceful-note@-1 {{Method called on moved-from object}}
+}
+
 void interFunTest1(A &a) {
   a.bar(); // peaceful-warning {{Method called on moved-from object 'a'}}
// peaceful-note@-1 {{Method called on moved-from object 'a'}}
Index: clang/test/Analysis/stack-addr-ps.cpp
===
--- clang/test/Analysis/stack-addr-ps.cpp
+++ clang/test/Analysis/stack-addr-ps.cpp
@@ -30,13 +30,13 @@
 
 const int &get_reference2() {
   const int &x = get_value(); // expected-note {{binding reference variable 'x' here}}
-  return x; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning reference to local temporary}}
+  return x; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x' returned to caller}} expected-warning {{returning reference to local temporary}} 
 }
 
 const int &get_reference3() {
   const int &x1 = get_value(); // expected-note {{binding reference variable 'x1' here}}
   const int &x2 = x1; // expected-note {{binding reference variable 'x2' here}}
-  return x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning reference to local temporary}}
+  return x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x1' returned to caller}} expected-warning {{returning reference to local temporary}}
 }
 
 int global_var;
@@ -60,7 +60,7 @@
 const int *f4() {
   const int &x1 = get_value(); // expected-note {{binding reference variable 'x1' here}}
   const int &x2 = x1; // expected-note {{binding reference variable 'x2' here}}
-  return &x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' returned}} expected-warning {{returning address of local temporary}}
+  return &x2; // expected-warning{{Address of stack memory associated with temporary object of type 'int' lifetime extended by local variable 'x1' returned to caller}} expected-warning {{returning address of local temporary}}
 }
 
 struct S {
Index: clang/test/Analysis/lifetime-extended-regions.cpp
===
--- /dev/null
+++ clang/test/Analysis/lifetime-extended-regions.cpp
@@ -0,0 +1,170 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-Wno-dangling -Wno-c++1z-extensions\
+// RUN:-verify=expected,cpp14\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-analyzer-config elide-constructors=false\
+// RUN:-Wno-dangling -Wno-c++1z-extensions\
+// RUN:-verify=expected,cpp14\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection\
+// RUN:-Wno-dangling -verify=expected,cpp17\
+// RUN:-x c++ -std=c++17 %s
+
+template
+void clang_analyzer_dump(T&&) {}
+
+template
+T create() { return T{}; }
+
+template
+T const& select(bool cond, T const& t, T const& u) { return cond ? t : u; }
+
+struct Composite {
+  int x;
+  int y;
+};
+
+struct Derived : Composite {
+  int z;
+};
+
+template
+struct Array {
+  T array[20];
+
+  T&& front() && { return s

[clang-tools-extra] fe7afcf - [clangd] Remove inline Specifier for DefineOutline Tweak

2023-05-26 Thread Kadir Cetinkaya via cfe-commits

Author: Brian Gluzman
Date: 2023-05-26T10:43:08+02:00
New Revision: fe7afcf70c93223a16ec7a2a5e07c4ace16c9a04

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

LOG: [clangd] Remove inline Specifier for DefineOutline Tweak

`inline` specifiers should be removed from from the function declaration and
the newly-created implementation.

For example, take the following (working) code:
```cpp
// foo.hpp
struct A {
  inline void foo() { std::cout << "hello world\n" << std::flush; }
};

// foo.cpp
#include "foo.hpp"

// main.cpp
#include "foo.hpp"

int main() {
  A a;
  a.foo();
  return 0;
}

// compile: clang++ -std=c++20 main.cpp foo.cpp -o main
```

After applying the tweak:
```
// foo.hpp
struct A {
  inline void foo();
};

// foo.cpp
#include "foo.hpp"

inline void A::foo() { std::cout << "hello world\n" << std::flush; }

// main.cpp
#include "foo.hpp"

int main() {
  A a;
  a.foo();
  return 0;
}

// compile: clang++ -std=c++20 main.cpp foo.cpp -o main
```

We get a link error, as expected:
```
/usr/bin/ld: /tmp/main-4c5d99.o: in function `main':
main.cpp:(.text+0x14): undefined reference to `A::foo()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

This revision removes these specifiers from both the header and the source 
file. This was identified in Github issue llvm/llvm-project#61295.

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index f883397aaaf1e..b84ae04072f2c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -131,6 +131,47 @@ getFunctionSourceAfterReplacements(const FunctionDecl *FD,
   return QualifiedFunc->substr(FuncBegin, FuncEnd - FuncBegin + 1);
 }
 
+// Returns replacements to delete tokens with kind `Kind` in the range
+// `FromRange`. Removes matching instances of given token preceeding the
+// function defition.
+llvm::Expected
+deleteTokensWithKind(const syntax::TokenBuffer &TokBuf, tok::TokenKind Kind,
+ SourceRange FromRange) {
+  tooling::Replacements DelKeywordCleanups;
+  llvm::Error Errors = llvm::Error::success();
+  bool FoundAny = false;
+  for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
+if (Tok.kind() != Kind)
+  continue;
+FoundAny = true;
+auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
+if (!Spelling) {
+  Errors = llvm::joinErrors(
+  std::move(Errors),
+  error("define outline: couldn't remove `{0}` keyword.",
+tok::getKeywordSpelling(Kind)));
+  break;
+}
+auto &SM = TokBuf.sourceManager();
+CharSourceRange DelRange =
+syntax::Token::range(SM, Spelling->front(), Spelling->back())
+.toCharRange(SM);
+if (auto Err =
+DelKeywordCleanups.add(tooling::Replacement(SM, DelRange, "")))
+  Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
+  }
+  if (!FoundAny) {
+Errors = llvm::joinErrors(
+std::move(Errors),
+error("define outline: couldn't find `{0}` keyword to remove.",
+  tok::getKeywordSpelling(Kind)));
+  }
+
+  if (Errors)
+return std::move(Errors);
+  return DelKeywordCleanups;
+}
+
 // Creates a modified version of function definition that can be inserted at a
 // 
diff erent location, qualifies return value and function name to achieve that.
 // Contains function signature, except defaulted parameter arguments, body and
@@ -251,34 +292,16 @@ getFunctionSourceCode(const FunctionDecl *FD, 
llvm::StringRef TargetNamespace,
   DelAttr(FD->getAttr());
 
   auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
-bool FoundAny = false;
-for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
-  if (Tok.kind() != Kind)
-continue;
-  FoundAny = true;
-  auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
-  if (!Spelling) {
-Errors = llvm::joinErrors(
-std::move(Errors),
-error("define outline: couldn't remove `{0}` keyword.",
-  tok::getKeywordSpelling(Kind)));
-break;
-  }
-  CharSourceRange DelRange =
-  syntax::Token::range(SM, Spelling->front(), Spelling->back())
-  .toCharRange(SM);
-  if (auto Err =
-  DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
-Errors = llvm::joinErrors(std::move(Errors), std::move(E

[PATCH] D151294: [clangd] Remove inline Specifier for DefineOutline Tweak

2023-05-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfe7afcf70c93: [clangd] Remove inline Specifier for 
DefineOutline Tweak (authored by bgluzman, committed by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151294

Files:
  clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
  clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
@@ -136,6 +136,12 @@
   "void foo() ;",
   "void foo() { return; }",
   },
+  // Inline specifier.
+  {
+  "inline void fo^o() { return; }",
+  " void foo() ;",
+  " void foo() { return; }",
+  },
   // Default args.
   {
   "void fo^o(int x, int y = 5, int = 2, int (*foo)(int) = nullptr) {}",
@@ -319,6 +325,17 @@
 };)cpp",
   "  Foo::Foo(int) {}\n",
   },
+  {
+  R"cpp(
+struct A {
+  inline void f^oo(int) {}
+};)cpp",
+  R"cpp(
+struct A {
+   void foo(int) ;
+};)cpp",
+  " void A::foo(int) {}\n",
+  },
   // Destrctors
   {
   "class A { ~A^(){} };",
Index: clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -131,6 +131,47 @@
   return QualifiedFunc->substr(FuncBegin, FuncEnd - FuncBegin + 1);
 }
 
+// Returns replacements to delete tokens with kind `Kind` in the range
+// `FromRange`. Removes matching instances of given token preceeding the
+// function defition.
+llvm::Expected
+deleteTokensWithKind(const syntax::TokenBuffer &TokBuf, tok::TokenKind Kind,
+ SourceRange FromRange) {
+  tooling::Replacements DelKeywordCleanups;
+  llvm::Error Errors = llvm::Error::success();
+  bool FoundAny = false;
+  for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
+if (Tok.kind() != Kind)
+  continue;
+FoundAny = true;
+auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
+if (!Spelling) {
+  Errors = llvm::joinErrors(
+  std::move(Errors),
+  error("define outline: couldn't remove `{0}` keyword.",
+tok::getKeywordSpelling(Kind)));
+  break;
+}
+auto &SM = TokBuf.sourceManager();
+CharSourceRange DelRange =
+syntax::Token::range(SM, Spelling->front(), Spelling->back())
+.toCharRange(SM);
+if (auto Err =
+DelKeywordCleanups.add(tooling::Replacement(SM, DelRange, "")))
+  Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
+  }
+  if (!FoundAny) {
+Errors = llvm::joinErrors(
+std::move(Errors),
+error("define outline: couldn't find `{0}` keyword to remove.",
+  tok::getKeywordSpelling(Kind)));
+  }
+
+  if (Errors)
+return std::move(Errors);
+  return DelKeywordCleanups;
+}
+
 // Creates a modified version of function definition that can be inserted at a
 // different location, qualifies return value and function name to achieve that.
 // Contains function signature, except defaulted parameter arguments, body and
@@ -251,34 +292,16 @@
   DelAttr(FD->getAttr());
 
   auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
-bool FoundAny = false;
-for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
-  if (Tok.kind() != Kind)
-continue;
-  FoundAny = true;
-  auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
-  if (!Spelling) {
-Errors = llvm::joinErrors(
-std::move(Errors),
-error("define outline: couldn't remove `{0}` keyword.",
-  tok::getKeywordSpelling(Kind)));
-break;
-  }
-  CharSourceRange DelRange =
-  syntax::Token::range(SM, Spelling->front(), Spelling->back())
-  .toCharRange(SM);
-  if (auto Err =
-  DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
-Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
-}
-if (!FoundAny) {
-  Errors = llvm::joinErrors(
-  std::move(Errors),
-  error("define outline: couldn't find `{0}` keyword to remove.",
-tok::getKeywordSpelling(Kind)));
+auto DelKeywords = deleteTokensWithKind(TokBuf, Kind, FromRange);
+if (!DelKeywords) {
+  Errors = llvm::joinErrors(std::move(Errors), DelKeywords.takeError());
+  return;
 }
+DeclarationCleanups = DeclarationCleanups.me

[clang] 10518fe - [clang-format][doc] Fix contradiction in SortIncludes description

2023-05-26 Thread Owen Pan via cfe-commits

Author: Mike Matthews
Date: 2023-05-26T01:58:57-07:00
New Revision: 10518feaf33760e77be46af62c41a1caf4ef1da2

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

LOG: [clang-format][doc] Fix contradiction in SortIncludes description

Fixes #62033.

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 56b6b62e3138c..a8fc651f92a99 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2453,7 +2453,7 @@ the configuration (without a prefix: ``Auto``).
   * ``BBCDS_Allowed`` (in configuration: ``Allowed``)
 Breaking between template declaration and ``concept`` is allowed. The
 actual behavior depends on the content and line breaking rules and
-penalties.
+penalities.
 
   * ``BBCDS_Always`` (in configuration: ``Always``)
 Always break before ``concept``, putting it in the line after the
@@ -4561,11 +4561,6 @@ the configuration (without a prefix: ``Auto``).
 
 **SortIncludes** (``SortIncludesOptions``) :versionbadge:`clang-format 3.8` 
:ref:`¶ `
   Controls if and how clang-format will sort ``#includes``.
-  If ``Never``, includes are never sorted.
-  If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  insensitive fashion.
-  If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  sensitive fashion.
 
   Possible values:
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 1cc1037562b89..78c08477e9a18 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3601,11 +3601,6 @@ struct FormatStyle {
   };
 
   /// Controls if and how clang-format will sort ``#includes``.
-  /// If ``Never``, includes are never sorted.
-  /// If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  /// insensitive fashion.
-  /// If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  /// sensitive fashion.
   /// \version 3.8
   SortIncludesOptions SortIncludes;
 



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


[PATCH] D147894: [clang-format][doc] SortIncludes documentation: remove contradiction in its description

2023-05-26 Thread Owen Pan 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 rG10518feaf337: [clang-format][doc] Fix contradiction in 
SortIncludes description (authored by michael-g-matthews, committed by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D147894?vs=512042&id=525986#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147894

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -3601,11 +3601,6 @@
   };
 
   /// Controls if and how clang-format will sort ``#includes``.
-  /// If ``Never``, includes are never sorted.
-  /// If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  /// insensitive fashion.
-  /// If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  /// sensitive fashion.
   /// \version 3.8
   SortIncludesOptions SortIncludes;
 
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2453,7 +2453,7 @@
   * ``BBCDS_Allowed`` (in configuration: ``Allowed``)
 Breaking between template declaration and ``concept`` is allowed. The
 actual behavior depends on the content and line breaking rules and
-penalties.
+penalities.
 
   * ``BBCDS_Always`` (in configuration: ``Always``)
 Always break before ``concept``, putting it in the line after the
@@ -4561,11 +4561,6 @@
 
 **SortIncludes** (``SortIncludesOptions``) :versionbadge:`clang-format 3.8` 
:ref:`¶ `
   Controls if and how clang-format will sort ``#includes``.
-  If ``Never``, includes are never sorted.
-  If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  insensitive fashion.
-  If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  sensitive fashion.
 
   Possible values:
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -3601,11 +3601,6 @@
   };
 
   /// Controls if and how clang-format will sort ``#includes``.
-  /// If ``Never``, includes are never sorted.
-  /// If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  /// insensitive fashion.
-  /// If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  /// sensitive fashion.
   /// \version 3.8
   SortIncludesOptions SortIncludes;
 
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -2453,7 +2453,7 @@
   * ``BBCDS_Allowed`` (in configuration: ``Allowed``)
 Breaking between template declaration and ``concept`` is allowed. The
 actual behavior depends on the content and line breaking rules and
-penalties.
+penalities.
 
   * ``BBCDS_Always`` (in configuration: ``Always``)
 Always break before ``concept``, putting it in the line after the
@@ -4561,11 +4561,6 @@
 
 **SortIncludes** (``SortIncludesOptions``) :versionbadge:`clang-format 3.8` :ref:`¶ `
   Controls if and how clang-format will sort ``#includes``.
-  If ``Never``, includes are never sorted.
-  If ``CaseInsensitive``, includes are sorted in an ASCIIbetical or case
-  insensitive fashion.
-  If ``CaseSensitive``, includes are sorted in an alphabetical or case
-  sensitive fashion.
 
   Possible values:
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] aed7959 - [clang-format][doc] Fix a typo introduced in 9aab0db13fb6d

2023-05-26 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-05-26T02:11:42-07:00
New Revision: aed795942b78876d004c146133d9077012256aff

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

LOG: [clang-format][doc] Fix a typo introduced in 9aab0db13fb6d

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index a8fc651f92a9..8f23a4aa27a9 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2453,7 +2453,7 @@ the configuration (without a prefix: ``Auto``).
   * ``BBCDS_Allowed`` (in configuration: ``Allowed``)
 Breaking between template declaration and ``concept`` is allowed. The
 actual behavior depends on the content and line breaking rules and
-penalities.
+penalties.
 
   * ``BBCDS_Always`` (in configuration: ``Always``)
 Always break before ``concept``, putting it in the line after the

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 78c08477e9a1..6a9d435174cd 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1801,7 +1801,7 @@ struct FormatStyle {
 BBCDS_Never,
 /// Breaking between template declaration and ``concept`` is allowed. The
 /// actual behavior depends on the content and line breaking rules and
-/// penalities.
+/// penalties.
 BBCDS_Allowed,
 /// Always break before ``concept``, putting it in the line after the
 /// template declaration.



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


[PATCH] D151547: [RISCV] Remove experimental for zihintntl.

2023-05-26 Thread Jianjian Guan via Phabricator via cfe-commits
jacquesguan created this revision.
jacquesguan added reviewers: craig.topper, asb, luismarques, frasercrmck.
Herald added subscribers: jobnoorman, luke, VincentWu, vkmr, jdoerfert, apazos, 
sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, PkmX, the_o, 
brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, shiva0217, 
kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, hiraditya, 
arichardson.
Herald added a project: All.
jacquesguan requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, pcwang-thead, eopXD, 
MaskRay.
Herald added projects: clang, LLVM.

Since zihintntl is ratified now, we could remove the experimental prefix and 
change its version to 1.0.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151547

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/CodeGen/RISCV/nontemporal-scalable.ll
  llvm/test/CodeGen/RISCV/nontemporal.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zihintntl-invalid.s
  llvm/test/MC/RISCV/rv32zihintntl-valid.s
  llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
  llvm/test/MC/RISCV/rv32zihintntlc-valid.s
  llvm/unittests/Support/RISCVISAInfoTest.cpp

Index: llvm/unittests/Support/RISCVISAInfoTest.cpp
===
--- llvm/unittests/Support/RISCVISAInfoTest.cpp
+++ llvm/unittests/Support/RISCVISAInfoTest.cpp
@@ -375,7 +375,7 @@
   RISCVISAInfo::OrderedExtensionMap Exts = (*MaybeISAInfo)->getExtensions();
   EXPECT_EQ(Exts.size(), 2UL);
   EXPECT_EQ(Exts.count("zihintntl"), 1U);
-  auto MaybeISAInfo2 = RISCVISAInfo::parseArchString("rv64izihintntl0p2", true);
+  auto MaybeISAInfo2 = RISCVISAInfo::parseArchString("rv64izihintntl1p0", true);
   ASSERT_THAT_EXPECTED(MaybeISAInfo2, Succeeded());
   RISCVISAInfo::OrderedExtensionMap Exts2 = (*MaybeISAInfo2)->getExtensions();
   EXPECT_EQ(Exts2.size(), 2UL);
@@ -454,13 +454,13 @@
   RISCVISAInfo::parseArchString("rv64im_zihintntl", true, false);
   ASSERT_THAT_EXPECTED(MaybeISAInfo1, Succeeded());
   EXPECT_THAT((*MaybeISAInfo1)->toFeatureVector(),
-  ElementsAre("+m", "+experimental-zihintntl"));
+  ElementsAre("+m", "+zihintntl"));
 
   auto MaybeISAInfo2 = RISCVISAInfo::parseArchString(
   "rv32e_zihintntl_xventanacondops", true, false);
   ASSERT_THAT_EXPECTED(MaybeISAInfo2, Succeeded());
   EXPECT_THAT((*MaybeISAInfo2)->toFeatureVector(),
-  ElementsAre("+e", "+experimental-zihintntl", "+xventanacondops"));
+  ElementsAre("+e", "+zihintntl", "+xventanacondops"));
 }
 
 TEST(ToFeatureVector, UnsupportedExtensionsAreDropped) {
Index: llvm/test/MC/RISCV/rv32zihintntlc-valid.s
===
--- llvm/test/MC/RISCV/rv32zihintntlc-valid.s
+++ llvm/test/MC/RISCV/rv32zihintntlc-valid.s
@@ -1,15 +1,15 @@
-# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zihintntl,+c -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zihintntl,+c -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zihintntl,+c -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zihintntl,+c -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zihintntl,+c < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl,+c -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+zihintntl,+c < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl,+c -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zihintntl,+c < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zihintntl,+c -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+zihintntl,+c < %s \
+# RUN: | llvm-objdump --mattr=+zihintntl,+c -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: not llvm-mc %s -triple=riscv32 -mattr=+experimental-zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
-# RUN: not llvm-mc %s -triple=riscv64 -mattr=+experimental-zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
+# RUN: not llvm-mc %s -triple=riscv32 -mattr=+zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
+# RUN: not llvm-mc %s -triple=riscv64 -mattr=+zihintntl 2>&1 | FileCheck -check-prefix=CHECK-NO-C %s
 
 # CHECK-ASM-AND-OBJ: ntl.p1
 # CHECK-ASM: encoding: [0x33,0x00,0x20,0x00]
Index: llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
===
--- llvm/test/MC/RISCV/rv32zihintntlc-invalid.s
+++ llvm

[PATCH] D151547: [RISCV] Remove experimental for zihintntl.

2023-05-26 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

Is the __riscv_ntl_* interface finalised and agreed? I'm wary of repeating the 
mistake we made with the V extension where we exposed intrinsics that weren't 
yet finalised.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151547

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


[PATCH] D151225: [clang][analyzer] Merge apiModeling.StdCLibraryFunctions and StdCLibraryFunctionArgs checkers into one.

2023-05-26 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.
This revision is now accepted and ready to land.

Ugh, yeah, so it has come to this. I championed my idea of granulalizing 
checkers into modeling and reporting components since what... 2018? I think the 
goal is still something to shoot for, but its time to admit that we the 
underlaying infrastructure needs to encourage that a lot more (and there is 
already so much dept in the form of these giant checkers).

I like the idea that the modeling portion and the reporting portion are in 
different checkers, but that is hard to achieve, when fatal errors by the sheer 
fact that they create sinkholes makes this practically impossible (we'd have to 
rewrite almost EVERY checker with that in mind, and also in way that it wont 
just require a branch). Even then, I'm not sure we would want that -- our 
checkers are not perfect, and yes, we sometimes do want to explicitly disable a 
non-alpha checker and everything that they do, including modeing because they 
are not working well on a project.

For how much I took a dump on checker silencing back in the day, I'm coming to 
terms with the fact that it is likely to be the most sustainable approach 
moving forward. Or, I don't know, the sheer size of these checkers really 
scream for some splitting up...

In any case, LGTM. I'm sure there are other ways around this, like creating an 
inner checker callback system inside this checker, but that sounds ridiculus, 
and its not like we can't do it after the fact.

Please grep the codebase for `apiModeling.StdCLibraryFunctionsChecker` to find 
other references to the now removed checker. Do the docs need any adjustment?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151225

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


[PATCH] D151549: [clang][dataflow] Remove unnecessary `ASTContext` parameter from `ControlFlowContext::build` overload.

2023-05-26 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When introducing this new overload in https://reviews.llvm.org/D151183, I didn't
consider that the `ASTContext` parameter was unnecessary because it could
also be obtained from the `FunctionDecl`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151549

Files:
  clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
  clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -65,7 +65,7 @@
   assert(Func != nullptr);
 
   auto CFCtx =
-  llvm::cantFail(ControlFlowContext::build(*Func, AST->getASTContext()));
+  llvm::cantFail(ControlFlowContext::build(*Func));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
   DataflowAnalysisContext DACtx(std::make_unique());
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -241,7 +241,7 @@
   llvm::errc::invalid_argument, "Could not find the target function.");
 
 // Build the control flow graph for the target function.
-auto MaybeCFCtx = ControlFlowContext::build(*Target, Context);
+auto MaybeCFCtx = ControlFlowContext::build(*Target);
 if (!MaybeCFCtx) return MaybeCFCtx.takeError();
 auto &CFCtx = *MaybeCFCtx;
 
Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -211,7 +211,7 @@
 return &It->second;
 
   if (F->hasBody()) {
-auto CFCtx = ControlFlowContext::build(*F, F->getASTContext());
+auto CFCtx = ControlFlowContext::build(*F);
 // FIXME: Handle errors.
 assert(CFCtx);
 auto Result = FunctionContexts.insert({F, std::move(*CFCtx)});
Index: clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
===
--- clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
+++ clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
@@ -68,13 +68,13 @@
 }
 
 llvm::Expected
-ControlFlowContext::build(const FunctionDecl &Func, ASTContext &C) {
+ControlFlowContext::build(const FunctionDecl &Func) {
   if (!Func.hasBody())
 return llvm::createStringError(
 std::make_error_code(std::errc::invalid_argument),
 "Cannot analyze function without a body");
 
-  return build(Func, *Func.getBody(), C);
+  return build(Func, *Func.getBody(), Func.getASTContext());
 }
 
 llvm::Expected
Index: clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
===
--- clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
+++ clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
@@ -33,8 +33,7 @@
 public:
   /// Builds a ControlFlowContext from a `FunctionDecl`.
   /// `Func.hasBody()` must be true, and `Func.isTemplated()` must be false.
-  static llvm::Expected build(const FunctionDecl &Func,
-  ASTContext &C);
+  static llvm::Expected build(const FunctionDecl &Func);
 
   /// Builds a ControlFlowContext from an AST node. `D` is the function in 
which
   /// `S` resides. `D.isTemplated()` must be false.


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -65,7 +65,7 @@
   assert(Func != nullptr);
 
   auto CFCtx =
-  llvm::cantFail(ControlFlowContext::build(*Func, AST->getASTContext()));
+  llvm::cantFail(ControlFlowContext::build(*Func));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
   DataflowAnalysisContext DACtx(std::make_unique());
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/Flow

[PATCH] D151225: [clang][analyzer] Merge apiModeling.StdCLibraryFunctions and StdCLibraryFunctionArgs checkers into one.

2023-05-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I think I'm also for this change.

I also wonder why we can't enable posix modeling by default. If we still can't, 
then when will we? Do you think it would make sense to enable them in the 
future?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151225

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


[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill updated this revision to Diff 526013.
Endill edited the summary of this revision.
Endill added a comment.

Address feedback
Docs contributed by @aaron.ballman


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

Files:
  clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
  clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
  clang/test/Frontend/verify-maybe-no-diagnostics.c

Index: clang/test/Frontend/verify-maybe-no-diagnostics.c
===
--- clang/test/Frontend/verify-maybe-no-diagnostics.c
+++ clang/test/Frontend/verify-maybe-no-diagnostics.c
@@ -2,7 +2,9 @@
 // RUN: %clang_cc1 -DTEST_B1 -verify %s
 // RUN: %clang_cc1 -DTEST_B2 -verify %s
 // RUN: %clang_cc1 -DTEST_C1 -verify %s
-// RUN: %clang_cc1 -DTEST_C2 -verify %s
+// RUN: not %clang_cc1 -DTEST_C2 -verify %s 2>&1 | FileCheck --check-prefix=C2-CHECK %s
+// RUN: %clang_cc1 -DTEST_C3 -verify %s
+// RUN: not %clang_cc1 -DTEST_C4 -verify %s 2>&1 | FileCheck --check-prefix=C4-CHECK %s
 // RUN: not %clang_cc1 -DTEST_D1 -verify %s 2>&1 | FileCheck --check-prefix=D1-CHECK %s
 // RUN: not %clang_cc1 -DTEST_D2 -verify %s 2>&1 | FileCheck --check-prefix=D2-CHECK %s
 // RUN: not %clang_cc1 -DTEST_D3 -verify %s 2>&1 | FileCheck --check-prefix=D3-CHECK %s
@@ -31,11 +33,29 @@
 #endif
 
 #ifdef TEST_C2
+// expected-maybe-no-diagnostics
 #error test_c2
-// expected-error@-1 {{test_c2}}
+
+//  C2-CHECK: error: 'error' diagnostics seen but not expected:
+// C2-CHECK-NEXT:   {{test_c2}}
+// C2-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_C3
+#error test_c3
+// expected-error@-1 {{test_c3}}
 // expected-maybe-no-diagnostics
 #endif
 
+#ifdef TEST_C4
+#error test_c4
+// expected-maybe-no-diagnostics
+
+//  C4-CHECK: error: 'error' diagnostics seen but not expected:
+// C4-CHECK-NEXT:   {{test_c4}}
+// C4-CHECK-NEXT: 1 error generated.
+#endif
+
 #ifdef TEST_D1
 // expected-maybe-no-diagnostics
 #error test_d1
Index: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
===
--- clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
+++ clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
@@ -453,6 +453,7 @@
 
 // Type in initial directive token: -{error|warning|note|no-diagnostics}
 bool NoDiag = false;
+bool MaybeNoDiag = false;
 StringRef DType;
 if (DToken.endswith(DType="-error"))
   D.DL = ED ? &ED->Errors : nullptr;
@@ -462,11 +463,9 @@
   D.DL = ED ? &ED->Remarks : nullptr;
 else if (DToken.endswith(DType="-note"))
   D.DL = ED ? &ED->Notes : nullptr;
-else if (DToken.endswith(DType="-maybe-no-diagnostics")) {
-  if (Status == VerifyDiagnosticConsumer::HasNoDirectives)
-Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
-  continue;
-} else if (DToken.endswith(DType="-no-diagnostics")) {
+else if (DToken.endswith(DType="-maybe-no-diagnostics"))
+  MaybeNoDiag = true;
+else if (DToken.endswith(DType="-no-diagnostics")) {
   NoDiag = true;
   if (D.RegexKind)
 continue;
@@ -481,6 +480,12 @@
 if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
   continue;
 
+if (MaybeNoDiag) {
+  if (Status == VerifyDiagnosticConsumer::HasNoDirectives)
+Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
+  continue;
+}
+
 if (NoDiag) {
   if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
 Diags.Report(Pos, diag::err_verify_invalid_no_diags)
Index: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
===
--- clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -183,6 +183,23 @@
 ///   // expected-no-diagnostics
 /// \endcode
 ///
+/// Additionally, you can use:
+///
+/// \code
+///   // expected-maybe-no-diagnostics
+/// \endcode
+///
+/// to specify that a file with no "expected-*" comments should pass when no
+/// diagnostics are generated, but doesn't conflict with "expected-*" directives
+/// when they are present. This situation mostly comes up for DR conformance tests
+/// where dozens of distinct test cases are within the same physical file but use
+/// the 'split-file' utility to split individual test cases into logical files
+/// at runtime. In that case, a header file containing "expected-maybe-no-diagnostics"
+/// can be force included into each RUN line in the physical file. The tests that
+/// expect diagostics continue to pass or fail depending on whether the correct
+/// diagnostics are emitted, but they do not fail automatically due to a
+/// combination of "expected-no-diagnostics" and "expected-*" within the same
+/// test. The "expected-no-diagnostics" comment is almost always preferred.
 class VerifyDiagnosticConsumer: publ

[PATCH] D151553: [clang] Fix consteval operators in template contexts

2023-05-26 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Clang used to reject consteval operators if they're used inside a
template due to TreeTransform putting two different `DeclRefExpr`
expressions for the same reference of the same operator declaration into
`ReferenceToConsteval` set.
It seems there was an attempt to not rebuild the whole operator that
never succeeded, so this patch just removes this attempt and
problemating referencing of a `DeclRefExpr` that always ended up
discarded.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151553

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

Index: clang/test/SemaCXX/consteval-operators.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/consteval-operators.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 -std=c++2a -emit-llvm-only -Wno-unused-value %s -verify
+
+// expected-no-diagnostics
+
+struct A {
+  consteval A operator+() { return {}; }
+};
+consteval A operator~(A) { return {}; }
+consteval A operator+(A, A) { return {}; }
+
+template  void f() {
+  A a;
+  A b = ~a;
+  A c = a + a;
+  A d = +a;
+}
+template void f();
+
+template  void foo() {
+  T a;
+  T b = ~a;
+  T c = a + a;
+  T d = +a;
+}
+
+template void foo();
+
+template  struct B { DataT D; };
+
+template 
+consteval B operator+(B lhs, B rhs) {
+  return B{lhs.D + rhs.D};
+}
+
+template  consteval T template_add(T a, T b) { return a + b; }
+
+consteval B non_template_add(B a, B b) { return a + b; }
+
+void bar() {
+  constexpr B a{};
+  constexpr B b{};
+  auto constexpr c = a + b;
+}
+
+static_assert((template_add(B{7}, B{3})).D == 10);
+static_assert((non_template_add(B{7}, B{3})).D == 10);
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -11937,10 +11937,6 @@
 llvm_unreachable("not an overloaded operator?");
   }
 
-  ExprResult Callee = getDerived().TransformExpr(E->getCallee());
-  if (Callee.isInvalid())
-return ExprError();
-
   ExprResult First;
   if (E->getOperator() == OO_Amp)
 First = getDerived().TransformAddressOfOperand(E->getArg(0));
@@ -11957,23 +11953,15 @@
   return ExprError();
   }
 
-  if (!getDerived().AlwaysRebuild() &&
-  Callee.get() == E->getCallee() &&
-  First.get() == E->getArg(0) &&
-  (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
-return SemaRef.MaybeBindToTemporary(E);
-
   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
   FPOptionsOverride NewOverrides(E->getFPFeatures());
   getSema().CurFPFeatures =
   NewOverrides.applyOverrides(getSema().getLangOpts());
   getSema().FpPragmaStack.CurrentValue = NewOverrides;
 
-  return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
- E->getOperatorLoc(),
- Callee.get(),
- First.get(),
- Second.get());
+  return getDerived().RebuildCXXOperatorCallExpr(
+  E->getOperator(), E->getOperatorLoc(), E->getCallee(), First.get(),
+  Second.get());
 }
 
 template
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -455,6 +455,8 @@
 - Fix crash when diagnosing default comparison method.
   (`#62791 `_) and
   (`#62102 `_).
+- Fix reject-valid when consteval operator appears inside of a template.
+  (`#62886 `_).
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill added a comment.

Thank you for the review!




Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:468
+Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
+  continue;
+} else if (DToken.endswith(DType="-no-diagnostics")) {

jdenny wrote:
> This `continue` skips the prefix checking below, which is important when 
> there are multiple prefixes active (e.g., `-verify=foo,bar`).  That is, any 
> old `BOGUS-maybe-no-diagnostics` will be effective then.
This should be fixed now. Thank you for spotting this!



Comment at: clang/test/Frontend/verify-maybe-no-diagnostics.c:38
+#endif
+
+#ifdef TEST_D1

jdenny wrote:
> Please test this case:
> 
> ```
> #ifdef TEST_C3
> // expected-maybe-no-diagnostics
> #error test_c3
> #endif
> ```
> 
> That is, does Clang actually fail in this case as expected because there's an 
> error and no corresponding `expected-error` directive?  Or does it ignore the 
> error because of the `expected-maybe-no-diagnostics` directive?
Added C2 and C4 tests that should cover that.

> That is, does Clang actually fail in this case as expected because there's an 
> error and no corresponding expected-error directive? Or does it ignore the 
> error because of the expected-maybe-no-diagnostics directive?

It works like there's no `// expected-maybe-no-diagnostics`. That is, failing 
because there's no matching `expected-error` directive for an error produced.



Comment at: clang/test/Frontend/verify-maybe-no-diagnostics.c:51-52
+#ifdef TEST_D2
+// expected-maybe-no-diagnostics
+// expected-no-diagnostics
+#error test_d2

jdenny wrote:
> So `expected-no-diagnostics` overrides `expected-maybe-no-diagnostics`.  In 
> your use case, omitting one or the other is not always possible?
Yes, it works the way you describe.
In our case, `// expected-maybe-no-diagnostic` comes into hundreds of test 
cases from force include. It's very much possible for us to ensure that only 
one of them is present, by banning `expected-no-diagnostics`.

`expected-maybe-no-diagnostic` is by design low-priority and no-friction 
directive, contrary to strict nature of all other directives. That's why it 
could be very easily overridden.



Comment at: clang/test/Frontend/verify-maybe-no-diagnostics.c:104
+//  D6-CHECK: error: 'error' diagnostics seen but not expected:
+// D6-CHECK-NEXT:   {{.*}} 'expected-no-diagnostics' directive cannot follow 
other expected directives
+// D6-CHECK-NEXT: 1 error generated.

jdenny wrote:
> This diagnostic is confusing.  Should we add "except 
> 'expected-maybe-no-diagnostics'"?
As I mentioned in another comment, `maybe-no-diagnostics` has the lowest 
priority, and doesn't have strict and declarative nature, unlike any other 
directive. That's why it should never be expected (and ideally very rarely 
used).

The purpose of all the tests I added is to ensure `expected-no-diagnostic` 
doesn't affect existing directives and their interaction in any way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

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


[PATCH] D151553: [clang] Fix consteval operators in template contexts

2023-05-26 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/TreeTransform.h:11940-11943
-  ExprResult Callee = getDerived().TransformExpr(E->getCallee());
-  if (Callee.isInvalid())
-return ExprError();
-

I don't understand why we would not need to transform the callee. do we do that 
elsewhere?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151553

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


[PATCH] D151553: [clang] Fix consteval operators in template contexts

2023-05-26 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added inline comments.



Comment at: clang/lib/Sema/TreeTransform.h:11940-11943
-  ExprResult Callee = getDerived().TransformExpr(E->getCallee());
-  if (Callee.isInvalid())
-return ExprError();
-

cor3ntin wrote:
> I don't understand why we would not need to transform the callee. do we do 
> that elsewhere?
For example, the code above for call and subscript operators never transforms 
the callee.
This `TransFormExpr` call  seems to be a no-op for overloaded operator call 
case, and the result never ends up in the resulting ast.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151553

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-05-26 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

Hey, found another error that looks to be different from @maskray's revert.

  $ bin/clang -c -O2 -g -ftrivial-auto-var-init=zero /tmp/repro.c


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D147218: [OpenMP][Flang][MLIR] Lowering of OpenMP requires directive from parse tree to MLIR

2023-05-26 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis added inline comments.



Comment at: flang/lib/Lower/OpenMP.cpp:2552
+
+void handleDeclareTarget(Fortran::lower::AbstractConverter &converter,
+ Fortran::lower::pft::Evaluation &eval,

This seems to be the only function name with the 'handle' prefix. Maybe rename 
it to something like `genDeclareTarget` ?



Comment at: flang/lib/Lower/OpenMP.cpp:2563
+
+  auto mod = converter.getFirOpBuilder().getModule();
   for (auto sym : symbolAndClause) {

Remove use of auto here.

Also in other places if the type isn't immediately discernible then consider 
naming the type. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147218

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


[PATCH] D151342: [Clang] Correctly handle generic lambda used as default template argument.

2023-05-26 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 526034.
cor3ntin added a comment.

Address Erich's feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151342

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Parse/ParseTemplate.cpp
  clang/test/SemaCXX/cxx2a-template-lambdas.cpp


Index: clang/test/SemaCXX/cxx2a-template-lambdas.cpp
===
--- clang/test/SemaCXX/cxx2a-template-lambdas.cpp
+++ clang/test/SemaCXX/cxx2a-template-lambdas.cpp
@@ -43,3 +43,30 @@
 }
 static_assert(outer() == 123);
 template int *outer(); // expected-note {{in instantiation}}
+
+
+namespace GH62611 {
+template 
+struct C {
+  static constexpr auto B = A;
+};
+
+int test() {
+  C<>::B(42);
+}
+
+namespace AutoParam
+{
+template 
+auto B = A;
+static_assert(B<>(42) == 42);
+}
+
+namespace TypeParam
+{
+template 
+auto B = T{};
+static_assert(B<>(42) == 42);
+}
+
+}
Index: clang/lib/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -841,10 +841,17 @@
   // we introduce the type parameter into the local scope.
   SourceLocation EqualLoc;
   ParsedType DefaultArg;
-  if (TryConsumeToken(tok::equal, EqualLoc))
+  if (TryConsumeToken(tok::equal, EqualLoc)) {
+// The default argument may declare template parameters, notably
+// if it contains a generic lambda, so we need to increase
+// the template depth as these parameters would not be instantiated
+// at the current level.
+TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
+++CurTemplateDepthTracker;
 DefaultArg =
 ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
 .get();
+  }
 
   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
   TypenameKeyword, EllipsisLoc,
@@ -1030,6 +1037,14 @@
   //   end of the template-parameter-list rather than a greater-than
   //   operator.
   GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
+
+  // The default argument may declare template parameters, notably
+  // if it contains a generic lambda, so we need to increase
+  // the template depth as these parameters would not be instantiated
+  // at the current level.
+  TemplateParameterDepthRAII CurTemplateDepthTracker(
+  TemplateParameterDepth);
+  ++CurTemplateDepthTracker;
   EnterExpressionEvaluationContext ConstantEvaluated(
   Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   DefaultArg =
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -485,6 +485,8 @@
   (`#114 `_)
 - Fix parsing of `auto(x)`, when it is surrounded by parentheses.
   (`#62494 `_)
+- Fix handling of generic lambda used as template arguments.
+  (`#62611 `_)
 
 Bug Fixes to AST Handling
 ^


Index: clang/test/SemaCXX/cxx2a-template-lambdas.cpp
===
--- clang/test/SemaCXX/cxx2a-template-lambdas.cpp
+++ clang/test/SemaCXX/cxx2a-template-lambdas.cpp
@@ -43,3 +43,30 @@
 }
 static_assert(outer() == 123);
 template int *outer(); // expected-note {{in instantiation}}
+
+
+namespace GH62611 {
+template 
+struct C {
+  static constexpr auto B = A;
+};
+
+int test() {
+  C<>::B(42);
+}
+
+namespace AutoParam
+{
+template 
+auto B = A;
+static_assert(B<>(42) == 42);
+}
+
+namespace TypeParam
+{
+template 
+auto B = T{};
+static_assert(B<>(42) == 42);
+}
+
+}
Index: clang/lib/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -841,10 +841,17 @@
   // we introduce the type parameter into the local scope.
   SourceLocation EqualLoc;
   ParsedType DefaultArg;
-  if (TryConsumeToken(tok::equal, EqualLoc))
+  if (TryConsumeToken(tok::equal, EqualLoc)) {
+// The default argument may declare template parameters, notably
+// if it contains a generic lambda, so we need to increase
+// the template depth as these parameters would not be instantiated
+// at the current level.
+TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
+++CurTemplateDepthTracker;
 DefaultArg =
 ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
 .get();
+  }
 
   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
   TypenameKeyword, EllipsisLoc,
@@ -1030,6 +103

[PATCH] D150670: [WebAssembly] Disable generation of fshl/fshr for rotates

2023-05-26 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 526044.
pmatos added a comment.

Update the patch by removing target specific changes in CGBuiltin. 
Leave fshl/fshr unchanged for rotates. This actually fixes a todo in fshl/r 
test.

@nikic What do you think of the current patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150670

Files:
  clang/test/CodeGen/WebAssembly/wasm-rotate.c
  llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
  llvm/test/CodeGen/WebAssembly/rotate-i3264.ll
  llvm/test/Transforms/InstCombine/fsh.ll

Index: llvm/test/Transforms/InstCombine/fsh.ll
===
--- llvm/test/Transforms/InstCombine/fsh.ll
+++ llvm/test/Transforms/InstCombine/fsh.ll
@@ -440,12 +440,10 @@
   ret <2 x i32> %r
 }
 
-; TODO: Don't let SimplifyDemandedBits split up a rotate - keep the same operand.
-
 define i32 @rotl_common_demanded(i32 %a0) {
 ; CHECK-LABEL: @rotl_common_demanded(
 ; CHECK-NEXT:[[X:%.*]] = xor i32 [[A0:%.*]], 2
-; CHECK-NEXT:[[R:%.*]] = call i32 @llvm.fshl.i32(i32 [[X]], i32 [[A0]], i32 8)
+; CHECK-NEXT:[[R:%.*]] = call i32 @llvm.fshl.i32(i32 [[X]], i32 [[X]], i32 8)
 ; CHECK-NEXT:ret i32 [[R]]
 ;
   %x = xor i32 %a0, 2
@@ -456,7 +454,7 @@
 define i33 @rotr_common_demanded(i33 %a0) {
 ; CHECK-LABEL: @rotr_common_demanded(
 ; CHECK-NEXT:[[X:%.*]] = xor i33 [[A0:%.*]], 2
-; CHECK-NEXT:[[R:%.*]] = call i33 @llvm.fshl.i33(i33 [[X]], i33 [[A0]], i33 25)
+; CHECK-NEXT:[[R:%.*]] = call i33 @llvm.fshl.i33(i33 [[X]], i33 [[X]], i33 25)
 ; CHECK-NEXT:ret i33 [[R]]
 ;
   %x = xor i33 %a0, 2
@@ -662,7 +660,8 @@
 
 define i32 @fshl_mask_args_same1(i32 %a) {
 ; CHECK-LABEL: @fshl_mask_args_same1(
-; CHECK-NEXT:[[T2:%.*]] = lshr i32 [[A:%.*]], 16
+; CHECK-NEXT:[[T1:%.*]] = and i32 [[A:%.*]], -65536
+; CHECK-NEXT:[[T2:%.*]] = call i32 @llvm.fshl.i32(i32 [[T1]], i32 [[T1]], i32 16)
 ; CHECK-NEXT:ret i32 [[T2]]
 ;
   %t1 = and i32 %a, 4294901760 ; 0x
@@ -718,7 +717,7 @@
 define <2 x i32> @fshr_mask_args_same_vector2(<2 x i32> %a, <2 x i32> %b) {
 ; CHECK-LABEL: @fshr_mask_args_same_vector2(
 ; CHECK-NEXT:[[T1:%.*]] = and <2 x i32> [[A:%.*]], 
-; CHECK-NEXT:[[T3:%.*]] = lshr exact <2 x i32> [[T1]], 
+; CHECK-NEXT:[[T3:%.*]] = call <2 x i32> @llvm.fshl.v2i32(<2 x i32> [[T1]], <2 x i32> [[T1]], <2 x i32> )
 ; CHECK-NEXT:ret <2 x i32> [[T3]]
 ;
   %t1 = and <2 x i32> %a, 
Index: llvm/test/CodeGen/WebAssembly/rotate-i3264.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/rotate-i3264.ll
@@ -0,0 +1,46 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 2
+; RUN: sed 's/iX/i32/g' %s | llc --mtriple=wasm32-unknown-unknown | FileCheck --check-prefix=I32 %s
+; RUN: sed 's/iX/i64/g' %s | llc --mtriple=wasm64-unknown-unknown | FileCheck --check-prefix=I64 %s
+
+declare iX @llvm.fshl.iX(iX, iX, iX)
+declare iX @llvm.fshr.iX(iX, iX, iX)
+
+define iX @testLeft(iX noundef %0, iX noundef %1) {
+; I32-LABEL: testLeft:
+; I32: .functype testLeft (i32, i32) -> (i32)
+; I32-NEXT:  # %bb.0:
+; I32-NEXT:local.get 0
+; I32-NEXT:local.get 1
+; I32-NEXT:i32.rotl
+; I32-NEXT:# fallthrough-return
+;
+; I64-LABEL: testLeft:
+; I64: .functype testLeft (i64, i64) -> (i64)
+; I64-NEXT:  # %bb.0:
+; I64-NEXT:local.get 0
+; I64-NEXT:local.get 1
+; I64-NEXT:i64.rotl
+; I64-NEXT:# fallthrough-return
+  %3 = call iX @llvm.fshl.iX(iX %0, iX %0, iX %1)
+  ret iX %3
+}
+
+define iX @testRight(iX noundef %0, iX noundef %1) {
+; I32-LABEL: testRight:
+; I32: .functype testRight (i32, i32) -> (i32)
+; I32-NEXT:  # %bb.0:
+; I32-NEXT:local.get 0
+; I32-NEXT:local.get 1
+; I32-NEXT:i32.rotr
+; I32-NEXT:# fallthrough-return
+;
+; I64-LABEL: testRight:
+; I64: .functype testRight (i64, i64) -> (i64)
+; I64-NEXT:  # %bb.0:
+; I64-NEXT:local.get 0
+; I64-NEXT:local.get 1
+; I64-NEXT:i64.rotr
+; I64-NEXT:# fallthrough-return
+  %3 = call iX @llvm.fshr.iX(iX %0, iX %0, iX %1)
+  ret iX %3
+}
Index: llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
===
--- llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
@@ -924,11 +924,13 @@
 if (II->getIntrinsicID() == Intrinsic::fshr)
   ShiftAmt = BitWidth - ShiftAmt;
 
-APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
-APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
-if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
-SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
-  return I;
+if (I->getOperand(0) != I->getOperan

[PATCH] D150670: [WebAssembly] Disable generation of fshl/fshr for rotates

2023-05-26 Thread Nikita Popov via Phabricator via cfe-commits
nikic added inline comments.



Comment at: llvm/test/Transforms/InstCombine/fsh.ll:664
+; CHECK-NEXT:[[T1:%.*]] = and i32 [[A:%.*]], -65536
+; CHECK-NEXT:[[T2:%.*]] = call i32 @llvm.fshl.i32(i32 [[T1]], i32 [[T1]], 
i32 16)
 ; CHECK-NEXT:ret i32 [[T2]]

We still want to simplify this case. Could possibly be done by checking whether 
all demanded bits are zero for one of the operands in the rotate case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150670

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


[PATCH] D150670: [WebAssembly] Disable generation of fshl/fshr for rotates

2023-05-26 Thread Paulo Matos via Phabricator via cfe-commits
pmatos added inline comments.



Comment at: llvm/test/Transforms/InstCombine/fsh.ll:664
+; CHECK-NEXT:[[T1:%.*]] = and i32 [[A:%.*]], -65536
+; CHECK-NEXT:[[T2:%.*]] = call i32 @llvm.fshl.i32(i32 [[T1]], i32 [[T1]], 
i32 16)
 ; CHECK-NEXT:ret i32 [[T2]]

nikic wrote:
> We still want to simplify this case. Could possibly be done by checking 
> whether all demanded bits are zero for one of the operands in the rotate case.
Ah, yes,  right. That should be just a simple shift right. Will see how to 
still allow that change. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150670

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


[PATCH] D151342: [Clang] Correctly handle generic lambda used as default template argument.

2023-05-26 Thread Corentin Jabot via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG75cd8cdbde45: [Clang] Correctly handle generic lambda used 
as default template argument. (authored by cor3ntin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151342

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Parse/ParseTemplate.cpp
  clang/test/SemaCXX/cxx2a-template-lambdas.cpp


Index: clang/test/SemaCXX/cxx2a-template-lambdas.cpp
===
--- clang/test/SemaCXX/cxx2a-template-lambdas.cpp
+++ clang/test/SemaCXX/cxx2a-template-lambdas.cpp
@@ -43,3 +43,30 @@
 }
 static_assert(outer() == 123);
 template int *outer(); // expected-note {{in instantiation}}
+
+
+namespace GH62611 {
+template 
+struct C {
+  static constexpr auto B = A;
+};
+
+int test() {
+  C<>::B(42);
+}
+
+namespace AutoParam
+{
+template 
+auto B = A;
+static_assert(B<>(42) == 42);
+}
+
+namespace TypeParam
+{
+template 
+auto B = T{};
+static_assert(B<>(42) == 42);
+}
+
+}
Index: clang/lib/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -841,10 +841,17 @@
   // we introduce the type parameter into the local scope.
   SourceLocation EqualLoc;
   ParsedType DefaultArg;
-  if (TryConsumeToken(tok::equal, EqualLoc))
+  if (TryConsumeToken(tok::equal, EqualLoc)) {
+// The default argument may declare template parameters, notably
+// if it contains a generic lambda, so we need to increase
+// the template depth as these parameters would not be instantiated
+// at the current level.
+TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
+++CurTemplateDepthTracker;
 DefaultArg =
 ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
 .get();
+  }
 
   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
   TypenameKeyword, EllipsisLoc,
@@ -1030,6 +1037,14 @@
   //   end of the template-parameter-list rather than a greater-than
   //   operator.
   GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
+
+  // The default argument may declare template parameters, notably
+  // if it contains a generic lambda, so we need to increase
+  // the template depth as these parameters would not be instantiated
+  // at the current level.
+  TemplateParameterDepthRAII CurTemplateDepthTracker(
+  TemplateParameterDepth);
+  ++CurTemplateDepthTracker;
   EnterExpressionEvaluationContext ConstantEvaluated(
   Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   DefaultArg =
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -507,6 +507,8 @@
   (`#114 `_)
 - Fix parsing of `auto(x)`, when it is surrounded by parentheses.
   (`#62494 `_)
+- Fix handling of generic lambda used as template arguments.
+  (`#62611 `_)
 
 Bug Fixes to AST Handling
 ^


Index: clang/test/SemaCXX/cxx2a-template-lambdas.cpp
===
--- clang/test/SemaCXX/cxx2a-template-lambdas.cpp
+++ clang/test/SemaCXX/cxx2a-template-lambdas.cpp
@@ -43,3 +43,30 @@
 }
 static_assert(outer() == 123);
 template int *outer(); // expected-note {{in instantiation}}
+
+
+namespace GH62611 {
+template 
+struct C {
+  static constexpr auto B = A;
+};
+
+int test() {
+  C<>::B(42);
+}
+
+namespace AutoParam
+{
+template 
+auto B = A;
+static_assert(B<>(42) == 42);
+}
+
+namespace TypeParam
+{
+template 
+auto B = T{};
+static_assert(B<>(42) == 42);
+}
+
+}
Index: clang/lib/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -841,10 +841,17 @@
   // we introduce the type parameter into the local scope.
   SourceLocation EqualLoc;
   ParsedType DefaultArg;
-  if (TryConsumeToken(tok::equal, EqualLoc))
+  if (TryConsumeToken(tok::equal, EqualLoc)) {
+// The default argument may declare template parameters, notably
+// if it contains a generic lambda, so we need to increase
+// the template depth as these parameters would not be instantiated
+// at the current level.
+TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
+++CurTemplateDepthTracker;
 DefaultArg =
 ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
 .get();
+  }
 
   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCu

[clang] 75cd8cd - [Clang] Correctly handle generic lambda used as default template argument.

2023-05-26 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2023-05-26T16:04:10+02:00
New Revision: 75cd8cdbde45d07800d5cefa6f7a213271245e4a

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

LOG: [Clang] Correctly handle generic lambda used as default template argument.

Adjust the template pparameter depth when parsing default
template arguments as they may introduce generic lambda whose parameters
are not substituted at the same depth.

Fixes #62611

Reviewed By: erichkeane, #clang-language-wg

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Parse/ParseTemplate.cpp
clang/test/SemaCXX/cxx2a-template-lambdas.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f1cc205c4a430..4387f9b3145be 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -507,6 +507,8 @@ Bug Fixes to C++ Support
   (`#114 `_)
 - Fix parsing of `auto(x)`, when it is surrounded by parentheses.
   (`#62494 `_)
+- Fix handling of generic lambda used as template arguments.
+  (`#62611 `_)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index 964d985b6b6e6..79f4ab683281e 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -841,10 +841,17 @@ NamedDecl *Parser::ParseTypeParameter(unsigned Depth, 
unsigned Position) {
   // we introduce the type parameter into the local scope.
   SourceLocation EqualLoc;
   ParsedType DefaultArg;
-  if (TryConsumeToken(tok::equal, EqualLoc))
+  if (TryConsumeToken(tok::equal, EqualLoc)) {
+// The default argument may declare template parameters, notably
+// if it contains a generic lambda, so we need to increase
+// the template depth as these parameters would not be instantiated
+// at the current level.
+TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
+++CurTemplateDepthTracker;
 DefaultArg =
 ParseTypeName(/*Range=*/nullptr, DeclaratorContext::TemplateTypeArg)
 .get();
+  }
 
   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
   TypenameKeyword, EllipsisLoc,
@@ -1030,6 +1037,14 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, 
unsigned Position) {
   //   end of the template-parameter-list rather than a greater-than
   //   operator.
   GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
+
+  // The default argument may declare template parameters, notably
+  // if it contains a generic lambda, so we need to increase
+  // the template depth as these parameters would not be instantiated
+  // at the current level.
+  TemplateParameterDepthRAII CurTemplateDepthTracker(
+  TemplateParameterDepth);
+  ++CurTemplateDepthTracker;
   EnterExpressionEvaluationContext ConstantEvaluated(
   Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   DefaultArg =

diff  --git a/clang/test/SemaCXX/cxx2a-template-lambdas.cpp 
b/clang/test/SemaCXX/cxx2a-template-lambdas.cpp
index 65baf29718f06..cc50292dbff48 100644
--- a/clang/test/SemaCXX/cxx2a-template-lambdas.cpp
+++ b/clang/test/SemaCXX/cxx2a-template-lambdas.cpp
@@ -43,3 +43,30 @@ constexpr T outer() {
 }
 static_assert(outer() == 123);
 template int *outer(); // expected-note {{in instantiation}}
+
+
+namespace GH62611 {
+template 
+struct C {
+  static constexpr auto B = A;
+};
+
+int test() {
+  C<>::B(42);
+}
+
+namespace AutoParam
+{
+template 
+auto B = A;
+static_assert(B<>(42) == 42);
+}
+
+namespace TypeParam
+{
+template 
+auto B = T{};
+static_assert(B<>(42) == 42);
+}
+
+}



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


[PATCH] D148723: [clang] Restrict Inline Builtin to non-static, non-odr linkage

2023-05-26 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 526059.
serge-sans-paille retitled this revision from "[clang] Fix comdat for 
InlineBuiltin declarations" to "[clang] Restrict Inline Builtin to non-static, 
non-odr linkage".
serge-sans-paille edited the summary of this revision.
serge-sans-paille added a comment.

Add a linkage check to further restrict what's an inline builtin.


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

https://reviews.llvm.org/D148723

Files:
  clang/lib/AST/Decl.cpp
  clang/test/CodeGen/inline-builtin-comdat.c


Index: clang/test/CodeGen/inline-builtin-comdat.c
===
--- /dev/null
+++ clang/test/CodeGen/inline-builtin-comdat.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-windows -S -emit-llvm -disable-llvm-passes 
%s -o - | FileCheck %s
+// Inline builtin are not supported for odr linkage
+// CHECK-NOT: .inline
+
+double __cdecl frexp( double _X, int* _Y);
+inline __attribute__((always_inline))  long double __cdecl frexpl( long double 
__x, int *__exp ) {
+  return (long double) frexp((double)__x, __exp );
+}
+
+long double pain(void)
+{
+long double f = 123.45;
+int i;
+long double f2 = frexpl(f, &i);
+return f2;
+}
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -3301,8 +3301,23 @@
 return false;
 
   const FunctionDecl *Definition;
-  return hasBody(Definition) && Definition->isInlineSpecified() &&
- Definition->hasAttr();
+  if (!hasBody(Definition))
+return false;
+
+  if (!Definition->isInlineSpecified() ||
+  !Definition->hasAttr())
+return false;
+
+  ASTContext &Context = getASTContext();
+  switch (Context.GetGVALinkageForFunction(this)) {
+  case GVA_Internal:
+  case GVA_DiscardableODR:
+  case GVA_StrongODR:
+return false;
+  case GVA_AvailableExternally:
+  case GVA_StrongExternal:
+return true;
+  }
 }
 
 bool FunctionDecl::isDestroyingOperatorDelete() const {


Index: clang/test/CodeGen/inline-builtin-comdat.c
===
--- /dev/null
+++ clang/test/CodeGen/inline-builtin-comdat.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-windows -S -emit-llvm -disable-llvm-passes %s -o - | FileCheck %s
+// Inline builtin are not supported for odr linkage
+// CHECK-NOT: .inline
+
+double __cdecl frexp( double _X, int* _Y);
+inline __attribute__((always_inline))  long double __cdecl frexpl( long double __x, int *__exp ) {
+  return (long double) frexp((double)__x, __exp );
+}
+
+long double pain(void)
+{
+long double f = 123.45;
+int i;
+long double f2 = frexpl(f, &i);
+return f2;
+}
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -3301,8 +3301,23 @@
 return false;
 
   const FunctionDecl *Definition;
-  return hasBody(Definition) && Definition->isInlineSpecified() &&
- Definition->hasAttr();
+  if (!hasBody(Definition))
+return false;
+
+  if (!Definition->isInlineSpecified() ||
+  !Definition->hasAttr())
+return false;
+
+  ASTContext &Context = getASTContext();
+  switch (Context.GetGVALinkageForFunction(this)) {
+  case GVA_Internal:
+  case GVA_DiscardableODR:
+  case GVA_StrongODR:
+return false;
+  case GVA_AvailableExternally:
+  case GVA_StrongExternal:
+return true;
+  }
 }
 
 bool FunctionDecl::isDestroyingOperatorDelete() const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp:159
+   anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
+ hasAnyReturnType(RetTypeVec)
   .bind("match";

Consider:

hasAnyReturnType -> 
`returns(hasCanonicalType(hasDeclaration(namedDecl(matchers::matchesAnyListedName(RetTypeVec`
Note that to use matchesAnyListedName, you should save RetTypeVec  as class 
member, just to be safe.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

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


[PATCH] D151517: Fix wrong error message when compiling C souce code

2023-05-26 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added a comment.

In D151517#4374583 , @ABataev wrote:

> Could you split it into 3 separate patch

Thanks Alexey!  Sure I am split into three.  Here is first one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151517

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


[PATCH] D151431: [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

2023-05-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 526063.
balazske marked an inline comment as done.
balazske added a comment.

Fixed the documentation issue.
Added tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151431

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UniquePtrArrayMismatchCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/unique-ptr-array-mismatch.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/unique-ptr-array-mismatch.cpp
@@ -0,0 +1,127 @@
+// RUN: %check_clang_tidy %s bugprone-unique-ptr-array-mismatch %t
+
+namespace std {
+
+template struct default_delete {};
+template struct default_delete {};
+
+template>
+class unique_ptr {
+public:
+  explicit unique_ptr(T* p) noexcept;
+  unique_ptr(T* p, Deleter d1 ) noexcept;
+};
+
+template 
+class unique_ptr {
+public:
+  template
+  explicit unique_ptr(U p) noexcept;
+  template
+  unique_ptr(U p, Deleter d1) noexcept;
+};
+
+} // namespace std
+
+struct A {};
+
+using PtrT = std::unique_ptr;
+using PtrTArr = std::unique_ptr;
+
+void f1() {
+  std::unique_ptr P1{new int};
+  std::unique_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P2{new int[10]};
+  // clang-format off
+  std::unique_ptr<  int  > P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr<  int[]  > P3{new int[10]};
+  // clang-format on
+  std::unique_ptr P4(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P4(new int[10]);
+  new std::unique_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  std::unique_ptr P5(new int[10]);
+
+  A deleter;
+  std::unique_ptr P6(new int[10], deleter);
+  std::unique_ptr P7(new int[10]);
+  std::default_delete def_del;
+  std::unique_ptr> P8(new int[10], def_del);
+
+  new PtrT(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  new PtrTArr(new A[10]);
+}
+
+void f2() {
+  std::unique_ptr P1(new A);
+  std::unique_ptr P2(new A[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P2(new A[10]);
+  std::unique_ptr P3(new A[10]);
+}
+
+void f3() {
+  std::unique_ptr P1{new int}, P2{new int[10]}, P3{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-MESSAGES: :[[@LINE-2]]:57: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+struct S {
+  std::unique_ptr P1;
+  std::unique_ptr P2{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  std::unique_ptr P3{new int}, P4{new int[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  S() : P1{new int[10]} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+};
+
+void f_parm(std::unique_ptr);
+
+void f4() {
+  f_parm(std::unique_ptr{new int[10]});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+std::unique_ptr f_ret() {
+  return std::unique_ptr(new int[10]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+}
+
+template 
+void f_tmpl() {
+  std::unique_ptr P1{new T[10]};
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: unique pointer to non-array is initialized with array [bugprone-unique-ptr-array-mismatch]
+  // CHECK-FIXES: std::unique_ptr P1{new T[10]};
+}
+
+void f5() {
+  f_tmpl();
+}
+
+tem

[PATCH] D148793: [WIP][clang-tidy] Implement an include-cleaner check.

2023-05-26 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 526064.
VitaNuo marked 13 inline comments as done.
VitaNuo added a comment.

Rework according to the review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148793

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clangd/TidyProvider.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/bar.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/baz.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/foo.h
  clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/private.h
  clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/system/string.h
  clang-tools-extra/test/clang-tidy/checkers/misc/system/vector.h
  clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
  clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
===
--- /dev/null
+++ clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -0,0 +1,159 @@
+#include "ClangTidyDiagnosticConsumer.h"
+#include "ClangTidyOptions.h"
+#include "ClangTidyTest.h"
+#include "misc/IncludeCleanerCheck.h"
+#include "gtest/gtest.h"
+
+#include 
+#include 
+
+using namespace clang::tidy::misc;
+
+namespace clang {
+namespace tidy {
+namespace test {
+
+TEST(IncludeCleanerCheckTest, BasicUnusedIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+#include 
+#include "bar.h"
+)";
+  const char *PostCode = "\n";
+
+  std::vector Errors;
+  EXPECT_EQ(PostCode, runCheckOnCode(
+  PreCode, &Errors, "file.cpp", std::nullopt,
+  ClangTidyOptions(), {{"bar.h", ""}, {"vector", ""}}));
+}
+
+TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+#include "foo/qux.h"
+#include 
+)";
+
+  std::vector Errors;
+  ClangTidyOptions Opts;
+  Opts.CheckOptions["IgnoreHeaders"] = "bar.h,foo/.*,vector";
+  EXPECT_EQ(PreCode, runCheckOnCode(
+ PreCode, &Errors, "file.cpp", std::nullopt, Opts,
+ {{"bar.h", ""}, {"vector", ""}, {"foo/qux.h", ""}}));
+}
+
+TEST(IncludeCleanerCheckTest, BasicMissingIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+
+int BarResult = bar();
+int BazResult = baz();
+)";
+  const char *PostCode = R"(
+#include "bar.h"
+#include "baz.h"
+
+int BarResult = bar();
+int BazResult = baz();
+)";
+
+  std::vector Errors;
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, &Errors, "file.cpp", std::nullopt, ClangTidyOptions(),
+{{"bar.h", R"(#pragma once
+  #include "baz.h"
+  int bar();
+   )"},
+ {"baz.h", R"(#pragma once
+  int baz();
+   )"}}));
+}
+
+TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
+  const char *PreCode = R"(
+#include "bar.h"
+
+int BarResult = bar();
+int BazResult = baz();
+int QuxResult = qux();
+)";
+
+  ClangTidyOptions Opts;
+  Opts.CheckOptions["IgnoreHeaders"] = "baz.h,foo/.*";
+  std::vector Errors;
+  EXPECT_EQ(PreCode, runCheckOnCode(
+ PreCode, &Errors, "file.cpp", std::nullopt, Opts,
+ {{"bar.h", R"(#pragma once
+  #include "baz.h"
+  #include "foo/qux.h"
+  int bar();
+   )"},
+  {"baz.h", R"(#pragma once
+  int baz();
+   )"},
+  {"foo/qux.h", R"(#pragma once
+  int qux();
+   )"}}));
+}
+
+TEST(IncludeCleanerCheckTest, SystemMissingIncludes) {
+  const char *PreCode = R"(
+#include 
+
+std::string HelloString;
+std::vector Vec;
+)";
+  const char *PostCode = R"(
+#include 
+#include 
+
+std::string HelloString;
+std::vector Vec;
+)";
+
+  std::vector Errors;
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, &Errors, "file.cpp", std::nullopt, ClangTidyOptions(),
+{{"string", R"(#pragma once
+  namespace std { class string {}; }
+)"},
+

[PATCH] D151431: [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

2023-05-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

The case of fully dependent type (`unique_ptr`) is not working in this 
checker and likely not in `SharedPtrArrayMismatchCheck`. I can fix this in a 
next patch (for both checkers).
Maybe we can remove the warning in all cases when the type is a POD type (or 
add a check option)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151431

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


[PATCH] D151517: Fix wrong error message when compiling C souce code

2023-05-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151517

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


[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added inline comments.



Comment at: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h:186-202
+/// Additionally, you can use:
+///
+/// \code
+///   // expected-maybe-no-diagnostics
+/// \endcode
+///
+/// to specify that a file with no "expected-*" comments should pass when no

Thanks for adding documentation.

I feel that this edit makes the behavior a little clearer, and it clarifies 
what happens when "expected-no-diagnostics" and "expected-maybe-no-diagnostics" 
are combined.

Also, the original text had:

> but they do not fail automatically due to a combination of 
> "expected-no-diagnostics" and "expected-*" within the same test

That reads to me like it's ok to combine "expected-no-diagnostics" and 
"expected-*" directives specifying diagnostics.  Hopefully this edit clarifies 
that point.




Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:470-471
   NoDiag = true;
   if (D.RegexKind)
 continue;
 }

Shouldn't `expected-maybe-no-diagnostics` have this too so that 
`expected-maybe-no-diagnostics-re` is skipped?  Please add a test.



Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:468
+Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
+  continue;
+} else if (DToken.endswith(DType="-no-diagnostics")) {

Endill wrote:
> jdenny wrote:
> > This `continue` skips the prefix checking below, which is important when 
> > there are multiple prefixes active (e.g., `-verify=foo,bar`).  That is, any 
> > old `BOGUS-maybe-no-diagnostics` will be effective then.
> This should be fixed now. Thank you for spotting this!
Thanks for the fix.  Please add a test so this bug doesn't pop up again.



Comment at: clang/test/Frontend/verify-maybe-no-diagnostics.c:104
+//  D6-CHECK: error: 'error' diagnostics seen but not expected:
+// D6-CHECK-NEXT:   {{.*}} 'expected-no-diagnostics' directive cannot follow 
other expected directives
+// D6-CHECK-NEXT: 1 error generated.

Endill wrote:
> jdenny wrote:
> > This diagnostic is confusing.  Should we add "except 
> > 'expected-maybe-no-diagnostics'"?
> As I mentioned in another comment, `maybe-no-diagnostics` has the lowest 
> priority, and doesn't have strict and declarative nature, unlike any other 
> directive. That's why it should never be expected (and ideally very rarely 
> used).
> 
> The purpose of all the tests I added is to ensure `expected-no-diagnostic` 
> doesn't affect existing directives and their interaction in any way.
I don't see how that addresses my concern.  Maybe it's because, after the 
latest edits, phab shifted my comment to the wrong test.  I was originally 
commenting on this:

> 'expected-no-diagnostics' directive cannot follow other expected directives

This message is now incorrect.  `expected-no-diagnostics` //can// follow 
`expected-maybe-no-diagnostics`.  What if we reword as follows?

> 'expected-no-diagnostics' directive cannot follow directives that expect 
> diagnostics


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

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


[PATCH] D151515: [CodeGen] add additional cast when checking call arguments

2023-05-26 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Thank you for the patch! Please apply clang-format at least one of pre-commit 
failures is due to that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151515

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


[PATCH] D151477: [clang][ExtractAPI] Refactor serializer to the CRTP

2023-05-26 Thread Daniel Grumberg via Phabricator via cfe-commits
dang added a comment.

LGTM with minor changes




Comment at: clang/include/clang/ExtractAPI/Serialization/SerializerBase.h:58
 
-  virtual ~APISerializer() = default;
 };

It would be nice to keep this as default, i.e. 
```
~APISetVisitor() = default;
```



Comment at: 
clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h:20
 
-#include "clang/ExtractAPI/API.h"
 #include "clang/ExtractAPI/APIIgnoresList.h"

In LLVM we tend to explicitly include any header we use and we definitely use 
the definitions ins API.h



Comment at: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp:748
 
-void SymbolGraphSerializer::serializeSingleRecord(const APIRecord *Record) {
+void SymbolGraphSerializer::visitSingleRecord(const APIRecord *Record) {
   switch (Record->getKind()) {

This isn't part of the visitation scheme but more of a way of serializing a 
single record. I would prefer to keep this as `serializeSingleRecord` 



Comment at: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp:808
 Object SymbolGraphSerializer::serialize() {
-  // Serialize global variables in the API set.
-  for (const auto &GlobalVar : API.getGlobalVariables())
-serializeGlobalVariableRecord(*GlobalVar.second);
-
-  for (const auto &GlobalFunction : API.getGlobalFunctions())
-serializeGlobalFunctionRecord(*GlobalFunction.second);
-
-  // Serialize enum records in the API set.
-  for (const auto &Enum : API.getEnums())
-serializeEnumRecord(*Enum.second);
-
-  // Serialize struct records in the API set.
-  for (const auto &Struct : API.getStructs())
-serializeStructRecord(*Struct.second);
-
-  // Serialize Objective-C interface records in the API set.
-  for (const auto &ObjCInterface : API.getObjCInterfaces())
-serializeObjCContainerRecord(*ObjCInterface.second);
-
-  // Serialize Objective-C protocol records in the API set.
-  for (const auto &ObjCProtocol : API.getObjCProtocols())
-serializeObjCContainerRecord(*ObjCProtocol.second);
-
-  for (const auto &Macro : API.getMacros())
-serializeMacroDefinitionRecord(*Macro.second);
-
-  for (const auto &Typedef : API.getTypedefs())
-serializeTypedefRecord(*Typedef.second);
-
+  APISetVisitor::traverseAPISet();
   return serializeCurrentGraph();

Does this need to be explicit like this? Would it not work to just call 
`traverseAPISet();` since we would inherit it through inheritance.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151477

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


[PATCH] D150913: [Clang][BFloat16] Upgrade __bf16 to arithmetic type, change mangling, and extend excess precision support.

2023-05-26 Thread M. Zeeshan Siddiqui via Phabricator via cfe-commits
codemzs updated this revision to Diff 526072.
codemzs marked an inline comment as done.
codemzs set the repository for this revision to rG LLVM Github Monorepo.
codemzs added a comment.

Addresses @rjmccall suggestions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150913

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/FPOptions.def
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/Type.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/AMDGPU.h
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/Basic/Targets/X86.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CodeGen/X86/avx512bf16-error.c
  clang/test/CodeGen/X86/bfloat-mangle.cpp
  clang/test/CodeGen/X86/bfloat16.cpp
  clang/test/CodeGen/X86/fexcess-precision-bfloat16.c
  clang/test/CodeGenCUDA/amdgpu-bf16.cu
  clang/test/CodeGenCUDA/bf16.cu
  clang/test/Driver/fexcess-precision.c
  clang/test/Sema/arm-bf16-forbidden-ops.c
  clang/test/Sema/arm-bf16-forbidden-ops.cpp
  clang/test/Sema/arm-bfloat.cpp
  clang/test/SemaCUDA/amdgpu-bf16.cu
  clang/test/SemaCUDA/bf16.cu

Index: clang/test/SemaCUDA/bf16.cu
===
--- clang/test/SemaCUDA/bf16.cu
+++ clang/test/SemaCUDA/bf16.cu
@@ -2,32 +2,32 @@
 // REQUIRES: x86-registered-target
 
 // RUN: %clang_cc1 "-triple" "x86_64-unknown-linux-gnu" "-aux-triple" "nvptx64-nvidia-cuda" \
-// RUN:"-target-cpu" "x86-64" -fsyntax-only -verify=scalar %s
+// RUN:"-target-cpu" "x86-64" -fsyntax-only -verify=scalar -Wno-unused %s
 // RUN: %clang_cc1 "-aux-triple" "x86_64-unknown-linux-gnu" "-triple" "nvptx64-nvidia-cuda" \
-// RUN:-fcuda-is-device "-aux-target-cpu" "x86-64" -fsyntax-only -verify=scalar %s
+// RUN:-fcuda-is-device "-aux-target-cpu" "x86-64" -fsyntax-only -verify=scalar -Wno-unused %s
 
 #include "Inputs/cuda.h"
 
 __device__ void test(bool b, __bf16 *out, __bf16 in) {
   __bf16 bf16 = in; // No error on using the type itself.
 
-  bf16 + bf16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
-  bf16 - bf16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
-  bf16 * bf16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
-  bf16 / bf16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__bf16')}}
+  bf16 + bf16;
+  bf16 - bf16;
+  bf16 * bf16;
+  bf16 / bf16;
 
   __fp16 fp16;
 
-  bf16 + fp16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
-  fp16 + bf16; // scalar-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
-  bf16 - fp16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
-  fp16 - bf16; // scalar-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
-  bf16 * fp16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
-  fp16 * bf16; // scalar-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
-  bf16 / fp16; // scalar-error {{invalid operands to binary expression ('__bf16' and '__fp16')}}
-  fp16 / bf16; // scalar-error {{invalid operands to binary expression ('__fp16' and '__bf16')}}
+  bf16 + fp16;
+  fp16 + bf16;
+  bf16 - fp16;
+  fp16 - bf16;
+  bf16 * fp16;
+  fp16 * bf16;
+  bf16 / fp16;
+  fp16 / bf16;
   bf16 = fp16; // scalar-error {{assigning to '__bf16' from incompatible type '__fp16'}}
   fp16 = bf16; // scalar-error {{assigning to '__fp16' from incompatible type '__bf16'}}
-  bf16 + (b ? fp16 : bf16); // scalar-error {{incompatible operand types ('__fp16' and '__bf16')}}
+  bf16 + (b ? fp16 : bf16);
   *out = bf16;
 }
Index: clang/test/SemaCUDA/amdgpu-bf16.cu
===
--- clang/test/SemaCUDA/amdgpu-bf16.cu
+++ clang/test/SemaCUDA/amdgpu-bf16.cu
@@ -1,13 +1,8 @@
 // REQUIRES: amdgpu-registered-target
 // REQUIRES: x86-registered-target
 
-// RUN: %clang_cc1 "-triple" "x86_64-unknown-linux-gnu" "-aux-triple" "amdgcn-amd-amdhsa"\
-// RUN:"-target-cpu" "x86-64" -fsyntax-only -verify=amdgcn %s
-// RUN: %clang_cc1 "-aux-triple" "x86_64-unknown-linux-gnu" "-triple" "amdgcn-amd-amdhsa"\
-// RUN:-fcuda-is-device "-aux-target-cpu" "x86-64" -fsyntax-only -verify=amdgcn %s
-
 // RUN: %clang_cc1 "-aux-triple" "x86_64-unknown-linux-gnu" "-triple" "r600-unknown-unknown"\
-// RUN:-fcuda-is-device "-aux-target-cpu" "x86-64" -fsyntax-only -verify=amdgcn,r600 %s
+// RUN:-fcuda-is-device "-aux-target-cpu" "x86-64" -fsyntax-only -verif

[PATCH] D151431: [clang-tidy] Add check bugprone-unique-ptr-array-mismatch.

2023-05-26 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.

In D151431#4376181 , @balazske wrote:

> Maybe we can remove the warning in all cases when the type is a POD type (or 
> add a check option)?

**Leave it... **From a user perspective, it doesn't mater if type is POD or not.
I was mentioning non POD just because this is one of "undefined behavior" that 
sometimes is well defined.
But you don't know if project isn't using some custom new[]/delete[]




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unique-ptr-array-mismatch.rst:24
+  std::unique_ptr x(new Foo[10]); // -> std::unique_ptr x(new 
Foo[10]);
+  // ^ warning: unique pointer to non-array is initialized 
with array [bugprone-unique-ptr-array-mismatch]
+  std::unique_ptr x1(new Foo), x2(new Foo[10]); // no replacement

remove check name from comment to make it shorter


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151431

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


[PATCH] D150221: Add option -fkeep-static-variables to emit all static variables

2023-05-26 Thread Zheng Qian via Phabricator via cfe-commits
qianzhen updated this revision to Diff 526090.
qianzhen added a comment.

Update the option text to be more descriptive


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150221

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/keep-static-variables.cpp

Index: clang/test/CodeGen/keep-static-variables.cpp
===
--- /dev/null
+++ clang/test/CodeGen/keep-static-variables.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fkeep-static-variables -emit-llvm %s -o - -triple=x86_64-unknown-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-ELF
+// RUN: %clang_cc1 -fkeep-static-variables -emit-llvm %s -o - -triple=powerpc64-ibm-aix-xcoff | FileCheck %s --check-prefixes=CHECK,CHECK-NON-ELF
+
+// CHECK: @_ZL2g1 = internal global i32 0, align 4
+// CHECK: @_ZL2g2 = internal global i32 1, align 4
+// CHECK: @_ZL2g3 = internal global i32 0, align 4
+// CHECK: @_ZL2g4 = internal global i32 2, align 4
+// CHECK-ELF: @llvm.compiler.used = appending global [4 x ptr] [ptr @_ZL2g1, ptr @_ZL2g2, ptr @_ZL2g3, ptr @_ZL2g4], section "llvm.metadata"
+// CHECK-NON-ELF: @llvm.used = appending global [4 x ptr] [ptr @_ZL2g1, ptr @_ZL2g2, ptr @_ZL2g3, ptr @_ZL2g4], section "llvm.metadata"
+
+static int g1;
+static int g2 = 1;
+static int g3;
+static int g4 = 2;
+
+int test1() {
+  g1 = 3;
+  return g1;
+}
+
+int test2() {
+  return g2;
+}
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7294,6 +7294,8 @@
 
   Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
 options::OPT_fno_keep_static_consts);
+  Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_variables,
+options::OPT_fno_keep_static_variables);
   Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
 options::OPT_fno_complete_member_pointers);
   Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -2198,10 +2198,11 @@
   if (D && D->hasAttr())
 addUsedOrCompilerUsedGlobal(GV);
 
-  if (CodeGenOpts.KeepStaticConsts && D && isa(D)) {
-const auto *VD = cast(D);
-if (VD->getType().isConstQualified() &&
-VD->getStorageDuration() == SD_Static)
+  if (D && isa(D)) {
+const auto *VD = dyn_cast(D);
+if (VD->getStorageDuration() == SD_Static &&
+(CodeGenOpts.KeepStaticVariables ||
+ (CodeGenOpts.KeepStaticConsts && VD->getType().isConstQualified(
   addUsedOrCompilerUsedGlobal(GV);
   }
 }
@@ -3084,12 +3085,11 @@
   if (LangOpts.EmitAllDecls)
 return true;
 
-  if (CodeGenOpts.KeepStaticConsts) {
-const auto *VD = dyn_cast(Global);
-if (VD && VD->getType().isConstQualified() &&
-VD->getStorageDuration() == SD_Static)
-  return true;
-  }
+  const auto *VD = dyn_cast(Global);
+  if (VD && VD->getStorageDuration() == SD_Static &&
+  (CodeGenOpts.KeepStaticVariables ||
+   (CodeGenOpts.KeepStaticConsts && VD->getType().isConstQualified(
+return true;
 
   return getContext().DeclMustBeEmitted(Global);
 }
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1697,6 +1697,10 @@
   CodeGenOpts<"KeepStaticConsts">, DefaultFalse,
   PosFlag, NegFlag,
   BothFlags<[NoXarchOption], " static const variables if unused">>;
+defm keep_static_variables : BoolFOption<"keep-static-variables",
+  CodeGenOpts<"KeepStaticVariables">, DefaultFalse,
+  PosFlag, NegFlag,
+  BothFlags<[NoXarchOption], " keeping all static variables to guarantee that they can be directly addressed">>;
 defm fixed_point : BoolFOption<"fixed-point",
   LangOpts<"FixedPoint">, DefaultFalse,
   PosFlag, NegFlag,
Index: clang/include/clang/Basic/CodeGenOptions.def
===
--- clang/include/clang/Basic/CodeGenOptions.def
+++ clang/include/clang/Basic/CodeGenOptions.def
@@ -472,6 +472,9 @@
 /// Whether to emit unused static constants.
 CODEGENOPT(KeepStaticConsts, 1, 0)
 
+/// Whether to emit all static variables.
+CODEGENOPT(KeepStaticVariables, 1, 0)
+
 /// Whether to follow the AAPCS enforcing at least one read before storing to a volatile bitfield
 CODEGENOPT(ForceAAPCSBitfieldLoad, 1, 0)
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mai

[PATCH] D144654: [Lex] Warn when defining or undefining any builtin macro

2023-05-26 Thread Nathan Chancellor via Phabricator via cfe-commits
nathanchance added subscribers: nickdesaulniers, nathanchance.
nathanchance added a comment.

For what it's worth, this change is quite noisy for the Linux kernel, as there 
are certain macros undefined in header files that are included in many other 
headers. Additionally, at least one new instance is in a UAPI header, so it 
cannot be changed to my knowledge (honestly, all of these appear to be 
intentional, so I am not sure any of them should be changed). Is there any way 
for us to opt out of this? It would be a shame if we had to outright disable 
`-Wbuiltin-macro-redefined`, it has caught issues before (the kernel is 
generally against opting out on a per-location basis but does have the 
infrastructure to do so, not sure if it will be available for all these 
locations though...).

`arch/arm/include/uapi/asm/types.h`: 
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/arm/include/uapi/asm/types.h?h=v6.4-rc3

  In file included from scripts/mod/devicetable-offsets.c:3:
  In file included from include/linux/mod_devicetable.h:12:
  In file included from include/uapi/linux/mei.h:10:
  In file included from include/uapi/linux/mei_uuid.h:12:
  In file included from include/linux/types.h:6:
  In file included from include/uapi/linux/types.h:5:
  arch/arm/include/uapi/asm/types.h:27:8: error: undefining builtin macro 
[-Werror,-Wbuiltin-macro-redefined]
  #undef __INT32_TYPE__
 ^
  arch/arm/include/uapi/asm/types.h:32:8: error: undefining builtin macro 
[-Werror,-Wbuiltin-macro-redefined]
  #undef __UINT32_TYPE__
 ^
  arch/arm/include/uapi/asm/types.h:37:8: error: undefining builtin macro 
[-Werror,-Wbuiltin-macro-redefined]
  #undef __UINTPTR_TYPE__
 ^
  3 errors generated.

`arch/arm64/include/asm/neon-intrinsics.h`: 
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/arm64/include/asm/neon-intrinsics.h?h=v6.4-rc3

  In file included from arch/arm64/lib/xor-neon.c:11:
  arch/arm64/include/asm/neon-intrinsics.h:18:8: error: undefining builtin 
macro [-Werror,-Wbuiltin-macro-redefined]
  #undef __INT64_TYPE__
 ^
  arch/arm64/include/asm/neon-intrinsics.h:23:8: error: undefining builtin 
macro [-Werror,-Wbuiltin-macro-redefined]
  #undef __UINT64_TYPE__
 ^
  2 errors generated.

`include/linux/drbd_genl_api.h` (this may be unnecessary now?): 
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/drbd_genl_api.h?h=v6.4-rc3

  In file included from drivers/block/drbd/drbd_debugfs.c:11:
  In file included from drivers/block/drbd/drbd_int.h:35:
  include/linux/drbd_genl_api.h:47:8: error: undefining builtin macro 
[-Werror,-Wbuiltin-macro-redefined]
  #undef linux
 ^
  1 error generated.

`arch/mips/kernel/vmlinux.lds.S` (there is little context available as to why 
this exists): 
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/mips/kernel/vmlinux.lds.S?h=v6.4-rc3

  In file included from :357:
  :6:8: error: undefining builtin macro 
[-Werror,-Wbuiltin-macro-redefined]
  #undef mips
 ^
  1 error generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144654

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


[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill updated this revision to Diff 526101.
Endill added a comment.

Address feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
  clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
  clang/test/Frontend/verify-maybe-no-diagnostics.c
  clang/test/Frontend/verify3.c

Index: clang/test/Frontend/verify3.c
===
--- clang/test/Frontend/verify3.c
+++ clang/test/Frontend/verify3.c
@@ -19,7 +19,7 @@
 // expected-no-diagnostics
 
 //  CHECK2: error: 'error' diagnostics seen but not expected:
-// CHECK2-NEXT:   Line 19: 'expected-no-diagnostics' directive cannot follow other expected directives
+// CHECK2-NEXT:   Line 19: 'expected-no-diagnostics' directive cannot follow directives that expect diagnostics
 // CHECK2-NEXT: 1 error generated.
 #endif
 
Index: clang/test/Frontend/verify-maybe-no-diagnostics.c
===
--- /dev/null
+++ clang/test/Frontend/verify-maybe-no-diagnostics.c
@@ -0,0 +1,142 @@
+// RUN: %clang_cc1 -DTEST_A1 -verify %s
+// RUN: not %clang_cc1 -DTEST_A2 -verify %s 2>&1 | FileCheck --check-prefix=A2-CHECK %s
+// RUN: not %clang_cc1 -DTEST_A3 -verify %s 2>&1 | FileCheck --check-prefix=A3-CHECK %s
+// RUN: %clang_cc1 -DTEST_B1 -verify %s
+// RUN: %clang_cc1 -DTEST_B2 -verify %s
+// RUN: %clang_cc1 -DTEST_C1 -verify %s
+// RUN: not %clang_cc1 -DTEST_C2 -verify %s 2>&1 | FileCheck --check-prefix=C2-CHECK %s
+// RUN: %clang_cc1 -DTEST_C3 -verify %s
+// RUN: not %clang_cc1 -DTEST_C4 -verify %s 2>&1 | FileCheck --check-prefix=C4-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D1 -verify %s 2>&1 | FileCheck --check-prefix=D1-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D2 -verify %s 2>&1 | FileCheck --check-prefix=D2-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D3 -verify %s 2>&1 | FileCheck --check-prefix=D3-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D4 -verify %s 2>&1 | FileCheck --check-prefix=D4-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D5 -verify %s 2>&1 | FileCheck --check-prefix=D5-CHECK %s
+// RUN: not %clang_cc1 -DTEST_D6 -verify %s 2>&1 | FileCheck --check-prefix=D6-CHECK %s
+
+#ifdef TEST_A1
+// expected-maybe-no-diagnostics
+#endif
+
+#ifdef TEST_A2
+// BOGUS-maybe-no-diagnostics
+
+//  A2-CHECK: error: no expected directives found: consider use of 'expected-no-diagnostics'
+// A2-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_A3
+// expected-maybe-no-diagnostics-re
+
+//  A3-CHECK: error: no expected directives found: consider use of 'expected-no-diagnostics'
+// A3-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_B1
+// expected-maybe-no-diagnostics
+// expected-no-diagnostics
+#endif
+
+#ifdef TEST_B2
+// expected-no-diagnostics
+// expected-maybe-no-diagnostics
+#endif
+
+#ifdef TEST_C1
+// expected-maybe-no-diagnostics
+#error test_c1
+// expected-error@-1 {{test_c1}}
+#endif
+
+#ifdef TEST_C2
+// expected-maybe-no-diagnostics
+#error test_c2
+
+//  C2-CHECK: error: 'error' diagnostics seen but not expected:
+// C2-CHECK-NEXT:   {{test_c2}}
+// C2-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_C3
+#error test_c3
+// expected-error@-1 {{test_c3}}
+// expected-maybe-no-diagnostics
+#endif
+
+#ifdef TEST_C4
+#error test_c4
+// expected-maybe-no-diagnostics
+
+//  C4-CHECK: error: 'error' diagnostics seen but not expected:
+// C4-CHECK-NEXT:   {{test_c4}}
+// C4-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_D1
+// expected-maybe-no-diagnostics
+#error test_d1
+// expected-error@-1 {{test_d1}}
+// expected-no-diagnostics
+
+//  D1-CHECK: error: 'error' diagnostics seen but not expected:
+// D1-CHECK-NEXT:   {{.*}} 'expected-no-diagnostics' directive cannot follow directives that expect diagnostics
+// D1-CHECK-NEXT: 1 error generated.
+#endif
+
+#ifdef TEST_D2
+// expected-maybe-no-diagnostics
+// expected-no-diagnostics
+#error test_d2
+// expected-error@-1 {{test_d2}}
+
+//  D2-CHECK: error: 'error' diagnostics seen but not expected:
+// D2-CHECK-NEXT:   {{test_d2}}
+// D2-CHECK-NEXT:   {{.*}} expected directive cannot follow 'expected-no-diagnostics' directive
+// D2-CHECK-NEXT: 2 errors generated.
+#endif
+
+#ifdef TEST_D3
+// expected-no-diagnostics
+// expected-maybe-no-diagnostics
+#error test_d3
+// expected-error@-1 {{test_d3}}
+
+//  D3-CHECK: error: 'error' diagnostics seen but not expected:
+// D3-CHECK-NEXT:   {{test_d3}}
+// D3-CHECK-NEXT:   {{.*}} expected directive cannot follow 'expected-no-diagnostics' directive
+// D3-CHECK-NEXT: 2 errors generated.
+#endif
+
+#ifdef TEST_D4
+// expected-no-diagnostics
+#error test_d4
+// expected-error@-1 {{test_d4}}
+// expected-maybe-no-diagnostics
+
+//  D4-CHECK: error: 'error' diagnostics seen but not expected:
+// D4-CHECK-NEXT:   {{test_d4}}
+// D4-CHECK-NEXT:  

[clang] 4a16f65 - [Driver][X86] Reject unsupported value for -mabi=

2023-05-26 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-05-26T09:52:57-07:00
New Revision: 4a16f65fc83df494318ced1d894f6b1e562d330c

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

LOG: [Driver][X86] Reject unsupported value for -mabi=

-mabi= was incorrectly claimed before D134671. -mabi=sysv appears to be
somewhat common in open-source packages, even if it was not intended to
be supported by Clang.
(For common options supported by multiple architectures, it's easy to
forget to report an error on unsupported targets. Unfortunately
the driver infrastructure doesn't make this less error-prone.)

On x86, support -mabi=sysv for non-Windows targets and -mabi=ms for Windows,
and remove the spurious -Wunused-command-line-argument warning.

With this change, all popular architectures claim -mabi=, so we don't
have to worry much about -Wunused-command-line-argument for other
architectures.

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

Added: 
clang/test/Driver/x86-mabi.c

Modified: 
clang/lib/Driver/ToolChains/Arch/X86.cpp

Removed: 
clang/test/Driver/mabi.c



diff  --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index f1ad370fe1acf..286bac2e7a2b6 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -119,6 +119,15 @@ std::string x86::getX86TargetCPU(const Driver &D, const 
ArgList &Args,
 void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
std::vector &Features) {
+  // Claim and report unsupported -mabi=. Note: we don't support "sysv_abi" or
+  // "ms_abi" as default function attributes.
+  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mabi_EQ)) {
+StringRef DefaultAbi = Triple.isOSWindows() ? "ms" : "sysv";
+if (A->getValue() != DefaultAbi)
+  D.Diag(diag::err_drv_unsupported_opt_for_target)
+  << A->getSpelling() << Triple.getTriple();
+  }
+
   // If -march=native, autodetect the feature list.
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {

diff  --git a/clang/test/Driver/mabi.c b/clang/test/Driver/mabi.c
deleted file mode 100644
index 01e494d91b7a2..0
--- a/clang/test/Driver/mabi.c
+++ /dev/null
@@ -1,6 +0,0 @@
-// RUN: %clang --target=i386-unknown-linux -mabi=ms -S %s -### 2>&1 | 
FileCheck --check-prefix=CHECK %s
-
-int f() {
-  // CHECK: warning: argument unused during compilation: '-mabi=ms'
-  return 0;
-}

diff  --git a/clang/test/Driver/x86-mabi.c b/clang/test/Driver/x86-mabi.c
new file mode 100644
index 0..790d3c8daf528
--- /dev/null
+++ b/clang/test/Driver/x86-mabi.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=ms -S %s 2>&1 | 
FileCheck %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=ms -S %s 2>&1 | 
FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=sysv -S %s 2>&1 | 
FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=sysv -S %s 2>&1 | 
FileCheck %s
+
+// RUN: %clang -### --target=x86_64-windows-gnu -mabi=ms -S %s 2>&1 | 
FileCheck %s
+
+// CHECK-NOT: {{error|warning}}:
+// ERR: error: unsupported option '-mabi=' for target '{{.*}}'
+
+int f() {
+  return 0;
+}



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


[PATCH] D151509: [Driver][X86] Reject unsupported value for -mabi=

2023-05-26 Thread Fangrui Song 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 rG4a16f65fc83d: [Driver][X86] Reject unsupported value for 
-mabi= (authored by MaskRay).

Changed prior to commit:
  https://reviews.llvm.org/D151509?vs=525842&id=526104#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151509

Files:
  clang/lib/Driver/ToolChains/Arch/X86.cpp
  clang/test/Driver/mabi.c
  clang/test/Driver/x86-mabi.c


Index: clang/test/Driver/x86-mabi.c
===
--- /dev/null
+++ clang/test/Driver/x86-mabi.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=ms -S %s 2>&1 | 
FileCheck %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=ms -S %s 2>&1 | 
FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=sysv -S %s 2>&1 | 
FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=sysv -S %s 2>&1 | 
FileCheck %s
+
+// RUN: %clang -### --target=x86_64-windows-gnu -mabi=ms -S %s 2>&1 | 
FileCheck %s
+
+// CHECK-NOT: {{error|warning}}:
+// ERR: error: unsupported option '-mabi=' for target '{{.*}}'
+
+int f() {
+  return 0;
+}
Index: clang/test/Driver/mabi.c
===
--- clang/test/Driver/mabi.c
+++ /dev/null
@@ -1,6 +0,0 @@
-// RUN: %clang --target=i386-unknown-linux -mabi=ms -S %s -### 2>&1 | 
FileCheck --check-prefix=CHECK %s
-
-int f() {
-  // CHECK: warning: argument unused during compilation: '-mabi=ms'
-  return 0;
-}
Index: clang/lib/Driver/ToolChains/Arch/X86.cpp
===
--- clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -119,6 +119,15 @@
 void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
std::vector &Features) {
+  // Claim and report unsupported -mabi=. Note: we don't support "sysv_abi" or
+  // "ms_abi" as default function attributes.
+  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mabi_EQ)) {
+StringRef DefaultAbi = Triple.isOSWindows() ? "ms" : "sysv";
+if (A->getValue() != DefaultAbi)
+  D.Diag(diag::err_drv_unsupported_opt_for_target)
+  << A->getSpelling() << Triple.getTriple();
+  }
+
   // If -march=native, autodetect the feature list.
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {


Index: clang/test/Driver/x86-mabi.c
===
--- /dev/null
+++ clang/test/Driver/x86-mabi.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=ms -S %s 2>&1 | FileCheck %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=ms -S %s 2>&1 | FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=x86_64-windows-msvc -mabi=sysv -S %s 2>&1 | FileCheck --check-prefix=ERR %s
+// RUN: %clang -### --target=i386-unknown-linux -mabi=sysv -S %s 2>&1 | FileCheck %s
+
+// RUN: %clang -### --target=x86_64-windows-gnu -mabi=ms -S %s 2>&1 | FileCheck %s
+
+// CHECK-NOT: {{error|warning}}:
+// ERR: error: unsupported option '-mabi=' for target '{{.*}}'
+
+int f() {
+  return 0;
+}
Index: clang/test/Driver/mabi.c
===
--- clang/test/Driver/mabi.c
+++ /dev/null
@@ -1,6 +0,0 @@
-// RUN: %clang --target=i386-unknown-linux -mabi=ms -S %s -### 2>&1 | FileCheck --check-prefix=CHECK %s
-
-int f() {
-  // CHECK: warning: argument unused during compilation: '-mabi=ms'
-  return 0;
-}
Index: clang/lib/Driver/ToolChains/Arch/X86.cpp
===
--- clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -119,6 +119,15 @@
 void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
std::vector &Features) {
+  // Claim and report unsupported -mabi=. Note: we don't support "sysv_abi" or
+  // "ms_abi" as default function attributes.
+  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mabi_EQ)) {
+StringRef DefaultAbi = Triple.isOSWindows() ? "ms" : "sysv";
+if (A->getValue() != DefaultAbi)
+  D.Diag(diag::err_drv_unsupported_opt_for_target)
+  << A->getSpelling() << Triple.getTriple();
+  }
+
   // If -march=native, autodetect the feature list.
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
 if (StringRef(A->getValue()) == "native") {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi

[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill added inline comments.



Comment at: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h:186-202
+/// Additionally, you can use:
+///
+/// \code
+///   // expected-maybe-no-diagnostics
+/// \endcode
+///
+/// to specify that a file with no "expected-*" comments should pass when no

jdenny wrote:
> Thanks for adding documentation.
> 
> I feel that this edit makes the behavior a little clearer, and it clarifies 
> what happens when "expected-no-diagnostics" and 
> "expected-maybe-no-diagnostics" are combined.
> 
> Also, the original text had:
> 
> > but they do not fail automatically due to a combination of 
> > "expected-no-diagnostics" and "expected-*" within the same test
> 
> That reads to me like it's ok to combine "expected-no-diagnostics" and 
> "expected-*" directives specifying diagnostics.  Hopefully this edit 
> clarifies that point.
> 
Yeah, it's better the way you propose.



Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:470-471
   NoDiag = true;
   if (D.RegexKind)
 continue;
 }

jdenny wrote:
> Shouldn't `expected-maybe-no-diagnostics` have this too so that 
> `expected-maybe-no-diagnostics-re` is skipped?  Please add a test.
You're right, there's no good reason for us not to do the same. Though I don't 
like that we silently skip over not-too-sensical `// 
expected-no-diagnostics-re`. I'll prepare a follow-up patch that makes `-re` a 
hard error for those two special directives.

Tested in A3



Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:468
+Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
+  continue;
+} else if (DToken.endswith(DType="-no-diagnostics")) {

jdenny wrote:
> Endill wrote:
> > jdenny wrote:
> > > This `continue` skips the prefix checking below, which is important when 
> > > there are multiple prefixes active (e.g., `-verify=foo,bar`).  That is, 
> > > any old `BOGUS-maybe-no-diagnostics` will be effective then.
> > This should be fixed now. Thank you for spotting this!
> Thanks for the fix.  Please add a test so this bug doesn't pop up again.
Done as A2 test



Comment at: clang/test/Frontend/verify-maybe-no-diagnostics.c:104
+//  D6-CHECK: error: 'error' diagnostics seen but not expected:
+// D6-CHECK-NEXT:   {{.*}} 'expected-no-diagnostics' directive cannot follow 
other expected directives
+// D6-CHECK-NEXT: 1 error generated.

jdenny wrote:
> Endill wrote:
> > jdenny wrote:
> > > This diagnostic is confusing.  Should we add "except 
> > > 'expected-maybe-no-diagnostics'"?
> > As I mentioned in another comment, `maybe-no-diagnostics` has the lowest 
> > priority, and doesn't have strict and declarative nature, unlike any other 
> > directive. That's why it should never be expected (and ideally very rarely 
> > used).
> > 
> > The purpose of all the tests I added is to ensure `expected-no-diagnostic` 
> > doesn't affect existing directives and their interaction in any way.
> I don't see how that addresses my concern.  Maybe it's because, after the 
> latest edits, phab shifted my comment to the wrong test.  I was originally 
> commenting on this:
> 
> > 'expected-no-diagnostics' directive cannot follow other expected directives
> 
> This message is now incorrect.  `expected-no-diagnostics` //can// follow 
> `expected-maybe-no-diagnostics`.  What if we reword as follows?
> 
> > 'expected-no-diagnostics' directive cannot follow directives that expect 
> > diagnostics
Sorry, I misunderstood your initial comment. It's fixed now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

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


[PATCH] D148723: [clang] Restrict Inline Builtin to non-static, non-odr linkage

2023-05-26 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D148723

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


[PATCH] D151320: [clang] Add `// expected-maybe-no-diagnostics` comment to VerifyDiagnosticConsumer

2023-05-26 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny accepted this revision.
jdenny added a comment.
This revision is now accepted and ready to land.

Thanks for addressing all my concerns.

LGTM except for a test issue I just commented on.




Comment at: clang/lib/Frontend/VerifyDiagnosticConsumer.cpp:468
+Status = VerifyDiagnosticConsumer::HasExpectedMaybeNoDiagnostics;
+  continue;
+} else if (DToken.endswith(DType="-no-diagnostics")) {

Endill wrote:
> jdenny wrote:
> > Endill wrote:
> > > jdenny wrote:
> > > > This `continue` skips the prefix checking below, which is important 
> > > > when there are multiple prefixes active (e.g., `-verify=foo,bar`).  
> > > > That is, any old `BOGUS-maybe-no-diagnostics` will be effective then.
> > > This should be fixed now. Thank you for spotting this!
> > Thanks for the fix.  Please add a test so this bug doesn't pop up again.
> Done as A2 test
Does A2 trigger the original bug?  I think there must be multiple prefixes for 
this fix to matter.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151320

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


[PATCH] D150913: [Clang][BFloat16] Upgrade __bf16 to arithmetic type, change mangling, and extend excess precision support.

2023-05-26 Thread M. Zeeshan Siddiqui via Phabricator via cfe-commits
codemzs added a comment.

Hi @rjmccall, @pengfei, and @zahiraam,

Thank you for your valuable review and acceptance of my patch. As I lack commit 
access, could I kindly request one of you to perform the commit on my behalf? 
Please use the following command: `git commit --amend --author="M. Zeeshan 
Siddiqui "`.

git commit message:

  [Clang][BFloat16] Upgrade __bf16 to arithmetic type, change mangling,
  and extend excess precision support
  
  Pursuant to discussions at
  
https://discourse.llvm.org/t/rfc-c-23-p1467r9-extended-floating-point-types-and-standard-names/70033/22,
  this commit enhances the handling of the __bf16 type in Clang.
  - Firstly, it upgrades __bf16 from a storage-only type to an arithmetic
type.
  - Secondly, it changes the mangling of __bf16 to DF16b on all
architectures except ARM. This change has been made in
accordance with the finalization of the mangling for the
std::bfloat16_t type, as discussed at
https://github.com/itanium-cxx-abi/cxx-abi/pull/147.
  - Finally, this commit extends the existing excess precision support to
the __bf16 type. This applies to hardware architectures that do not
natively support bfloat16 arithmetic.
  Appropriate tests have been added to verify the effects of these
  changes and ensure no regressions in other areas of the compiler.
  
  Reviewed By: rjmccall, pengfei, zahiraam
  
  Differential Revision: https://reviews.llvm.org/D150913

I would like to add that I have rebased this patch on LLVM main as of just now 
and also applied clang formatting to this patch. However, to maintain 
consistency and respect untouched lines, I opted to reverse certain 
clang-format changes, which might result in a clang format failure on Debian. 
Should you deem it necessary for me to apply clang formatting across all lines 
regardless, I am open to revising the format accordingly.

Your assistance is greatly appreciated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150913

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


[PATCH] D151515: [CodeGen] add additional cast when checking call arguments

2023-05-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added subscribers: efriedma, rjmccall, rnk.
rnk added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:4376
+.getTypePtr()
+->getPointeeOrArrayElementType();
+  const Type *CanonicalArgTy = getContext()

I think this discards too much information about pointer types. I think it 
would treat two pointers with interestingly different qualifiers differently. 
Consider, perhaps, a mismatch in pointer address spaces, which are passed 
differently (think `__ptr32` `__ptr64`).

I think there is probably some other way to get the type of the parameter after 
pointer decay. I would ask @efriedma since he's the current IRGen owner or 
@rjmccall  since I think he may have added this prototype assertion originally, 
I just moved the code around.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151515

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


[PATCH] D151492: Add fastmath attributes to llvm.call_intrinsic

2023-05-26 Thread Lily Orth-Smith via Phabricator via cfe-commits
electriclilies updated this revision to Diff 526115.
electriclilies added a comment.

fix test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151492

Files:
  mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
  mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
  mlir/test/Dialect/LLVMIR/call-intrin.mlir


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1) 
{fastmathFlags = #llvm.fastmath}
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = 
#llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
@@ -95,7 +95,7 @@
 
 /// Builder for LLVM_CallIntrinsicOp
 static LogicalResult
-convertCallLLVMIntrinsicOp(CallIntrinsicOp &op, llvm::IRBuilderBase &builder,
+convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
   llvm::Module *module = builder.GetInsertBlock()->getModule();
   llvm::Intrinsic::ID id =
@@ -114,6 +114,8 @@
   } else {
 fn = llvm::Intrinsic::getDeclaration(module, id, {});
   }
+  FastmathFlagsInterface itf = op;
+  builder.setFastMathFlags(getFastmathFlags(itf));
 
   auto *inst =
   builder.CreateCall(fn, moduleTranslation.lookupValues(op.getOperands()));
Index: mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
===
--- mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -867,19 +867,24 @@
 // CallIntrinsicOp
 //======//
 
-def LLVM_CallIntrinsicOp : LLVM_Op<"call_intrinsic"> {
+def LLVM_CallIntrinsicOp
+: LLVM_Op<"call_intrinsic",
+  [DeclareOpInterfaceMethods]> {
   let summary = "Call to an LLVM intrinsic function.";
   let description = [{
 Call the specified llvm intrinsic. If the intrinsic is overloaded, use
 the MLIR function type of this op to determine which intrinsic to call.
 }];
-  let arguments = (ins StrAttr:$intrin, Variadic:$args);
+  let arguments = (ins StrAttr:$intrin, Variadic:$args,
+   DefaultValuedAttr:$fastmathFlags);
   let results = (outs Variadic:$results);
   let llvmBuilder = [{
 return convertCallLLVMIntrinsicOp(op, builder, moduleTranslation);
   }];
   let assemblyFormat = [{
-$intrin `(` $args `)` `:` functional-type($args, $results) attr-dict
+$intrin `(` $args `)` `:` functional-type($args, $results)
+  custom(attr-dict)
   }];
 }
 


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1) {fastmathFlags = #llvm.fastmath}
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = #llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp

[clang] acb1b4f - Fix wrong error message when compiling C souce code:

2023-05-26 Thread Jennifer Yu via cfe-commits

Author: Jennifer Yu
Date: 2023-05-26T10:14:52-07:00
New Revision: acb1b4fbb7939faa369337b9b26b960fdc91e4b8

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

LOG: Fix wrong error message when compiling C souce code:
Currently emit error for uses_allocators(alloc(traits)):

called object type 'omp_allocator_handle_t' (aka
'enum omp_allocator_handle_t') is not a function or function pointer

To fix this, since "alloc" is Id expresison(spce 5.2), during the parser
(in ParseOpenMP.cpp), using tryParseCXXIdExpression instead of
ParseExpression for C.

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

Added: 


Modified: 
clang/lib/Parse/ParseOpenMP.cpp
clang/test/OpenMP/target_uses_allocators.c

Removed: 




diff  --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index a7db7a1c2582..8c57dc9e071f 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -3103,8 +3103,13 @@ OMPClause 
*Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
 return nullptr;
   SmallVector Data;
   do {
+CXXScopeSpec SS;
+Token Replacement;
 ExprResult Allocator =
-getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
+getLangOpts().CPlusPlus
+? ParseCXXIdExpression()
+: tryParseCXXIdExpression(SS, /*isAddressOfOperand=*/false,
+  Replacement);
 if (Allocator.isInvalid()) {
   SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
 StopBeforeMatch);

diff  --git a/clang/test/OpenMP/target_uses_allocators.c 
b/clang/test/OpenMP/target_uses_allocators.c
index f096c4a3f275..566fa51686db 100644
--- a/clang/test/OpenMP/target_uses_allocators.c
+++ b/clang/test/OpenMP/target_uses_allocators.c
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50  -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -verify 
-emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-include-pch %t %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -verify 
-emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-include-pch %t %s -emit-llvm -o - | FileCheck %s
 
 #ifndef HEADER
 #define HEADER
@@ -19,9 +21,27 @@ typedef enum omp_allocator_handle_t {
   KMP_ALLOCATOR_MAX_HANDLE = __UINTPTR_MAX__
 } omp_allocator_handle_t;
 
+typedef enum omp_alloctrait_key_t { omp_atk_sync_hint = 1,
+omp_atk_alignment = 2,
+omp_atk_access = 3,
+omp_atk_pool_size = 4,
+omp_atk_fallback = 5,
+omp_atk_fb_data = 6,
+omp_atk_pinned = 7,
+omp_atk_partition = 8
+} omp_alloctrait_key_t;
+
+typedef struct omp_alloctrait_t {
+  omp_alloctrait_key_t key;
+  __UINTPTR_TYPE__ value;
+} omp_alloctrait_t;
+
+
 // CHECK: define {{.*}}[[FIE:@.+]]()
 void fie(void) {
   int x;
+  omp_allocator_handle_t my_allocator;
+  omp_alloctrait_t traits[10];
   #pragma omp target uses_allocators(omp_null_allocator) 
allocate(omp_null_allocator: x) firstprivate(x)
   {}
   #pragma omp target uses_allocators(omp_default_mem_alloc) 
allocate(omp_default_mem_alloc: x) firstprivate(x)
@@ -40,6 +60,8 @@ void fie(void) {
   {}
   #pragma omp target uses_allocators(omp_thread_mem_alloc) 
allocate(omp_thread_mem_alloc: x) firstprivate(x) // expected-warning 
{{allocator with the 'thread' trait access has unspecified behavior on 'target' 
directive}}
   {}
+#pragma omp target uses_allocators(omp_null_allocator, omp_thread_mem_alloc, 
my_allocator(traits))
+  {}
 }
 
 #endif
@@ -106,3 +128,16 @@ void fie(void) {
 // CHECK-NEXT: %[[#R1:]] = load i32, ptr %x.addr, align 4
 // CHECK-NEXT: store i32 %[[#R1]], ptr %.x..void.addr, align 4
 // CHECK-NEXT: call void @__kmpc_free(i32 %[[#R0]], ptr %.x..void.addr, ptr 
inttoptr (i64 8 to ptr))
+
+// CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca ptr,
+// CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
+// CHECK: [[TRAITS_ADDR:%.+]] = load ptr, ptr [[TRAITS_ADDR_REF]],
+// CHECK: [[TRAITS:%.+]] = load ptr, ptr [[TRAITS_ADDR]],
+// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_a

[PATCH] D151517: Fix wrong error message when compiling C souce code

2023-05-26 Thread Jennifer Yu 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 rGacb1b4fbb793: Fix wrong error message when compiling C souce 
code: (authored by jyu2).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151517

Files:
  clang/lib/Parse/ParseOpenMP.cpp
  clang/test/OpenMP/target_uses_allocators.c


Index: clang/test/OpenMP/target_uses_allocators.c
===
--- clang/test/OpenMP/target_uses_allocators.c
+++ clang/test/OpenMP/target_uses_allocators.c
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50  -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -verify 
-emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-include-pch %t %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -verify 
-emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -triple 
powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-include-pch %t %s -emit-llvm -o - | FileCheck %s
 
 #ifndef HEADER
 #define HEADER
@@ -19,9 +21,27 @@
   KMP_ALLOCATOR_MAX_HANDLE = __UINTPTR_MAX__
 } omp_allocator_handle_t;
 
+typedef enum omp_alloctrait_key_t { omp_atk_sync_hint = 1,
+omp_atk_alignment = 2,
+omp_atk_access = 3,
+omp_atk_pool_size = 4,
+omp_atk_fallback = 5,
+omp_atk_fb_data = 6,
+omp_atk_pinned = 7,
+omp_atk_partition = 8
+} omp_alloctrait_key_t;
+
+typedef struct omp_alloctrait_t {
+  omp_alloctrait_key_t key;
+  __UINTPTR_TYPE__ value;
+} omp_alloctrait_t;
+
+
 // CHECK: define {{.*}}[[FIE:@.+]]()
 void fie(void) {
   int x;
+  omp_allocator_handle_t my_allocator;
+  omp_alloctrait_t traits[10];
   #pragma omp target uses_allocators(omp_null_allocator) 
allocate(omp_null_allocator: x) firstprivate(x)
   {}
   #pragma omp target uses_allocators(omp_default_mem_alloc) 
allocate(omp_default_mem_alloc: x) firstprivate(x)
@@ -40,6 +60,8 @@
   {}
   #pragma omp target uses_allocators(omp_thread_mem_alloc) 
allocate(omp_thread_mem_alloc: x) firstprivate(x) // expected-warning 
{{allocator with the 'thread' trait access has unspecified behavior on 'target' 
directive}}
   {}
+#pragma omp target uses_allocators(omp_null_allocator, omp_thread_mem_alloc, 
my_allocator(traits))
+  {}
 }
 
 #endif
@@ -106,3 +128,16 @@
 // CHECK-NEXT: %[[#R1:]] = load i32, ptr %x.addr, align 4
 // CHECK-NEXT: store i32 %[[#R1]], ptr %.x..void.addr, align 4
 // CHECK-NEXT: call void @__kmpc_free(i32 %[[#R0]], ptr %.x..void.addr, ptr 
inttoptr (i64 8 to ptr))
+
+// CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca ptr,
+// CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
+// CHECK: [[TRAITS_ADDR:%.+]] = load ptr, ptr [[TRAITS_ADDR_REF]],
+// CHECK: [[TRAITS:%.+]] = load ptr, ptr [[TRAITS_ADDR]],
+// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_allocator(i32 %{{.+}}, ptr 
null, i32 10, ptr [[TRAITS]])
+// CHECK: [[CONV:%.+]] = ptrtoint ptr [[ALLOCATOR]] to i64
+// CHECK: store i64 [[CONV]], ptr [[MY_ALLOCATOR_ADDR]],
+
+// Destroy allocator upon exit from the region.
+// CHECK: [[ALLOCATOR:%.+]] = load i64, ptr [[MY_ALLOCATOR_ADDR]],
+// CHECK: [[CONV:%.+]] = inttoptr i64 [[ALLOCATOR]] to ptr
+// CHECK: call void @__kmpc_destroy_allocator(i32 %{{.+}}, ptr [[CONV]])
Index: clang/lib/Parse/ParseOpenMP.cpp
===
--- clang/lib/Parse/ParseOpenMP.cpp
+++ clang/lib/Parse/ParseOpenMP.cpp
@@ -3103,8 +3103,13 @@
 return nullptr;
   SmallVector Data;
   do {
+CXXScopeSpec SS;
+Token Replacement;
 ExprResult Allocator =
-getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
+getLangOpts().CPlusPlus
+? ParseCXXIdExpression()
+: tryParseCXXIdExpression(SS, /*isAddressOfOperand=*/false,
+  Replacement);
 if (Allocator.isInvalid()) {
   SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
 StopBeforeMatch);


Index: clang/test/OpenMP/target_uses_allocators.c
===
--- clang/test/OpenMP/target_uses_allocators.c
+++ clang/test/OpenMP/target_uses_allocators.c
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -verify -fop

[PATCH] D151492: Add fastmath attributes to llvm.call_intrinsic

2023-05-26 Thread Lily Orth-Smith via Phabricator via cfe-commits
electriclilies updated this revision to Diff 526117.
electriclilies added a comment.

fix


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151492

Files:
  mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
  mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
  mlir/test/Dialect/LLVMIR/call-intrin.mlir


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call reassoc <4 x float> @llvm.x86.sse41.round.ss(<4 x float> 
, <4 x float> , i32 1)
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = 
#llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
@@ -95,7 +95,7 @@
 
 /// Builder for LLVM_CallIntrinsicOp
 static LogicalResult
-convertCallLLVMIntrinsicOp(CallIntrinsicOp &op, llvm::IRBuilderBase &builder,
+convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
   llvm::Module *module = builder.GetInsertBlock()->getModule();
   llvm::Intrinsic::ID id =
@@ -114,6 +114,8 @@
   } else {
 fn = llvm::Intrinsic::getDeclaration(module, id, {});
   }
+  FastmathFlagsInterface itf = op;
+  builder.setFastMathFlags(getFastmathFlags(itf));
 
   auto *inst =
   builder.CreateCall(fn, moduleTranslation.lookupValues(op.getOperands()));
Index: mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
===
--- mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -867,19 +867,24 @@
 // CallIntrinsicOp
 //======//
 
-def LLVM_CallIntrinsicOp : LLVM_Op<"call_intrinsic"> {
+def LLVM_CallIntrinsicOp
+: LLVM_Op<"call_intrinsic",
+  [DeclareOpInterfaceMethods]> {
   let summary = "Call to an LLVM intrinsic function.";
   let description = [{
 Call the specified llvm intrinsic. If the intrinsic is overloaded, use
 the MLIR function type of this op to determine which intrinsic to call.
 }];
-  let arguments = (ins StrAttr:$intrin, Variadic:$args);
+  let arguments = (ins StrAttr:$intrin, Variadic:$args,
+   DefaultValuedAttr:$fastmathFlags);
   let results = (outs Variadic:$results);
   let llvmBuilder = [{
 return convertCallLLVMIntrinsicOp(op, builder, moduleTranslation);
   }];
   let assemblyFormat = [{
-$intrin `(` $args `)` `:` functional-type($args, $results) attr-dict
+$intrin `(` $args `)` `:` functional-type($args, $results)
+  custom(attr-dict)
   }];
 }
 


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call reassoc <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = #llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/

[PATCH] D151515: [CodeGen] add additional cast when checking call arguments

2023-05-26 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Relevant bit of the AST:

  `-ExprWithCleanups 0xd16a780  'void':'void'
`-CXXOperatorCallExpr 0xd16a678  'void':'void' '()'
  |-ImplicitCastExpr 0xd16a5a8  'void (*)(int (&&)[]) const' 

  | `-DeclRefExpr 0xd16a528  'void (int (&&)[]) const' lvalue 
CXXMethod 0xd14f7f8 'operator()' 'void (int (&&)[]) const'
  |-ImplicitCastExpr 0xd16a5e8  'const (lambda at :5:12)' 
lvalue 
  | `-DeclRefExpr 0xd16a460  '(lambda at :5:12)':'(lambda at 
:5:12)' lvalue Var 0xd14f628 'f' '(lambda at :5:12)':'(lambda at 
:5:12)'
  `-MaterializeTemporaryExpr 0xd16a660  'int[1]' xvalue
`-InitListExpr 0xd16a600  'int[1]'
  `-ImplicitCastExpr 0xd16a640  'int' 
`-DeclRefExpr 0xd16a480  'int' lvalue ParmVar 0xd14f3a8 'a' 
'int'

At first glance, I'd consider this a problem with the AST: there should be a 
no-op cast from `int[1]` to `int[]`.  We generate such a cast for the following:

  void foo(int a) {
auto f = [](int(&&)[]) {};
int aa[1] = {a};
f(static_cast(aa));
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151515

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


[PATCH] D151572: [clang][ConstantEmitter] have tryEmitPrivate try ConstExprEmitter fast-path first

2023-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers created this revision.
Herald added a project: All.
nickdesaulniers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

As suggested by @efriedma in:
https://reviews.llvm.org/D76096#4370369

Some minor code style fixes as well in
ConstantEmitter::tryEmitPrivateForVarInit.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151572

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1656,9 +1656,8 @@
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (auto value = D.evaluateValue()) {
+  if (APValue *value = D.evaluateValue())
 return tryEmitPrivateForMemory(*value, destType);
-  }
 
   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
   // reference is a constant expression, and the reference binds to a 
temporary,
@@ -1672,10 +1671,10 @@
   const Expr *E = D.getInit();
   assert(E && "No initializer to emit");
 
-  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
-  auto C =
-ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
-  return (C ? emitForMemory(C, destType) : nullptr);
+  QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
+  llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
+  return C ? emitForMemory(C, destType) : nullptr;
 }
 
 llvm::Constant *
@@ -1742,6 +1741,10 @@
 QualType destType) {
   assert(!destType->isVoidType() && "can't emit a void constant");
 
+  if (llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), destType))
+return C;
+
   Expr::EvalResult Result;
 
   bool Success = false;
@@ -1751,13 +1754,10 @@
   else
 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
 
-  llvm::Constant *C;
   if (Success && !Result.HasSideEffects)
-C = tryEmitPrivate(Result.Val, destType);
-  else
-C = ConstExprEmitter(*this).Visit(const_cast(E), destType);
+return tryEmitPrivate(Result.Val, destType);
 
-  return C;
+  return nullptr;
 }
 
 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType 
QT) {


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1656,9 +1656,8 @@
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (auto value = D.evaluateValue()) {
+  if (APValue *value = D.evaluateValue())
 return tryEmitPrivateForMemory(*value, destType);
-  }
 
   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
   // reference is a constant expression, and the reference binds to a temporary,
@@ -1672,10 +1671,10 @@
   const Expr *E = D.getInit();
   assert(E && "No initializer to emit");
 
-  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
-  auto C =
-ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
-  return (C ? emitForMemory(C, destType) : nullptr);
+  QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
+  llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
+  return C ? emitForMemory(C, destType) : nullptr;
 }
 
 llvm::Constant *
@@ -1742,6 +1741,10 @@
 QualType destType) {
   assert(!destType->isVoidType() && "can't emit a void constant");
 
+  if (llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), destType))
+return C;
+
   Expr::EvalResult Result;
 
   bool Success = false;
@@ -1751,13 +1754,10 @@
   else
 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
 
-  llvm::Constant *C;
   if (Success && !Result.HasSideEffects)
-C = tryEmitPrivate(Result.Val, destType);
-  else
-C = ConstExprEmitter(*this).Visit(const_cast(E), destType);
+return tryEmitPrivate(Result.Val, destType);
 
-  return C;
+  return nullptr;
 }
 
 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 2a84c63 - [clang-tidy] Optimize misc-confusable-identifiers

2023-05-26 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-05-26T17:46:13Z
New Revision: 2a84c635f2a1dcb4546a5d751a32eac24103c7e6

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

LOG: [clang-tidy] Optimize misc-confusable-identifiers

Main performance issue in this check were caused by many
calls to getPrimaryContext and constant walk up to declaration
contexts using getParent. Also there were issue with forallBases
that is slow.

Profiled with perf and tested on open-source project Cataclysm-DDA.
Before changes check took 27320 seconds, after changes 3682 seconds.
That's 86.5% reduction. More optimizations are still possible in this
check.

Reviewed By: serge-sans-paille

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
index 355e097108030..63ba663aaca9a 100644
--- a/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
@@ -45,7 +45,7 @@ ConfusableIdentifierCheck::~ConfusableIdentifierCheck() = 
default;
 // We're skipping 1. and 3. for the sake of simplicity, but this can lead to
 // false positive.
 
-std::string ConfusableIdentifierCheck::skeleton(StringRef Name) {
+static std::string skeleton(StringRef Name) {
   using namespace llvm;
   std::string SName = Name.str();
   std::string Skeleton;
@@ -89,75 +89,107 @@ std::string ConfusableIdentifierCheck::skeleton(StringRef 
Name) {
   return Skeleton;
 }
 
-static bool mayShadowImpl(const NamedDecl *ND0, const NamedDecl *ND1) {
-  const DeclContext *DC0 = ND0->getDeclContext()->getPrimaryContext();
-  const DeclContext *DC1 = ND1->getDeclContext()->getPrimaryContext();
+static bool mayShadowImpl(const DeclContext *DC0, const DeclContext *DC1) {
+  return DC0 && DC0 == DC1;
+}
 
-  if (isa(ND0) || isa(ND0))
-return true;
+static bool mayShadowImpl(const NamedDecl *ND0, const NamedDecl *ND1) {
+  return isa(ND0) || isa(ND1);
+}
 
-  while (DC0->isTransparentContext())
-DC0 = DC0->getParent();
-  while (DC1->isTransparentContext())
-DC1 = DC1->getParent();
+static bool isMemberOf(const ConfusableIdentifierCheck::ContextInfo *DC0,
+   const ConfusableIdentifierCheck::ContextInfo *DC1) {
+  if (DC0->Bases.empty())
+return false;
+  return llvm::is_contained(DC1->Bases, DC0->PrimaryContext);
+}
 
-  if (DC0->Equals(DC1))
+static bool enclosesContext(const ConfusableIdentifierCheck::ContextInfo *DC0,
+const ConfusableIdentifierCheck::ContextInfo *DC1) 
{
+  if (DC0->PrimaryContext == DC1->PrimaryContext)
 return true;
 
-  return false;
+  return llvm::is_contained(DC0->PrimaryContexts, DC1->PrimaryContext) ||
+ llvm::is_contained(DC1->PrimaryContexts, DC0->PrimaryContext);
 }
 
-static bool isMemberOf(const NamedDecl *ND, const CXXRecordDecl *RD) {
-  const DeclContext *NDParent = ND->getDeclContext();
-  if (!NDParent || !isa(NDParent))
-return false;
-  if (NDParent == RD)
+static bool mayShadow(const NamedDecl *ND0,
+  const ConfusableIdentifierCheck::ContextInfo *DC0,
+  const NamedDecl *ND1,
+  const ConfusableIdentifierCheck::ContextInfo *DC1) {
+  if (!DC0->Bases.empty() && ND1->getAccess() != AS_private &&
+  isMemberOf(DC1, DC0))
 return true;
-  return !RD->forallBases(
-  [NDParent](const CXXRecordDecl *Base) { return NDParent != Base; });
+  if (!DC1->Bases.empty() && ND0->getAccess() != AS_private &&
+  isMemberOf(DC0, DC1))
+return true;
+
+  return enclosesContext(DC0, DC1) &&
+ (mayShadowImpl(ND0, ND1) || mayShadowImpl(DC0->NonTransparentContext,
+   
DC1->NonTransparentContext));
 }
 
-static bool mayShadow(const NamedDecl *ND0, const NamedDecl *ND1) {
+const ConfusableIdentifierCheck::ContextInfo *
+ConfusableIdentifierCheck::getContextInfo(const DeclContext *DC) {
+  const DeclContext *PrimaryContext = DC->getPrimaryContext();
+  auto It = ContextInfos.find(PrimaryContext);
+  if (It != ContextInfos.end())
+return &It->second;
+
+  ContextInfo &Info = ContextInfos[PrimaryContext];
+  Info.PrimaryContext = PrimaryContext;
+  Info.NonTransparentContext = PrimaryContext;
+
+  while (Info.NonTransparentContext->isTransparentContext()) {
+Info.NonTransparentContext = Info.NonTransparentContext->getParent();
+if (!Info.NonTransparentContext)
+  break;
+  }
 
-  const DeclContext *DC0 = ND0->getDeclContext()->getPrimaryContext

[PATCH] D151051: [clang-tidy] Optimize misc-confusable-identifiers

2023-05-26 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2a84c635f2a1: [clang-tidy] Optimize 
misc-confusable-identifiers (authored by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151051

Files:
  clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
  clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.h

Index: clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.h
===
--- clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.h
+++ clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.h
@@ -11,6 +11,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_CONFUSABLE_IDENTIFIER_CHECK_H
 
 #include "../ClangTidyCheck.h"
+#include 
 
 namespace clang::tidy::misc {
 
@@ -26,9 +27,23 @@
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
 
+  struct ContextInfo {
+const DeclContext *PrimaryContext;
+const DeclContext *NonTransparentContext;
+llvm::SmallVector PrimaryContexts;
+llvm::SmallVector Bases;
+  };
+
 private:
-  std::string skeleton(StringRef);
-  llvm::StringMap> Mapper;
+  struct Entry {
+const NamedDecl *Declaration;
+const ContextInfo *Info;
+  };
+
+  const ContextInfo *getContextInfo(const DeclContext *DC);
+
+  llvm::StringMap> Mapper;
+  std::unordered_map ContextInfos;
 };
 
 } // namespace clang::tidy::misc
Index: clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
@@ -45,7 +45,7 @@
 // We're skipping 1. and 3. for the sake of simplicity, but this can lead to
 // false positive.
 
-std::string ConfusableIdentifierCheck::skeleton(StringRef Name) {
+static std::string skeleton(StringRef Name) {
   using namespace llvm;
   std::string SName = Name.str();
   std::string Skeleton;
@@ -89,75 +89,107 @@
   return Skeleton;
 }
 
-static bool mayShadowImpl(const NamedDecl *ND0, const NamedDecl *ND1) {
-  const DeclContext *DC0 = ND0->getDeclContext()->getPrimaryContext();
-  const DeclContext *DC1 = ND1->getDeclContext()->getPrimaryContext();
+static bool mayShadowImpl(const DeclContext *DC0, const DeclContext *DC1) {
+  return DC0 && DC0 == DC1;
+}
 
-  if (isa(ND0) || isa(ND0))
-return true;
+static bool mayShadowImpl(const NamedDecl *ND0, const NamedDecl *ND1) {
+  return isa(ND0) || isa(ND1);
+}
 
-  while (DC0->isTransparentContext())
-DC0 = DC0->getParent();
-  while (DC1->isTransparentContext())
-DC1 = DC1->getParent();
+static bool isMemberOf(const ConfusableIdentifierCheck::ContextInfo *DC0,
+   const ConfusableIdentifierCheck::ContextInfo *DC1) {
+  if (DC0->Bases.empty())
+return false;
+  return llvm::is_contained(DC1->Bases, DC0->PrimaryContext);
+}
 
-  if (DC0->Equals(DC1))
+static bool enclosesContext(const ConfusableIdentifierCheck::ContextInfo *DC0,
+const ConfusableIdentifierCheck::ContextInfo *DC1) {
+  if (DC0->PrimaryContext == DC1->PrimaryContext)
 return true;
 
-  return false;
+  return llvm::is_contained(DC0->PrimaryContexts, DC1->PrimaryContext) ||
+ llvm::is_contained(DC1->PrimaryContexts, DC0->PrimaryContext);
 }
 
-static bool isMemberOf(const NamedDecl *ND, const CXXRecordDecl *RD) {
-  const DeclContext *NDParent = ND->getDeclContext();
-  if (!NDParent || !isa(NDParent))
-return false;
-  if (NDParent == RD)
+static bool mayShadow(const NamedDecl *ND0,
+  const ConfusableIdentifierCheck::ContextInfo *DC0,
+  const NamedDecl *ND1,
+  const ConfusableIdentifierCheck::ContextInfo *DC1) {
+  if (!DC0->Bases.empty() && ND1->getAccess() != AS_private &&
+  isMemberOf(DC1, DC0))
 return true;
-  return !RD->forallBases(
-  [NDParent](const CXXRecordDecl *Base) { return NDParent != Base; });
+  if (!DC1->Bases.empty() && ND0->getAccess() != AS_private &&
+  isMemberOf(DC0, DC1))
+return true;
+
+  return enclosesContext(DC0, DC1) &&
+ (mayShadowImpl(ND0, ND1) || mayShadowImpl(DC0->NonTransparentContext,
+   DC1->NonTransparentContext));
 }
 
-static bool mayShadow(const NamedDecl *ND0, const NamedDecl *ND1) {
+const ConfusableIdentifierCheck::ContextInfo *
+ConfusableIdentifierCheck::getContextInfo(const DeclContext *DC) {
+  const DeclContext *PrimaryContext = DC->getPrimaryContext();
+  auto It = ContextInfos.find(PrimaryContext);
+  if (It != ContextInfos.end())
+return &It->second;
+
+  ContextInfo &Info = ContextInfos[PrimaryContext];
+  Info.PrimaryContext = PrimaryContext;
+  Info.NonTranspare

[PATCH] D151515: [CodeGen] add additional cast when checking call arguments

2023-05-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Yeah, I agree with Eli, there should be a cast here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151515

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


[PATCH] D149677: [clang][TypePrinter] Add option to skip over elaborated types

2023-05-26 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 526128.
li.zhe.hua added a comment.

Switch option name to SuppressElaboration


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D149677

Files:
  clang/include/clang/AST/PrettyPrinter.h
  clang/lib/AST/TypePrinter.cpp
  clang/unittests/AST/TypePrinterTest.cpp

Index: clang/unittests/AST/TypePrinterTest.cpp
===
--- clang/unittests/AST/TypePrinterTest.cpp
+++ clang/unittests/AST/TypePrinterTest.cpp
@@ -97,6 +97,33 @@
  "const f *", Clean));
 }
 
+TEST(TypePrinter, SuppressElaboration) {
+  llvm::StringLiteral Code = R"cpp(
+namespace shared {
+namespace a {
+template 
+struct S {};
+}  // namespace a
+namespace b {
+struct Foo {};
+}  // namespace b
+using Alias = a::S;
+}  // namespace shared
+  )cpp";
+
+  auto Matcher = typedefNameDecl(hasName("::shared::Alias"),
+ hasType(qualType().bind("id")));
+  ASSERT_TRUE(PrintedTypeMatches(
+  Code, {}, Matcher, "a::S",
+  [](PrintingPolicy &Policy) { Policy.FullyQualifiedName = true; }));
+  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher,
+ "shared::a::S",
+ [](PrintingPolicy &Policy) {
+   Policy.SuppressElaboration = true;
+   Policy.FullyQualifiedName = true;
+ }));
+}
+
 TEST(TypePrinter, TemplateIdWithNTTP) {
   constexpr char Code[] = R"cpp(
 template 
Index: clang/lib/AST/TypePrinter.cpp
===
--- clang/lib/AST/TypePrinter.cpp
+++ clang/lib/AST/TypePrinter.cpp
@@ -1567,6 +1567,11 @@
 return;
   }
 
+  if (Policy.SuppressElaboration) {
+printBefore(T->getNamedType(), OS);
+return;
+  }
+
   // The tag definition will take care of these.
   if (!Policy.IncludeTagDefinition)
   {
@@ -1586,6 +1591,12 @@
 raw_ostream &OS) {
   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
 return;
+
+  if (Policy.SuppressElaboration) {
+printAfter(T->getNamedType(), OS);
+return;
+  }
+
   ElaboratedTypePolicyRAII PolicyRAII(Policy);
   printAfter(T->getNamedType(), OS);
 }
Index: clang/include/clang/AST/PrettyPrinter.h
===
--- clang/include/clang/AST/PrettyPrinter.h
+++ clang/include/clang/AST/PrettyPrinter.h
@@ -60,14 +60,15 @@
   : Indentation(2), SuppressSpecifiers(false),
 SuppressTagKeyword(LO.CPlusPlus), IncludeTagDefinition(false),
 SuppressScope(false), SuppressUnwrittenScope(false),
-SuppressInlineNamespace(true), SuppressInitializers(false),
-ConstantArraySizeAsWritten(false), AnonymousTagLocations(true),
-SuppressStrongLifetime(false), SuppressLifetimeQualifiers(false),
+SuppressInlineNamespace(true), SuppressElaboration(false),
+SuppressInitializers(false), ConstantArraySizeAsWritten(false),
+AnonymousTagLocations(true), SuppressStrongLifetime(false),
+SuppressLifetimeQualifiers(false),
 SuppressTemplateArgsInCXXConstructors(false),
 SuppressDefaultTemplateArgs(true), Bool(LO.Bool),
 Nullptr(LO.CPlusPlus11 || LO.C2x), NullptrTypeInNamespace(LO.CPlusPlus),
-Restrict(LO.C99), Alignof(LO.CPlusPlus11),
-UnderscoreAlignof(LO.C11), UseVoidForZeroParams(!LO.CPlusPlus),
+Restrict(LO.C99), Alignof(LO.CPlusPlus11), UnderscoreAlignof(LO.C11),
+UseVoidForZeroParams(!LO.CPlusPlus),
 SplitTemplateClosers(!LO.CPlusPlus11), TerseOutput(false),
 PolishForDeclaration(false), Half(LO.Half),
 MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
@@ -139,6 +140,10 @@
   /// removed.
   unsigned SuppressInlineNamespace : 1;
 
+  /// Ignore qualifiers and tag keywords as specified by elaborated type sugar,
+  /// instead letting the underlying type print as normal.
+  unsigned SuppressElaboration : 1;
+
   /// Suppress printing of variable initializers.
   ///
   /// This flag is used when printing the loop variable in a for-range
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D149677: [clang][TypePrinter] Add option to skip over elaborated types

2023-05-26 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua added inline comments.



Comment at: clang/lib/AST/TypePrinter.cpp:1570
 
+  if (Policy.IgnoreElaboratedQualifiers) {
+printBefore(T->getNamedType(), OS);

aaron.ballman wrote:
> So, effectively, the idea here is: you want the ability to skip printing the 
> elaborated keyword and nested name specifier, and you additionally want to 
> skip use of `ElaboratedTypePolicyRAII` when calling 
> `printBefore()`/`printAfter()` because that forces suppression of tags and 
> scopes?
> 
> I think what I'm struggling with a bit is that this is doing three things at 
> once; one is the elaboration keyword (so we no longer print `typename` or 
> `struct` when `IncludeTagDefinition` is false), another is the nested name 
> specifier (we no longer print the leading foo::bar), and the third is that we 
> no longer suppress tags and scopes when printing the underlying type. That 
> makes it tricky to figure out how to name this thing, but the best I could 
> come up with is: `SuppressElaboration` which isn't really different from 
> `IgnoreElaboration` at all. So I think either of those names is "fine", but 
> I'm still a bit uncomfortable about how complex the interactions are becoming.
> another is the nested name specifier (we no longer print the leading 
> foo::bar), and the third is that we no longer suppress tags and scopes when 
> printing the underlying type

I would say that this is the primary desired behavior of the option. More 
specifically, it's //not// that we don't print the nested name specifier and no 
longer suppress those options, but rather, we print the underlying type with 
the options as specified by the policy. `SuppressTagKeyword`, `SuppressScope`, 
and `FullyQualifiedName` work as expected (from my perspective). The 
interaction with `IncludeTagDefinition` dropping the keyword wasn't explicitly 
intended, but it is still consistent with printing the canonical type (which 
would also drop the keyword).

One last name idea to throw out there, in case it seems worth discussing: 
`DesugarElaboratedTypes`. In that case, I'd probably also move the check up 
above L1559 and we treat the entire `ElaboratedType` as if it did not exist.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D149677

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


[PATCH] D150985: [clang] Allow fp in atomic fetch max/min builtins

2023-05-26 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added a comment.

In D150985#4369279 , @tra wrote:

> As I said, I'm OK with the patch in principle, I just don't know what other 
> factors I may be missing.
>
> Tests seem to be missing for c11 variants of the builtins.

will add test for c11 variants.




Comment at: clang/test/Sema/atomic-ops.c:209
+  __atomic_fetch_min(D, 3, memory_order_seq_cst);
+  __atomic_fetch_max(P, 3, memory_order_seq_cst);
   __atomic_fetch_max(p, 3);   // expected-error {{too few 
arguments to function call, expected 3, have 2}}

tra wrote:
> Is that intentional that we now allow atomic max on a `int **P` ? My 
> understanding that we were supposed to allow additional FP types only.
you are right. here should emit a diag "must be a pointer to integer or 
supported floating point type". will fix.



Comment at: clang/test/SemaOpenCL/atomic-ops.cl:65
+  __opencl_atomic_fetch_min(f, 1, memory_order_seq_cst, 
memory_scope_work_group);
+  __opencl_atomic_fetch_max(f, 1, memory_order_seq_cst, 
memory_scope_work_group);
 

tra wrote:
> We probably want to add tests for `double`, too.
will do


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

https://reviews.llvm.org/D150985

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


[PATCH] D151572: [clang][ConstantEmitter] have tryEmitPrivate try ConstExprEmitter fast-path first

2023-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 526131.
nickdesaulniers added a comment.

- one more style update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151572

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1657,9 +1657,8 @@
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (auto value = D.evaluateValue()) {
+  if (APValue *value = D.evaluateValue())
 return tryEmitPrivateForMemory(*value, destType);
-  }
 
   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
   // reference is a constant expression, and the reference binds to a 
temporary,
@@ -1673,10 +1672,11 @@
   const Expr *E = D.getInit();
   assert(E && "No initializer to emit");
 
-  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
-  auto C =
-ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
-  return (C ? emitForMemory(C, destType) : nullptr);
+  QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
+  if (llvm::Constant *C = ConstExprEmitter(*this).Visit(const_cast(E),
+nonMemoryDestType))
+return emitForMemory(C, destType);
+  return nullptr;
 }
 
 llvm::Constant *
@@ -1743,6 +1743,10 @@
 QualType destType) {
   assert(!destType->isVoidType() && "can't emit a void constant");
 
+  if (llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), destType))
+return C;
+
   Expr::EvalResult Result;
 
   bool Success = false;
@@ -1752,13 +1756,10 @@
   else
 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
 
-  llvm::Constant *C;
   if (Success && !Result.HasSideEffects)
-C = tryEmitPrivate(Result.Val, destType);
-  else
-C = ConstExprEmitter(*this).Visit(const_cast(E), destType);
+return tryEmitPrivate(Result.Val, destType);
 
-  return C;
+  return nullptr;
 }
 
 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType 
QT) {


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1657,9 +1657,8 @@
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (auto value = D.evaluateValue()) {
+  if (APValue *value = D.evaluateValue())
 return tryEmitPrivateForMemory(*value, destType);
-  }
 
   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
   // reference is a constant expression, and the reference binds to a temporary,
@@ -1673,10 +1672,11 @@
   const Expr *E = D.getInit();
   assert(E && "No initializer to emit");
 
-  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
-  auto C =
-ConstExprEmitter(*this).Visit(const_cast(E), nonMemoryDestType);
-  return (C ? emitForMemory(C, destType) : nullptr);
+  QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
+  if (llvm::Constant *C = ConstExprEmitter(*this).Visit(const_cast(E),
+nonMemoryDestType))
+return emitForMemory(C, destType);
+  return nullptr;
 }
 
 llvm::Constant *
@@ -1743,6 +1743,10 @@
 QualType destType) {
   assert(!destType->isVoidType() && "can't emit a void constant");
 
+  if (llvm::Constant *C =
+  ConstExprEmitter(*this).Visit(const_cast(E), destType))
+return C;
+
   Expr::EvalResult Result;
 
   bool Success = false;
@@ -1752,13 +1756,10 @@
   else
 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
 
-  llvm::Constant *C;
   if (Success && !Result.HasSideEffects)
-C = tryEmitPrivate(Result.Val, destType);
-  else
-C = ConstExprEmitter(*this).Visit(const_cast(E), destType);
+return tryEmitPrivate(Result.Val, destType);
 
-  return C;
+  return nullptr;
 }
 
 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151572: [clang][ConstantEmitter] have tryEmitPrivate try ConstExprEmitter fast-path first

2023-05-26 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Did you intentionally skip moving the ConstExprEmitter call in 
tryEmitPrivateForVarInit?  (VarDecl::evaluateValue calls the constant 
evaluator.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151572

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


[PATCH] D151575: [clang][diagnostics] Always show include stacks on errors

2023-05-26 Thread Zenong Zhang via Phabricator via cfe-commits
SlaterLatiao created this revision.
Herald added a project: All.
SlaterLatiao requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Fixes PR#62001.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151575

Files:
  clang/lib/Frontend/DiagnosticRenderer.cpp
  clang/test/Misc/Inputs/include-stack-on-error-1.h
  clang/test/Misc/Inputs/include-stack-on-error-2.h
  clang/test/Misc/Inputs/include-stack-on-error-3.h
  clang/test/Misc/include-stack-on-error-1.cpp
  clang/test/Misc/include-stack-on-error-2.cpp


Index: clang/test/Misc/include-stack-on-error-2.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-2.cpp
@@ -0,0 +1,15 @@
+// Test duplicate include stacks that are not on a new error are skipped.
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I 
%S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-3.h"
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function for call to 'b1'
+// This include should be skipped due to duplicate include location.
+// NOTESTACK-NOT:  In file included from
+// NOTESTACK: note: candidate function not viable
+// NOTESTACK:  In file included from
+// NOTESTACK: error: invalid operands to binary expression
+// NOTESTACK:  In file included from
+// NOTESTACK: note: in instantiation of function template specialization
\ No newline at end of file
Index: clang/test/Misc/include-stack-on-error-1.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-1.cpp
@@ -0,0 +1,25 @@
+// Test duplicate include stacks on a new error are not skipped.
+// RUN: not %clang_cc1 -fsyntax-only -I %S/Inputs %s 2>&1 | FileCheck %s 
-check-prefix=STACK
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I 
%S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-2.h"
+
+// STACK:  In file included from
+// STACK: error: no matching function for call to 'b1'
+// STACK-NOT:  In file included from
+// STACK: note: candidate function not viable
+// STACK:  In file included from
+// STACK: error: invalid operands to binary expression
+// STACK-NOT:  In file included from
+// STACK: note: in instantiation of function template specialization
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function for call to 'b1'
+// NOTESTACK:  In file included from
+// NOTESTACK: note: candidate function not viable
+// NOTESTACK:  In file included from
+// NOTESTACK: error: invalid operands to binary expression
+// NOTESTACK:  In file included from
+// NOTESTACK: note: in instantiation of function template specialization
+
Index: clang/test/Misc/Inputs/include-stack-on-error-3.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-3.h
@@ -0,0 +1,5 @@
+void b1();
+void c() {
+b1(0);
+b2("0", "0");
+}
\ No newline at end of file
Index: clang/test/Misc/Inputs/include-stack-on-error-2.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-2.h
@@ -0,0 +1,4 @@
+void c() {
+b1(0);
+b2("0", "0");
+}
\ No newline at end of file
Index: clang/test/Misc/Inputs/include-stack-on-error-1.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-1.h
@@ -0,0 +1,2 @@
+void b1();
+template  void b2(T x, T y) { x + y; }
\ No newline at end of file
Index: clang/lib/Frontend/DiagnosticRenderer.cpp
===
--- clang/lib/Frontend/DiagnosticRenderer.cpp
+++ clang/lib/Frontend/DiagnosticRenderer.cpp
@@ -167,6 +167,10 @@
   PLoc.isInvalid() ? FullSourceLoc()
: FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
 
+  // Reset `LastIncludeLoc` on a new error so that the include stacks are
+  // not skipped.
+  if (Level == DiagnosticsEngine::Error)
+LastIncludeLoc = SourceLocation();
   // Skip redundant include stacks altogether.
   if (LastIncludeLoc == IncludeLoc)
 return;


Index: clang/test/Misc/include-stack-on-error-2.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-2.cpp
@@ -0,0 +1,15 @@
+// Test duplicate include stacks that are not on a new error are skipped.
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-3.h"
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function

[PATCH] D150446: [analyzer] Check ArraySubscriptExprs in ArrayBoundCheckerV2

2023-05-26 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

@NoQ **Re: ElementRegion hacks:** Your suggestion is very convincing, and I 
agree that while my idea would bring some clarity to some particular issues, 
overall it would just worsen the "chaotic heap of classes" situation. The only 
advantage of my solution is that it would be an incremental change; but it's 
only incrementing the amount of problems, so I think I won't continue working 
on it.

On the other hand, I'd be interested in participating in the implementation of 
your suggestion. Unfortunately I don't have enough capacity to just sit down 
and start coding it; but I could suggest this reorganization as a potential 
thesis topic for a student/intern. (Our team regularly gets interns from Eötvös 
Loránd University; if one of them is interested, then perhaps we could tackle 
this issue with me in a mentor / advisor role, and the student creating the 
bulk of the code reorganization commits. These are very far-fetched plans, but 
I'd be glad to see the cleanup that you suggested and I'll try to contribute 
what I can. Of course if you have a more concrete plan for doing this rewrite, 
then instead of intruding I'm happy to help with e.g. reviews.)

**Re: this review:**

> One straightforward implication is that this way [checking 
> PreStmt] we avoid dealing with multiplication/division 
> when calculating offsets.

Unfortunately this is not the case, because the size of the arrays (calculated 
by `clang::ento::getDynamicExtent()` in DynamicExtent.cpp 
) is still 
expressed in bytes ("CharUnits") and we need to multiply the index with 
`sizeof(elemType)` before we can compare it to this value. The distinguishing 
feature of ArrayBoundCheckerV2 is that it has some (ad-hoc but useful) logic 
for reasoning about some multiplications; that part is not changed by this 
commit.

Now that you mention it, I see that it would be //nice// to avoid bothering 
with byte offsets and multiplications in the simple case when we want to take a 
single `int` from an array of `int`s. To achieve this we'd need to introduce 
extent handling functions that measure the size of arrays in number of elements 
(of what kind?) instead of bytes; right now I don't know how difficult would it 
be to achieve that. (As far as I see the extent is usually either a constant 
[that can be readily divided], or it's a freshly conjured symbol... Are those 
symbols used for anything meaningful? Can we ever put an upper bound on them?) 
However this all should probably belong to a separate commit/review/discourse 
thread.

**Re: PreStmt:** That's a very good idea, but I feel that it belongs 
to the "engine level" and it's mostly orthogonal to the behavior this checker. 
My short-term (or at most medium-term) goal is to move this checker out of 
alpha (fix bugs, squash common false positives, improve messages etc.) and here 
I accept the limitation that (like all the currently "stable" checkers) it's 
mostly limited to loop-less code. On a longer term it'd be interesting to work 
on improving the loop handling engine (or just adding a gimmicky "loop 
prediction" ability to this checker); but I don't have concrete plans that far 
ahead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150446

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


[PATCH] D151576: Fix runtime crash inside __kmpc_init_allocator

2023-05-26 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 created this revision.
jyu2 added reviewers: ABataev, jdoerfert.
jyu2 added projects: OpenMP, clang.
Herald added a project: All.
jyu2 requested review of this revision.
Herald added subscribers: openmp-commits, cfe-commits, jplehr, sstefan1.

It seems load of traits.addr should be passed in runtime call.  Currently
the load of load traits.addr gets passed cause runtime to fail.

To fix this, skip the call to EmitLoadOfScalar for extra load.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151576

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/target_parallel_for_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_simd_uses_allocators_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_uses_allocators_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_uses_allocators.c
  clang/test/OpenMP/target_uses_allocators_codegen.cpp
  openmp/libomptarget/test/mapping/target_uses_allocator.c

Index: openmp/libomptarget/test/mapping/target_uses_allocator.c
===
--- /dev/null
+++ openmp/libomptarget/test/mapping/target_uses_allocator.c
@@ -0,0 +1,56 @@
+// RUN: %libomptarget-compile-run-and-check-generic
+
+#include 
+#include 
+
+#define N 1024
+
+int test_omp_aligned_alloc_on_device() {
+  int errors = 0;
+
+  omp_memspace_handle_t memspace = omp_default_mem_space;
+  omp_alloctrait_t traits[2] = {{omp_atk_alignment, 64}, {omp_atk_access, 64}};
+  omp_allocator_handle_t alloc =
+  omp_init_allocator(omp_default_mem_space, 1, traits);
+
+#pragma omp target map(tofrom : errors) uses_allocators(alloc(traits))
+  {
+int *x;
+int not_correct_array_values = 0;
+
+x = (int *)omp_aligned_alloc(64, N * sizeof(int), alloc);
+if (x == NULL) {
+  errors++;
+} else {
+#pragma omp parallel for simd simdlen(16) aligned(x : 64)
+  for (int i = 0; i < N; i++) {
+x[i] = i;
+  }
+
+#pragma omp parallel for simd simdlen(16) aligned(x : 64)
+  for (int i = 0; i < N; i++) {
+if (x[i] != i) {
+#pragma omp atomic write
+  not_correct_array_values = 1;
+}
+  }
+  if (not_correct_array_values) {
+errors++;
+  }
+  omp_free(x, alloc);
+}
+  }
+
+  omp_destroy_allocator(alloc);
+
+  return errors;
+}
+
+int main() {
+  int errors = 0;
+  if (test_omp_aligned_alloc_on_device())
+printf("FAILE\n");
+  else
+// CHECK: PASSED
+printf("PASSED\n");
+}
Index: clang/test/OpenMP/target_uses_allocators_codegen.cpp
===
--- clang/test/OpenMP/target_uses_allocators_codegen.cpp
+++ clang/test/OpenMP/target_uses_allocators_codegen.cpp
@@ -78,8 +78,7 @@
 // CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca ptr,
 // CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
 // CHECK: [[TRAITS_ADDR:%.+]] = load ptr, ptr [[TRAITS_ADDR_REF]],
-// CHECK: [[TRAITS:%.+]] = load ptr, ptr [[TRAITS_ADDR]],
-// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_allocator(i32 %{{.+}}, ptr null, i32 10, ptr [[TRAITS]])
+// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_allocator(i32 %{{.+}}, ptr null, i32 10, ptr [[TRAITS_ADDR]])
 // CHECK: [[CONV:%.+]] = ptrtoint ptr [[ALLOCATOR]] to i64
 // CHECK: store i64 [[CONV]], ptr [[MY_ALLOCATOR_ADDR]],
 
Index: clang/test/OpenMP/target_uses_allocators.c
===
--- clang/test/OpenMP/target_uses_allocators.c
+++ clang/test/OpenMP/target_uses_allocators.c
@@ -132,8 +132,7 @@
 // CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca ptr,
 // CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
 // CHECK: [[TRAITS_ADDR:%.+]] = load ptr, ptr [[TRAITS_ADDR_REF]],
-// CHECK: [[TRAITS:%.+]] = load ptr, ptr [[TRAITS_ADDR]],
-// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_allocator(i32 %{{.+}}, ptr null, i32 10, ptr [[TRAITS]])
+// CHECK: [[ALLOCATOR:%.+]] = call ptr @__kmpc_init_allocator(i32 %{{.+}}, ptr null, i32 10, ptr [[TRAITS_ADDR]])
 // CHECK: [[CONV:%.+]] = ptrtoint ptr [[ALLOCATOR]] to i64
 // CHECK: store i64 [[CONV]], ptr [[MY_ALLOCATOR_ADDR]],
 
Index: clang/test/OpenMP/target_teams_uses_allocators_codegen.cpp
===
--- clang/test/OpenMP/target_teams_uses_allocators_codegen.cpp
+++ clang/test/OpenMP/target_teams_uses_allocators_codegen.cpp
@@ -78,8 +78,7 @@
 // CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca ptr,
 // CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
 // CHECK: [[TRAITS_ADDR:%.+]] = load ptr, ptr [[TRAITS_ADDR_REF]],
-// C

[PATCH] D151576: Fix runtime crash inside __kmpc_init_allocator

2023-05-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151576

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


[PATCH] D151572: [clang][ConstantEmitter] have tryEmitPrivate try ConstExprEmitter fast-path first

2023-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D151572#4376697 , @efriedma wrote:

> Did you intentionally skip moving the ConstExprEmitter call in 
> tryEmitPrivateForVarInit?  (VarDecl::evaluateValue calls the constant 
> evaluator.)

Yes, I'll do that in a follow up patch as it results in quite a few test 
failures that I'm looking into now.  Triple check my messages on LLVM Discord. 
;)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151572

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


[PATCH] D151575: [clang][diagnostics] Always show include stacks on errors

2023-05-26 Thread Zenong Zhang via Phabricator via cfe-commits
SlaterLatiao updated this revision to Diff 526144.
SlaterLatiao added a comment.

- Add newline to end of file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151575

Files:
  clang/lib/Frontend/DiagnosticRenderer.cpp
  clang/test/Misc/Inputs/include-stack-on-error-1.h
  clang/test/Misc/Inputs/include-stack-on-error-2.h
  clang/test/Misc/Inputs/include-stack-on-error-3.h
  clang/test/Misc/include-stack-on-error-1.cpp
  clang/test/Misc/include-stack-on-error-2.cpp


Index: clang/test/Misc/include-stack-on-error-2.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-2.cpp
@@ -0,0 +1,15 @@
+// Test duplicate include stacks that are not on a new error are skipped.
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I 
%S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-3.h"
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function for call to 'b1'
+// This include should be skipped due to duplicate include location.
+// NOTESTACK-NOT:  In file included from
+// NOTESTACK: note: candidate function not viable
+// NOTESTACK:  In file included from
+// NOTESTACK: error: invalid operands to binary expression
+// NOTESTACK:  In file included from
+// NOTESTACK: note: in instantiation of function template specialization
Index: clang/test/Misc/include-stack-on-error-1.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-1.cpp
@@ -0,0 +1,24 @@
+// Test duplicate include stacks on a new error are not skipped.
+// RUN: not %clang_cc1 -fsyntax-only -I %S/Inputs %s 2>&1 | FileCheck %s 
-check-prefix=STACK
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I 
%S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-2.h"
+
+// STACK:  In file included from
+// STACK: error: no matching function for call to 'b1'
+// STACK-NOT:  In file included from
+// STACK: note: candidate function not viable
+// STACK:  In file included from
+// STACK: error: invalid operands to binary expression
+// STACK-NOT:  In file included from
+// STACK: note: in instantiation of function template specialization
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function for call to 'b1'
+// NOTESTACK:  In file included from
+// NOTESTACK: note: candidate function not viable
+// NOTESTACK:  In file included from
+// NOTESTACK: error: invalid operands to binary expression
+// NOTESTACK:  In file included from
+// NOTESTACK: note: in instantiation of function template specialization
Index: clang/test/Misc/Inputs/include-stack-on-error-3.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-3.h
@@ -0,0 +1,5 @@
+void b1();
+void c() {
+b1(0);
+b2("0", "0");
+}
Index: clang/test/Misc/Inputs/include-stack-on-error-2.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-2.h
@@ -0,0 +1,4 @@
+void c() {
+b1(0);
+b2("0", "0");
+}
Index: clang/test/Misc/Inputs/include-stack-on-error-1.h
===
--- /dev/null
+++ clang/test/Misc/Inputs/include-stack-on-error-1.h
@@ -0,0 +1,2 @@
+void b1();
+template  void b2(T x, T y) { x + y; }
Index: clang/lib/Frontend/DiagnosticRenderer.cpp
===
--- clang/lib/Frontend/DiagnosticRenderer.cpp
+++ clang/lib/Frontend/DiagnosticRenderer.cpp
@@ -167,6 +167,10 @@
   PLoc.isInvalid() ? FullSourceLoc()
: FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
 
+  // Reset `LastIncludeLoc` on a new error so that the include stacks are
+  // not skipped.
+  if (Level == DiagnosticsEngine::Error)
+LastIncludeLoc = SourceLocation();
   // Skip redundant include stacks altogether.
   if (LastIncludeLoc == IncludeLoc)
 return;


Index: clang/test/Misc/include-stack-on-error-2.cpp
===
--- /dev/null
+++ clang/test/Misc/include-stack-on-error-2.cpp
@@ -0,0 +1,15 @@
+// Test duplicate include stacks that are not on a new error are skipped.
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-show-note-include-stack -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=NOTESTACK
+
+#include "include-stack-on-error-1.h"
+#include "include-stack-on-error-3.h"
+
+// NOTESTACK:  In file included from
+// NOTESTACK: error: no matching function for call to 'b1'
+// This include should be skipped due to duplicate include location.
+// NOTESTACK-NOT:  In file included from
+// NOTE

[PATCH] D151477: [clang][ExtractAPI] Refactor serializer to the CRTP

2023-05-26 Thread Erick Velez via Phabricator via cfe-commits
evelez7 updated this revision to Diff 526148.
evelez7 added a comment.

Address review feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151477

Files:
  clang/include/clang/ExtractAPI/Serialization/SerializerBase.h
  clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
  clang/lib/ExtractAPI/CMakeLists.txt
  clang/lib/ExtractAPI/Serialization/SerializerBase.cpp
  clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp

Index: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
===
--- clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -14,16 +14,11 @@
 #include "clang/ExtractAPI/Serialization/SymbolGraphSerializer.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Version.h"
-#include "clang/ExtractAPI/API.h"
-#include "clang/ExtractAPI/APIIgnoresList.h"
 #include "clang/ExtractAPI/DeclarationFragments.h"
-#include "clang/ExtractAPI/Serialization/SerializerBase.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
-#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
-#include "llvm/Support/JSON.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/VersionTuple.h"
 #include 
@@ -541,19 +536,16 @@
 Array generateParentContexts(const RecordTy &Record, const APISet &API,
  Language Lang) {
   Array ParentContexts;
-  generatePathComponents(Record, API,
- [Lang, &ParentContexts](const PathComponent &PC) {
-   ParentContexts.push_back(
-   serializeParentContext(PC, Lang));
- });
+  generatePathComponents(
+  Record, API, [Lang, &ParentContexts](const PathComponent &PC) {
+ParentContexts.push_back(serializeParentContext(PC, Lang));
+  });
 
   return ParentContexts;
 }
 
 } // namespace
 
-void SymbolGraphSerializer::anchor() {}
-
 /// Defines the format version emitted by SymbolGraphSerializer.
 const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
 
@@ -670,7 +662,7 @@
   Relationships.emplace_back(std::move(Relationship));
 }
 
-void SymbolGraphSerializer::serializeGlobalFunctionRecord(
+void SymbolGraphSerializer::visitGlobalFunctionRecord(
 const GlobalFunctionRecord &Record) {
   auto Obj = serializeAPIRecord(Record);
   if (!Obj)
@@ -679,7 +671,7 @@
   Symbols.emplace_back(std::move(*Obj));
 }
 
-void SymbolGraphSerializer::serializeGlobalVariableRecord(
+void SymbolGraphSerializer::visitGlobalVariableRecord(
 const GlobalVariableRecord &Record) {
   auto Obj = serializeAPIRecord(Record);
   if (!Obj)
@@ -688,7 +680,7 @@
   Symbols.emplace_back(std::move(*Obj));
 }
 
-void SymbolGraphSerializer::serializeEnumRecord(const EnumRecord &Record) {
+void SymbolGraphSerializer::visitEnumRecord(const EnumRecord &Record) {
   auto Enum = serializeAPIRecord(Record);
   if (!Enum)
 return;
@@ -697,7 +689,7 @@
   serializeMembers(Record, Record.Constants);
 }
 
-void SymbolGraphSerializer::serializeStructRecord(const StructRecord &Record) {
+void SymbolGraphSerializer::visitStructRecord(const StructRecord &Record) {
   auto Struct = serializeAPIRecord(Record);
   if (!Struct)
 return;
@@ -706,7 +698,7 @@
   serializeMembers(Record, Record.Fields);
 }
 
-void SymbolGraphSerializer::serializeObjCContainerRecord(
+void SymbolGraphSerializer::visitObjCContainerRecord(
 const ObjCContainerRecord &Record) {
   auto ObjCContainer = serializeAPIRecord(Record);
   if (!ObjCContainer)
@@ -743,7 +735,7 @@
   }
 }
 
-void SymbolGraphSerializer::serializeMacroDefinitionRecord(
+void SymbolGraphSerializer::visitMacroDefinitionRecord(
 const MacroDefinitionRecord &Record) {
   auto Macro = serializeAPIRecord(Record);
 
@@ -758,28 +750,28 @@
   case APIRecord::RK_Unknown:
 llvm_unreachable("Records should have a known kind!");
   case APIRecord::RK_GlobalFunction:
-serializeGlobalFunctionRecord(*cast(Record));
+visitGlobalFunctionRecord(*cast(Record));
 break;
   case APIRecord::RK_GlobalVariable:
-serializeGlobalVariableRecord(*cast(Record));
+visitGlobalVariableRecord(*cast(Record));
 break;
   case APIRecord::RK_Enum:
-serializeEnumRecord(*cast(Record));
+visitEnumRecord(*cast(Record));
 break;
   case APIRecord::RK_Struct:
-serializeStructRecord(*cast(Record));
+visitStructRecord(*cast(Record));
 break;
   case APIRecord::RK_ObjCInterface:
-serializeObjCContainerRecord(*cast(Record));
+visitObjCContainerRecord(*cast(Record));
 break;
   case APIRecord::RK_ObjCProtocol:
-serializeObjCContainerRecord(*cast(Record));
+visitObjCContainerRecord(*cast(Record));
 break;
   case APIRecord::RK_MacroDefinition:
-serializeMacr

[PATCH] D151492: Add fastmath attributes to llvm.call_intrinsic

2023-05-26 Thread Jeff Niu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9346dc6f675e: Add fastmath attributes to llvm.call_intrinsic 
(authored by electriclilies, committed by Mogball).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151492

Files:
  mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
  mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
  mlir/test/Dialect/LLVMIR/call-intrin.mlir


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call reassoc <4 x float> @llvm.x86.sse41.round.ss(<4 x float> 
, <4 x float> , i32 1)
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : 
(vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = 
#llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.cpp
@@ -95,7 +95,7 @@
 
 /// Builder for LLVM_CallIntrinsicOp
 static LogicalResult
-convertCallLLVMIntrinsicOp(CallIntrinsicOp &op, llvm::IRBuilderBase &builder,
+convertCallLLVMIntrinsicOp(CallIntrinsicOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
   llvm::Module *module = builder.GetInsertBlock()->getModule();
   llvm::Intrinsic::ID id =
@@ -114,6 +114,8 @@
   } else {
 fn = llvm::Intrinsic::getDeclaration(module, id, {});
   }
+  FastmathFlagsInterface itf = op;
+  builder.setFastMathFlags(getFastmathFlags(itf));
 
   auto *inst =
   builder.CreateCall(fn, moduleTranslation.lookupValues(op.getOperands()));
Index: mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
===
--- mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
+++ mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td
@@ -867,19 +867,24 @@
 // CallIntrinsicOp
 //======//
 
-def LLVM_CallIntrinsicOp : LLVM_Op<"call_intrinsic"> {
+def LLVM_CallIntrinsicOp
+: LLVM_Op<"call_intrinsic",
+  [DeclareOpInterfaceMethods]> {
   let summary = "Call to an LLVM intrinsic function.";
   let description = [{
 Call the specified llvm intrinsic. If the intrinsic is overloaded, use
 the MLIR function type of this op to determine which intrinsic to call.
 }];
-  let arguments = (ins StrAttr:$intrin, Variadic:$args);
+  let arguments = (ins StrAttr:$intrin, Variadic:$args,
+   DefaultValuedAttr:$fastmathFlags);
   let results = (outs Variadic:$results);
   let llvmBuilder = [{
 return convertCallLLVMIntrinsicOp(op, builder, moduleTranslation);
   }];
   let assemblyFormat = [{
-$intrin `(` $args `)` `:` functional-type($args, $results) attr-dict
+$intrin `(` $args `)` `:` functional-type($args, $results)
+  custom(attr-dict)
   }];
 }
 


Index: mlir/test/Dialect/LLVMIR/call-intrin.mlir
===
--- mlir/test/Dialect/LLVMIR/call-intrin.mlir
+++ mlir/test/Dialect/LLVMIR/call-intrin.mlir
@@ -5,13 +5,13 @@
 // CHECK: declare ptr @malloc(i64)
 // CHECK: declare void @free(ptr)
 // CHECK: define <4 x float> @round_sse41() {
-// CHECK:  %1 = call <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
+// CHECK:  %1 = call reassoc <4 x float> @llvm.x86.sse41.round.ss(<4 x float> , <4 x float> , i32 1)
 // CHECK:  ret <4 x float> %1
 // CHECK: }
 llvm.func @round_sse41() -> vector<4xf32> {
 %0 = llvm.mlir.constant(1 : i32) : i32
 %1 = llvm.mlir.constant(dense<0.2> : vector<4xf32>) : vector<4xf32>
-%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {}
+%res = llvm.call_intrinsic "llvm.x86.sse41.round.ss"(%1, %1, %0) : (vector<4xf32>, vector<4xf32>, i32) -> vector<4xf32> {fastmathFlags = #llvm.fastmath}
 llvm.return %res: vector<4xf32>
 }
 
Index: mlir/lib/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTra

[PATCH] D151578: [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in ObjC language guesser

2023-05-26 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton created this revision.
benhamilton added a reviewer: MyDeveloperDay.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, owenpan.
benhamilton requested review of this revision.

This adds to the ObjC language guesser a few more common macros used
in ObjC headers. These can help distinguish ObjC headers which
otherwise lack ObjC types from C++ headers.

Contributed by danblakemore.

Tested:

  New tests included. Ran unit tests with:
  ```
  % cmake -S llvm -B build -G Ninja && \
ninja -C build FormatTests && \
./build/tools/clang/unittests/Format/FormatTests 
--gtest_filter="*FormatTestObjC*"
  
  (snip)
  [--] 24 tests from FormatTestObjC (265 ms total)
  
  [--] Global test environment tear-down
  [==] 26 tests from 2 test suites ran. (270 ms total)
  [  PASSED  ] 26 tests.
  ```


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151578

Files:
  clang/lib/Format/Format.cpp
  clang/test/Format/dump-config-objc-macros.h
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,20 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXPORT int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,7 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2744,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,20 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXPORT int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,7 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2744,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151578: [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in ObjC language guesser

2023-05-26 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 526151.
benhamilton added a comment.

Fix auto-complete-o.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151578

Files:
  clang/lib/Format/Format.cpp
  clang/test/Format/dump-config-objc-macros.h
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,20 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXTERN int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,7 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2744,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,20 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXTERN int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,7 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2744,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151578: [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in ObjC language guesser

2023-05-26 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 526154.
benhamilton added a comment.

Add `FOUNDATION_EXTERN` alias for `FOUNDATION_EXPORT` (Apple `#define`s the 
former to the latter).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151578

Files:
  clang/lib/Format/Format.cpp
  clang/test/Format/dump-config-objc-macros.h
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,26 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXPORT void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXTERN int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,8 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2745,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,26 @@
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXPORT void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
Index: clang/test/Format/dump-config-objc-macros.h
===
--- /dev/null
+++ clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXTERN int kConstant;
+
+NS_ASSUME_NONNULL_END
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2687,6 +2687,8 @@
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2745,7 @@
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151581: [clang][modules] NFCI: Distinguish written/effective umbrella directories

2023-05-26 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: benlangmuir, bnbarham.
Herald added a subscriber: ributzka.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

For modules with umbrellas, we track how they were written in the module map. 
Unfortunately, the getter for the umbrella directory conflates the "as written" 
directory and the "effective" directory (either the written one or the parent 
of the written umbrella header).

This patch makes the distinction between "as written" and "effective" umbrella 
directories clearer. No functional change intended.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151581

Files:
  clang/include/clang/Basic/Module.h
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Basic/Module.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2846,11 +2846,11 @@
 }
 
 // Emit the umbrella header, if there is one.
-if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
+if (auto UmbrellaHeader = Mod->getWrittenUmbrellaHeader()) {
   RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
   Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
 UmbrellaHeader.NameAsWritten);
-} else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
+} else if (auto UmbrellaDir = Mod->getWrittenUmbrellaDir()) {
   RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
   Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
 UmbrellaDir.NameAsWritten);
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -5713,9 +5713,9 @@
   std::string Filename = std::string(Blob);
   ResolveImportedPath(F, Filename);
   if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
-if (!CurrentModule->getUmbrellaHeader()) {
+if (!CurrentModule->getWrittenUmbrellaHeader()) {
   // FIXME: NameAsWritten
-  ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
+  ModMap.setWrittenUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
 }
 // Note that it's too late at this point to return out of date if the
 // name from the PCM doesn't match up with the one in the module map,
@@ -5751,9 +5751,9 @@
   std::string Dirname = std::string(Blob);
   ResolveImportedPath(F, Dirname);
   if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
-if (!CurrentModule->getUmbrellaDir()) {
+if (!CurrentModule->getWrittenUmbrellaDir()) {
   // FIXME: NameAsWritten
-  ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
+  ModMap.setWrittenUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
 }
   }
   break;
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -282,14 +282,14 @@
 
 static void collectAllSubModulesWithUmbrellaHeader(
 const Module &Mod, SmallVectorImpl &SubMods) {
-  if (Mod.getUmbrellaHeader())
+  if (Mod.getWrittenUmbrellaHeader())
 SubMods.push_back(&Mod);
   for (auto *M : Mod.submodules())
 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
 }
 
 void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
-  const Module::Header &UmbrellaHeader = Mod.getUmbrellaHeader();
+  Module::Header UmbrellaHeader = Mod.getWrittenUmbrellaHeader();
   assert(UmbrellaHeader.Entry && "Module must use umbrella header");
   const FileID &File = SourceMgr.translateFile(UmbrellaHeader.Entry);
   SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);
@@ -298,7 +298,7 @@
 return;
 
   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
-  const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
+  const DirectoryEntry *Dir = Mod.getEffectiveUmbrellaDir();
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   std::error_code EC;
   for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -266,7 +266,8 @@
   << UmbrellaMod->getFullModuleName();
   else
 // Record this umbrella header.
-setUmbrellaHeader(Mod, *File, Header.FileName, RelativePathName.

[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread NagaChaitanya Vellanki via Phabricator via cfe-commits
chaitanyav updated this revision to Diff 526159.
chaitanyav marked 4 inline comments as done.
chaitanyav added a comment.

Make changes as per comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

Files:
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
@@ -52,6 +52,9 @@
   bool empty() const noexcept;
 };
 
+class error_code {
+};
+
 // the check should be able to match std lib calls even if the functions are
 // declared inside inline namespaces
 inline namespace v1 {
@@ -72,6 +75,10 @@
 
 void useFuture(const std::future &fut);
 
+std::error_code errorFunc() {
+return std::error_code();
+}
+
 void warning() {
   std::async(increment, 42);
   // CHECK-NOTES: [[@LINE-1]]:3: warning: the value returned by this function should be used
@@ -185,6 +192,10 @@
 // CHECK-NOTES: [[@LINE-1]]:5: warning: the value {{.*}} should be used
 // CHECK-NOTES: [[@LINE-2]]:5: note: cast {{.*}} this warning
   }
+
+  errorFunc();
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value {{.*}} should be used
+  // CHECK-NOTES: [[@LINE-2]]:3: note: cast {{.*}} this warning
 }
 
 void noWarning() {
@@ -209,6 +220,8 @@
   std::vector VecNoWarning;
   auto VecEmptyRetval = VecNoWarning.empty();
 
+  (void) errorFunc();
+
   // test using the return value in different kinds of expressions
   useFuture(std::async(increment, 42));
   std::launder(&FNoWarning)->f();
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
@@ -46,5 +46,11 @@
  return value often indicates that the programmer confused the function with
  ``clear()``.
 
+.. option:: CheckedReturnTypes
+
+   Semicolon-separated list of function return types to check.
+   By default the following function return types are checked:
+   `std::error_code, std::expected, boost::system::error_code, abseil::Status`
+
 `cert-err33-c <../cert/err33-c.html>`_ is an alias of this check that checks a
 fixed and large set of standard library functions.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -248,6 +248,10 @@
   constructor initializers. Correctly handle constructor arguments as being
   sequenced when constructor call is written as list-initialization.
 
+- Extend :doc:`bugprone-unused-return-value
+  ` check to check for all functions
+  with specified return types using the ``CheckedReturnTypes`` option.
+
 - Deprecated :doc:`cert-dcl21-cpp
   ` check.
 
Index: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
@@ -27,6 +27,7 @@
 
 private:
   std::string CheckedFunctions;
+  const std::vector CheckedReturnTypes;
 };
 
 } // namespace clang::tidy::bugprone
Index: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "UnusedReturnValueCheck.h"
+#include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -27,7 +28,6 @@
   return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node,
   Finder, Builder);
 }
-
 } // namespace
 
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
@@ -124,19 +124,30 @@
"::sigismember;"
"::strcasecmp;"
"::strsignal;"
-   "::ttyname")) {}
+   "::ttyname")),
+  CheckedReturnTypes(utils::options::parseStringList(

[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp:129
+  CheckedReturnTypes(utils::options::parseStringList(
+  Options.get("CheckedReturnTypes", "std::error_code;"
+"std::expected;"

good but put those all as fully qualified names (starting with ::) like in 
Checkedfunctions, and align documentation



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst:53
+   By default the following function return types are checked:
+   `std::error_code, std::expected, boost::system::error_code, abseil::Status`
+

split this, into `::std::error_code`, `::std::expected`, and so on...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

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


[PATCH] D32199: [TySan] A Type Sanitizer (Clang)

2023-05-26 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 526163.
fhahn added a comment.

Rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D32199

Files:
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/Sanitizers.def
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenTBAA.cpp
  clang/lib/CodeGen/SanitizerMetadata.cpp
  clang/lib/CodeGen/SanitizerMetadata.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/CodeGen/sanitize-type-attr.cpp
  clang/test/Driver/sanitizer-ld.c

Index: clang/test/Driver/sanitizer-ld.c
===
--- clang/test/Driver/sanitizer-ld.c
+++ clang/test/Driver/sanitizer-ld.c
@@ -268,6 +268,28 @@
 // CHECK-ASAN-MYRIAD-NOT: "-lc"
 // CHECK-ASAN-MYRIAD: libclang_rt.asan-sparcel.a"
 
+// RUN: %clangxx %s -### -o %t.o 2>&1 \
+// RUN: --target=x86_64-unknown-linux -fuse-ld=ld -stdlib=platform -lstdc++ \
+// RUN: -fsanitize=type \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-TYSAN-LINUX-CXX %s
+//
+// CHECK-TYSAN-LINUX-CXX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-TYSAN-LINUX-CXX-NOT: stdc++
+// CHECK-TYSAN-LINUX-CXX: "--whole-archive" "{{.*}}libclang_rt.tysan{{[^.]*}}.a" "--no-whole-archive"
+// CHECK-TYSAN-LINUX-CXX: stdc++
+
+// RUN: %clangxx -fsanitize=type -### %s 2>&1 \
+// RUN: -mmacosx-version-min=10.6 \
+// RUN: --target=x86_64-apple-darwin13.4.0 -fuse-ld=ld -stdlib=platform \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-TYSAN-DARWIN-CXX %s
+// CHECK-TYSAN-DARWIN-CXX: "{{.*}}ld{{(.exe)?}}"
+// CHECK-TYSAN-DARWIN-CXX: libclang_rt.tysan_osx_dynamic.dylib
+// CHECK-TYSAN-DARWIN-CXX-NOT: -lc++abi
+
 // RUN: %clangxx -### %s 2>&1 \
 // RUN: --target=x86_64-unknown-linux -fuse-ld=ld -stdlib=platform -lstdc++ \
 // RUN: -fsanitize=thread \
Index: clang/test/CodeGen/sanitize-type-attr.cpp
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-type-attr.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck -check-prefix=WITHOUT %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s -fsanitize=type | FileCheck -check-prefix=TYSAN %s
+// RUN: echo "src:%s" | sed -e 's/\\//g' > %t
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s -fsanitize=type -fsanitize-blacklist=%t | FileCheck -check-prefix=BL %s
+
+// The sanitize_type attribute should be attached to functions
+// when TypeSanitizer is enabled, unless no_sanitize("type") attribute
+// is present.
+
+// WITHOUT:  NoTYSAN1{{.*}}) [[NOATTR:#[0-9]+]]
+// BL:  NoTYSAN1{{.*}}) [[NOATTR:#[0-9]+]]
+// TYSAN:  NoTYSAN1{{.*}}) [[NOATTR:#[0-9]+]]
+__attribute__((no_sanitize("type"))) int NoTYSAN1(int *a) { return *a; }
+
+// WITHOUT:  NoTYSAN2{{.*}}) [[NOATTR]]
+// BL:  NoTYSAN2{{.*}}) [[NOATTR]]
+// TYSAN:  NoTYSAN2{{.*}}) [[NOATTR]]
+__attribute__((no_sanitize("type"))) int NoTYSAN2(int *a);
+int NoTYSAN2(int *a) { return *a; }
+
+// WITHOUT:  NoTYSAN3{{.*}}) [[NOATTR:#[0-9]+]]
+// BL:  NoTYSAN3{{.*}}) [[NOATTR:#[0-9]+]]
+// TYSAN:  NoTYSAN3{{.*}}) [[NOATTR:#[0-9]+]]
+__attribute__((no_sanitize("type"))) int NoTYSAN3(int *a) { return *a; }
+
+// WITHOUT:  TYSANOk{{.*}}) [[NOATTR]]
+// BL:  TYSANOk{{.*}}) [[NOATTR]]
+// TYSAN: TYSANOk{{.*}}) [[WITH:#[0-9]+]]
+int TYSANOk(int *a) { return *a; }
+
+// WITHOUT:  TemplateTYSANOk{{.*}}) [[NOATTR]]
+// BL:  TemplateTYSANOk{{.*}}) [[NOATTR]]
+// TYSAN: TemplateTYSANOk{{.*}}) [[WITH]]
+template 
+int TemplateTYSANOk() { return i; }
+
+// WITHOUT:  TemplateNoTYSAN{{.*}}) [[NOATTR]]
+// BL:  TemplateNoTYSAN{{.*}}) [[NOATTR]]
+// TYSAN: TemplateNoTYSAN{{.*}}) [[NOATTR]]
+template 
+__attribute__((no_sanitize("type"))) int TemplateNoTYSAN() { return i; }
+
+int force_instance = TemplateTYSANOk<42>() + TemplateNoTYSAN<42>();
+
+// Check that __cxx_global_var_init* get the sanitize_type attribute.
+int global1 = 0;
+int global2 = *(int *)((char *)&global1 + 1);
+// WITHOUT: @__cxx_global_var_init{{.*}}[[NOATTR:#[0-9]+]]
+// BL: @__cxx_global_var_init{{.*}}[[NOATTR:#[0-9]+]]
+// TYSAN: @__cxx_global_var_init{{.*}}[[WITH:#[0-9]+]]
+
+// Make sure that we don't add globals to the list for which we don't have a
+// specific type description.
+// FIXME: We now have a type description for this type and a global is added. Should it?
+struct SX {
+  int a, b;
+};
+SX sx;
+
+// WITHOUT: attributes

[PATCH] D148723: [clang] Restrict Inline Builtin to non-static, non-odr linkage

2023-05-26 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

@jyu2 : could you test that patch in your setup ? Also I can't find the bug id 
associated with your original bug anymore...


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

https://reviews.llvm.org/D148723

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


[PATCH] D151503: [CUDA] correctly install cuda_wrappers/bits/shared_ptr_base.h

2023-05-26 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added inline comments.



Comment at: clang/lib/Headers/CMakeLists.txt:516
   COMPONENT cuda-resource-headers)
 
 install(

Do we need an install target for `${cuda_wrapper_bits_files}` for the 
`cuda-resource-headers` component as well? It seems to be the case because this 
patch is treating `${cuda_wrapper_bits_files}` as part of 
`cuda-resource-headers`.

```
add_header_target("cuda-resource-headers" 
"${cuda_files};${cuda_wrapper_files};${cuda_wrapper_bits_files}")
```




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151503

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


[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread NagaChaitanya Vellanki via Phabricator via cfe-commits
chaitanyav updated this revision to Diff 526173.
chaitanyav marked an inline comment as done.
chaitanyav added a comment.

use fully qualified name in code and documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

Files:
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
  clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp
@@ -52,6 +52,9 @@
   bool empty() const noexcept;
 };
 
+class error_code {
+};
+
 // the check should be able to match std lib calls even if the functions are
 // declared inside inline namespaces
 inline namespace v1 {
@@ -72,6 +75,10 @@
 
 void useFuture(const std::future &fut);
 
+std::error_code errorFunc() {
+return std::error_code();
+}
+
 void warning() {
   std::async(increment, 42);
   // CHECK-NOTES: [[@LINE-1]]:3: warning: the value returned by this function should be used
@@ -185,6 +192,10 @@
 // CHECK-NOTES: [[@LINE-1]]:5: warning: the value {{.*}} should be used
 // CHECK-NOTES: [[@LINE-2]]:5: note: cast {{.*}} this warning
   }
+
+  errorFunc();
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value {{.*}} should be used
+  // CHECK-NOTES: [[@LINE-2]]:3: note: cast {{.*}} this warning
 }
 
 void noWarning() {
@@ -209,6 +220,8 @@
   std::vector VecNoWarning;
   auto VecEmptyRetval = VecNoWarning.empty();
 
+  (void) errorFunc();
+
   // test using the return value in different kinds of expressions
   useFuture(std::async(increment, 42));
   std::launder(&FNoWarning)->f();
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
@@ -46,5 +46,11 @@
  return value often indicates that the programmer confused the function with
  ``clear()``.
 
+.. option:: CheckedReturnTypes
+
+   Semicolon-separated list of function return types to check.
+   By default the following function return types are checked:
+   `::std::error_code`, `::std::expected`, `::boost::system::error_code`, `::abseil::Status`
+
 `cert-err33-c <../cert/err33-c.html>`_ is an alias of this check that checks a
 fixed and large set of standard library functions.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -248,6 +248,10 @@
   constructor initializers. Correctly handle constructor arguments as being
   sequenced when constructor call is written as list-initialization.
 
+- Extend :doc:`bugprone-unused-return-value
+  ` check to check for all functions
+  with specified return types using the ``CheckedReturnTypes`` option.
+
 - Deprecated :doc:`cert-dcl21-cpp
   ` check.
 
Index: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
@@ -27,6 +27,7 @@
 
 private:
   std::string CheckedFunctions;
+  const std::vector CheckedReturnTypes;
 };
 
 } // namespace clang::tidy::bugprone
Index: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "UnusedReturnValueCheck.h"
+#include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -27,7 +28,6 @@
   return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node,
   Finder, Builder);
 }
-
 } // namespace
 
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
@@ -124,19 +124,30 @@
"::sigismember;"
"::strcasecmp;"
"::strsignal;"
-   "::ttyname")) {}
+   "::ttyname")),
+  CheckedReturnTyp

[PATCH] D151584: [clang][modules] NFCI: Use `DirectoryEntryRef` for umbrella directory

2023-05-26 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: benlangmuir, bnbarham.
Herald added a subscriber: ributzka.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This removes some deprecated uses of `DirectoryEntry::getName()`.

Depends on D151581 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151584

Files:
  clang/include/clang/Basic/Module.h
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Basic/Module.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -5750,7 +5750,8 @@
   // See comments in SUBMODULE_UMBRELLA_HEADER
   std::string Dirname = std::string(Blob);
   ResolveImportedPath(F, Dirname);
-  if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
+  if (auto Umbrella =
+  PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
 if (!CurrentModule->getWrittenUmbrellaDir()) {
   // FIXME: NameAsWritten
   ModMap.setWrittenUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -298,7 +298,7 @@
 return;
 
   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
-  const DirectoryEntry *Dir = Mod.getEffectiveUmbrellaDir();
+  OptionalDirectoryEntryRef Dir = Mod.getEffectiveUmbrellaDir();
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   std::error_code EC;
   for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
@@ -318,7 +318,7 @@
 if (!ModMap.isHeaderInUnavailableModule(*Header)) {
   // Find the relative path that would access this header.
   SmallString<128> RelativePath;
-  computeRelativePath(FileMgr, Dir, *Header, RelativePath);
+  computeRelativePath(FileMgr, *Dir, *Header, RelativePath);
   Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
   << Mod.getFullModuleName() << RelativePath;
 }
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1186,9 +1186,9 @@
 }
 
 void ModuleMap::setWrittenUmbrellaDir(
-Module *Mod, const DirectoryEntry *UmbrellaDir, const Twine &NameAsWritten,
+Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten,
 const Twine &PathRelativeToRootModuleDirectory) {
-  Mod->Umbrella = UmbrellaDir;
+  Mod->Umbrella = &UmbrellaDir.getMapEntry();
   Mod->UmbrellaAsWritten = NameAsWritten.str();
   Mod->UmbrellaRelativeToRootModuleDirectory =
   PathRelativeToRootModuleDirectory.str();
@@ -2515,16 +2515,14 @@
   }
 
   // Look for this file.
-  const DirectoryEntry *Dir = nullptr;
+  OptionalDirectoryEntryRef Dir;
   if (llvm::sys::path::is_absolute(DirName)) {
-if (auto D = SourceMgr.getFileManager().getDirectory(DirName))
-  Dir = *D;
+Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
   } else {
 SmallString<128> PathName;
 PathName = Directory->getName();
 llvm::sys::path::append(PathName, DirName);
-if (auto D = SourceMgr.getFileManager().getDirectory(PathName))
-  Dir = *D;
+Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(PathName);
   }
 
   if (!Dir) {
@@ -2558,7 +2556,7 @@
 return;
   }
 
-  if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
+  if (Module *OwningModule = Map.UmbrellaDirs[*Dir]) {
 Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
   << OwningModule->getFullModuleName();
 HadError = true;
@@ -2566,7 +2564,7 @@
   }
 
   // Record this umbrella directory.
-  Map.setWrittenUmbrellaDir(ActiveModule, Dir, DirNameAsWritten, DirName);
+  Map.setWrittenUmbrellaDir(ActiveModule, *Dir, DirNameAsWritten, DirName);
 }
 
 /// Parse a module export declaration.
Index: clang/lib/Basic/Module.cpp
===
--- clang/lib/Basic/Module.cpp
+++ clang/lib/Basic/Module.cpp
@@ -263,12 +263,12 @@
   return nameParts.empty();
 }
 
-const DirectoryEntry *Module::getEffectiveUmbrellaDir() const {
+OptionalDirectoryEntryRef Module::getEffectiveUmbrellaDir() const {
   if (const auto *ME = Umbrella.dyn_cast())
 return FileEntryRef(*ME).getDir();
-  if (const auto *ME = Umbrella.dyn_cast())
-return ME;
-  return nullptr;
+  if (const auto *ME = Umbrella.dyn_cast())
+return DirectoryEntryRef(*ME);
+  return std::nullopt;
 }
 
 void Module::addTopHeader(const FileEntry *File) {
Index: clang/include/clang/

[PATCH] D150430: Implement BufferOverlap check for sprint/snprintf

2023-05-26 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner added a comment.

@steakhal did you get a chance to look at my comment?

I would really love to see this merged upstream if you think this could be a 
beneficial change :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150430

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


[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.

LGTM, you may consider reducing commit message (aka review description by 
removing example and error from it, and leaving just plain description of a 
change).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

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


[PATCH] D151383: [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread NagaChaitanya Vellanki via Phabricator via cfe-commits
chaitanyav added a comment.

In D151383#4377043 , @PiotrZSL wrote:

> LGTM, you may consider reducing commit message (aka review description by 
> removing example and error from it, and leaving just plain description of a 
> change).

got it, will make sure to remove them from the arc generated commit message.




Comment at: clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp:159
+   anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
+ hasAnyReturnType(RetTypeVec)
   .bind("match";

PiotrZSL wrote:
> Consider:
> 
> hasAnyReturnType -> 
> `returns(hasCanonicalType(hasDeclaration(namedDecl(matchers::matchesAnyListedName(RetTypeVec`
> Note that to use matchesAnyListedName, you should save RetTypeVec  as class 
> member, just to be safe.
I followed the code in ForRangeCopyCheck.cpp and made the changes accordingly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151383

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


[PATCH] D148723: [clang] Restrict Inline Builtin to non-static, non-odr linkage

2023-05-26 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added a comment.

In D148723#4376946 , 
@serge-sans-paille wrote:

> @jyu2 : could you test that patch in your setup ? Also I can't find the bug 
> id associated with your original bug anymore...

I just submit bug in https://github.com/llvm/llvm-project/issues/62958 and 
assign that to you.


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

https://reviews.llvm.org/D148723

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


[PATCH] D151586: [clang][modules] NFCI: Extract optionality out of `Module::{Header,DirectoryName}`

2023-05-26 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: benlangmuir, bnbarham.
Herald added a subscriber: ributzka.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Most users of `Module::Header` already assume its `Entry` is populated. Enforce 
this assumption in the type system and handle the only case where this is not 
the case by wrapping the whole struct in `std::optional`. Do the same for 
`Module::DirectoryName`.

Depends on D151584 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151586

Files:
  clang/include/clang/Basic/Module.h
  clang/lib/Basic/Module.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2849,11 +2849,11 @@
 if (auto UmbrellaHeader = Mod->getWrittenUmbrellaHeader()) {
   RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
   Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
-UmbrellaHeader.NameAsWritten);
+UmbrellaHeader->NameAsWritten);
 } else if (auto UmbrellaDir = Mod->getWrittenUmbrellaDir()) {
   RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
   Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
-UmbrellaDir.NameAsWritten);
+UmbrellaDir->NameAsWritten);
 }
 
 // Emit the headers.
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1973,10 +1973,11 @@
 std::string Filename = std::string(key.Filename);
 if (key.Imported)
   Reader.ResolveImportedPath(M, Filename);
-// FIXME: NameAsWritten
-Module::Header H = {std::string(key.Filename), "",
-FileMgr.getOptionalFileRef(Filename)};
-ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
+if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
+  // FIXME: NameAsWritten
+  Module::Header H = {std::string(key.Filename), "", *FE};
+  ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
+}
 HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
   }
 
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -289,9 +289,9 @@
 }
 
 void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
-  Module::Header UmbrellaHeader = Mod.getWrittenUmbrellaHeader();
-  assert(UmbrellaHeader.Entry && "Module must use umbrella header");
-  const FileID &File = SourceMgr.translateFile(UmbrellaHeader.Entry);
+  auto UmbrellaHeader = Mod.getWrittenUmbrellaHeader();
+  assert(UmbrellaHeader && "Module must use umbrella header");
+  const FileID &File = SourceMgr.translateFile(UmbrellaHeader->Entry);
   SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);
   if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
  ExpectedHeadersLoc))
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1291,7 +1291,7 @@
 
   // Notify callbacks that we just added a new header.
   for (const auto &Cb : Callbacks)
-Cb->moduleMapAddHeader(Header.Entry->getName());
+Cb->moduleMapAddHeader(Header.Entry.getName());
 }
 
 OptionalFileEntryRef
@@ -2543,7 +2543,7 @@
 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
  I != E && !EC; I.increment(EC)) {
   if (auto FE = SourceMgr.getFileManager().getOptionalFileRef(I->path())) {
-Module::Header Header = {"", std::string(I->path()), FE};
+Module::Header Header = {"", std::string(I->path()), *FE};
 Headers.push_back(std::move(Header));
   }
 }
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -365,16 +365,16 @@
   // Note that Module->PrivateHeaders will not be a TopHeader.
 
   if (auto UmbrellaHeader = Module->getWrittenUmbrellaHeader()) {
-Module->addTopHeader(UmbrellaHeader.Entry);
+Module->addTopHeader(UmbrellaHeader->Entry);
 if (Module->Parent)
   // Include the umbrella header for submodules.
-  addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
+  

[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivateForVarInit try ConstExprEmitter fast-path first

2023-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers created this revision.
Herald added a project: All.
nickdesaulniers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

As suggested by @efriedma in:
https://reviews.llvm.org/D76096#4370369

Signed-off-by: Nick Desaulniers 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151587

Files:
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/test/CodeGenCXX/const-init-cxx1y.cpp
  clang/test/CodeGenCXX/cxx0x-initializer-references.cpp
  clang/test/CodeGenCXX/designated-init.cpp

Index: clang/test/CodeGenCXX/designated-init.cpp
===
--- clang/test/CodeGenCXX/designated-init.cpp
+++ clang/test/CodeGenCXX/designated-init.cpp
@@ -4,7 +4,8 @@
 struct A { int x, y[3]; };
 struct B { A a; };
 
-// CHECK: @b ={{.*}} global %{{[^ ]*}} { %{{[^ ]*}} { i32 1, [3 x i32] [i32 2, i32 5, i32 4] } }
+// CHECK: @b = global %struct.B zeroinitializer, align 4
+
 B b = {(A){1, 2, 3, 4}, .a.y[1] = 5};
 
 union U {
@@ -19,10 +20,10 @@
   C c;
 };
 
-// CHECK: @d1 = {{.*}} { i32 1, [3 x %[[U:.*]]] [%[[U]] { i32 2 }, %[[U]] { i32 5 }, %[[U]] { i32 4 }] }
+// CHECK: @d1 = global %struct.D zeroinitializer, align 4
 D d1 = {(C){1, {{.n=2}, {.f=3}, {.n=4}}}, .c.u[1].n = 5};
 
-// CHECK: @d2 = {{.*}} { i32 1, { %[[U]], float, %[[U]] } { %[[U]] { i32 2 }, float 5.{{0*}}e+00, %[[U]] { i32 4 } } }
+// CHECK: @d2 = global %struct.D zeroinitializer, align 4
 D d2 = {(C){1, 2, 3, 4}, .c.u[1].f = 5};
 
 struct Bitfield {
@@ -34,7 +35,7 @@
   int n;
   Bitfield b;
 };
-// CHECK: @bitfield = {{.*}} { i32 1, { i8, i8, [2 x i8] } { i8 42, i8 2, [2 x i8] undef } }
+// CHECK: @bitfield = global %struct.WithBitfield zeroinitializer, align 4
 WithBitfield bitfield = {1, (Bitfield){2, 3, 4}, .b.b = 5};
 
 struct String {
@@ -43,7 +44,7 @@
 struct WithString {
   String str;
 };
-// CHECK: @string = {{.*}} [12 x i8] c"Hello World\00" } }
+// CHECK: @string = global %struct.WithString zeroinitializer, align 1
 WithString string = {(String){"hello world"}, .str.buffer[0] = 'H', .str.buffer[6] = 'W'};
 
 struct LargeArray {
@@ -52,7 +53,7 @@
 struct WithLargeArray {
   LargeArray arr;
 };
-// CHECK: @large ={{.*}} global { { <{ [11 x i32], [4085 x i32] }> } } { { <{ [11 x i32], [4085 x i32] }> } { <{ [11 x i32], [4085 x i32] }> <{ [11 x i32] [i32 1, i32 2, i32 3, i32 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 10], [4085 x i32] zeroinitializer }> } }
+// CHECK: @large = global %struct.WithLargeArray zeroinitializer, align 4
 WithLargeArray large = {(LargeArray){1, 2, 3}, .arr.arr[10] = 10};
 
 union OverwritePaddingWithBitfield {
@@ -62,5 +63,6 @@
 struct WithOverwritePaddingWithBitfield {
   OverwritePaddingWithBitfield a;
 };
-// CHECK: @overwrite_padding ={{.*}} global { { i8, i8 } } { { i8, i8 } { i8 3, i8 1 } }
+// CHECK: @overwrite_padding = global %struct.WithOverwritePaddingWithBitfield zeroinitializer, align 1
+
 WithOverwritePaddingWithBitfield overwrite_padding = {(OverwritePaddingWithBitfield){1}, .a.bitfield = 3};
Index: clang/test/CodeGenCXX/cxx0x-initializer-references.cpp
===
--- clang/test/CodeGenCXX/cxx0x-initializer-references.cpp
+++ clang/test/CodeGenCXX/cxx0x-initializer-references.cpp
@@ -6,7 +6,7 @@
 const char (&extended_string_ref)[5] = {"hi"};
 
 // This binds directly to a string literal object.
-// CHECK: @nonextended_string_ref ={{.*}} constant ptr @.str
+// CHECK: @nonextended_string_ref = constant [3 x i8] c"hi\00", align 4
 const char (&nonextended_string_ref)[3] = {"hi"};
 
 namespace reference {
Index: clang/test/CodeGenCXX/const-init-cxx1y.cpp
===
--- clang/test/CodeGenCXX/const-init-cxx1y.cpp
+++ clang/test/CodeGenCXX/const-init-cxx1y.cpp
@@ -23,11 +23,11 @@
   struct A { int &&temporary; int x; };
   constexpr int f(int &r) { r *= 9; return r - 12; }
   A a = { 6, f(a.temporary) };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1aE_ = internal global i32 54
+  // CHECK: @_ZGRN21ModifyStaticTemporary1aE_ = internal global i32 6, align 4
   // CHECK: @_ZN21ModifyStaticTemporary1aE ={{.*}} global {{.*}} ptr @_ZGRN21ModifyStaticTemporary1aE_, i32 42
 
   A b = { 7, ++b.temporary };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1bE_ = internal global i32 8
+  // CHECK: @_ZGRN21ModifyStaticTemporary1bE_ = internal global i32 7, align 4
   // CHECK: @_ZN21ModifyStaticTemporary1bE ={{.*}} global {{.*}} ptr @_ZGRN21ModifyStaticTemporary1bE_, i32 8
 
   // Can't emit all of 'c' as a constant here, so emit the initial value of
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1215,11 +1215,6 @@
 return Visit(E->getSubExpr(), T);
   }
 
-  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
- 

[PATCH] D151590: [Driver] Add ClangFlags::TargetSpecific to simplify err_drv_unsupported_opt_for_target processing

2023-05-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: aaron.ballman, jansvoboda11, pengfei, power-llvm-team.
Herald added subscribers: jrtc27, fedor.sergeev, nemanjai, jyknight.
Herald added a project: All.
MaskRay requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

clang/lib/Driver/ToolChains/Clang.cpp has a lot of fragments like the following:

  if (const Arg *A = Args.getLastArg(...)) {
if (Triple is xxx)
  A->render(Args, CmdArgs);
else
  D.Diag(diag::err_drv_unsupported_opt_for_target) << ...;
  }

The problem is more apparent with a recent surge of AIX-specific options.

Introduce the TargetSpecific flag so that we can move the target-specific
options to ToolChains/*.cpp and ToolChains/Arch/*.cpp and overload the
warn_drv_unused_argument mechanism to give an err_drv_unsupported_opt_for_target
error.

Migrate -march=/-mcpu= and some AIX-specific options to use this simplified 
pattern.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D151590

Files:
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/lib/Driver/ToolChains/AIX.h
  clang/lib/Driver/ToolChains/Arch/PPC.cpp
  clang/lib/Driver/ToolChains/Arch/Sparc.cpp
  clang/lib/Driver/ToolChains/Clang.cpp

Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6142,23 +6142,6 @@
 }
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
-if (Triple.isOSAIX())
-  CmdArgs.push_back("-mignore-xcoff-visibility");
-else
-  D.Diag(diag::err_drv_unsupported_opt_for_target)
-  << A->getAsString(Args) << TripleStr;
-  }
-
-  if (const Arg *A =
-  Args.getLastArg(options::OPT_mdefault_visibility_export_mapping_EQ)) {
-if (Triple.isOSAIX())
-  A->render(Args, CmdArgs);
-else
-  D.Diag(diag::err_drv_unsupported_opt_for_target)
-  << A->getAsString(Args) << TripleStr;
-  }
-
   if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
 options::OPT_fno_visibility_inlines_hidden, false))
 CmdArgs.push_back("-fvisibility-inlines-hidden");
@@ -6967,10 +6950,6 @@
   Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
 options::OPT_fno_apple_pragma_pack);
 
-  if (Args.hasFlag(options::OPT_fxl_pragma_pack,
-   options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
-CmdArgs.push_back("-fxl-pragma-pack");
-
   // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
   if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
Index: clang/lib/Driver/ToolChains/Arch/Sparc.cpp
===
--- clang/lib/Driver/ToolChains/Arch/Sparc.cpp
+++ clang/lib/Driver/ToolChains/Arch/Sparc.cpp
@@ -118,12 +118,6 @@
 
 std::string sparc::getSparcTargetCPU(const Driver &D, const ArgList &Args,
  const llvm::Triple &Triple) {
-  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
-D.Diag(diag::err_drv_unsupported_opt_for_target)
-<< A->getSpelling() << Triple.getTriple();
-return "";
-  }
-
   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) {
 StringRef CPUName = A->getValue();
 if (CPUName == "native") {
Index: clang/lib/Driver/ToolChains/Arch/PPC.cpp
===
--- clang/lib/Driver/ToolChains/Arch/PPC.cpp
+++ clang/lib/Driver/ToolChains/Arch/PPC.cpp
@@ -87,10 +87,6 @@
 /// Get the (LLVM) name of the PowerPC cpu we are targeting.
 std::string ppc::getPPCTargetCPU(const Driver &D, const ArgList &Args,
  const llvm::Triple &T) {
-  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
-D.Diag(diag::err_drv_unsupported_opt_for_target)
-<< A->getSpelling() << T.getTriple();
-  }
   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
 return normalizeCPUName(A->getValue(), T);
   return getPPCGenericTargetCPU(T);
Index: clang/lib/Driver/ToolChains/AIX.h
===
--- clang/lib/Driver/ToolChains/AIX.h
+++ clang/lib/Driver/ToolChains/AIX.h
@@ -80,6 +80,10 @@
   void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const override;
 
+  void addClangTargetOptions(
+  const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args,
+  Action::OffloadKind DeviceOffloadingKind) const override;
+
   void addProfileRTLibs(const llvm::opt::ArgList &Args,
 llvm

[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivateForVarInit try ConstExprEmitter fast-path first

2023-05-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 526192.
nickdesaulniers added a comment.

- also remove VisitExprWithCleanups, down to two outstanding test failures


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151587

Files:
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/test/CodeGenCXX/const-init-cxx1y.cpp
  clang/test/CodeGenCXX/designated-init.cpp

Index: clang/test/CodeGenCXX/designated-init.cpp
===
--- clang/test/CodeGenCXX/designated-init.cpp
+++ clang/test/CodeGenCXX/designated-init.cpp
@@ -4,7 +4,8 @@
 struct A { int x, y[3]; };
 struct B { A a; };
 
-// CHECK: @b ={{.*}} global %{{[^ ]*}} { %{{[^ ]*}} { i32 1, [3 x i32] [i32 2, i32 5, i32 4] } }
+// CHECK: @b = global %struct.B zeroinitializer, align 4
+
 B b = {(A){1, 2, 3, 4}, .a.y[1] = 5};
 
 union U {
@@ -19,10 +20,10 @@
   C c;
 };
 
-// CHECK: @d1 = {{.*}} { i32 1, [3 x %[[U:.*]]] [%[[U]] { i32 2 }, %[[U]] { i32 5 }, %[[U]] { i32 4 }] }
+// CHECK: @d1 = global %struct.D zeroinitializer, align 4
 D d1 = {(C){1, {{.n=2}, {.f=3}, {.n=4}}}, .c.u[1].n = 5};
 
-// CHECK: @d2 = {{.*}} { i32 1, { %[[U]], float, %[[U]] } { %[[U]] { i32 2 }, float 5.{{0*}}e+00, %[[U]] { i32 4 } } }
+// CHECK: @d2 = global %struct.D zeroinitializer, align 4
 D d2 = {(C){1, 2, 3, 4}, .c.u[1].f = 5};
 
 struct Bitfield {
@@ -34,7 +35,7 @@
   int n;
   Bitfield b;
 };
-// CHECK: @bitfield = {{.*}} { i32 1, { i8, i8, [2 x i8] } { i8 42, i8 2, [2 x i8] undef } }
+// CHECK: @bitfield = global %struct.WithBitfield zeroinitializer, align 4
 WithBitfield bitfield = {1, (Bitfield){2, 3, 4}, .b.b = 5};
 
 struct String {
@@ -43,7 +44,7 @@
 struct WithString {
   String str;
 };
-// CHECK: @string = {{.*}} [12 x i8] c"Hello World\00" } }
+// CHECK: @string = global %struct.WithString zeroinitializer, align 1
 WithString string = {(String){"hello world"}, .str.buffer[0] = 'H', .str.buffer[6] = 'W'};
 
 struct LargeArray {
@@ -52,7 +53,7 @@
 struct WithLargeArray {
   LargeArray arr;
 };
-// CHECK: @large ={{.*}} global { { <{ [11 x i32], [4085 x i32] }> } } { { <{ [11 x i32], [4085 x i32] }> } { <{ [11 x i32], [4085 x i32] }> <{ [11 x i32] [i32 1, i32 2, i32 3, i32 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 0, i32 10], [4085 x i32] zeroinitializer }> } }
+// CHECK: @large = global %struct.WithLargeArray zeroinitializer, align 4
 WithLargeArray large = {(LargeArray){1, 2, 3}, .arr.arr[10] = 10};
 
 union OverwritePaddingWithBitfield {
@@ -62,5 +63,6 @@
 struct WithOverwritePaddingWithBitfield {
   OverwritePaddingWithBitfield a;
 };
-// CHECK: @overwrite_padding ={{.*}} global { { i8, i8 } } { { i8, i8 } { i8 3, i8 1 } }
+// CHECK: @overwrite_padding = global %struct.WithOverwritePaddingWithBitfield zeroinitializer, align 1
+
 WithOverwritePaddingWithBitfield overwrite_padding = {(OverwritePaddingWithBitfield){1}, .a.bitfield = 3};
Index: clang/test/CodeGenCXX/const-init-cxx1y.cpp
===
--- clang/test/CodeGenCXX/const-init-cxx1y.cpp
+++ clang/test/CodeGenCXX/const-init-cxx1y.cpp
@@ -34,8 +34,8 @@
   // 'c.temporary', not the value as modified by the partial evaluation within
   // the initialization of 'c.x'.
   A c = { 10, (++c.temporary, b.x) };
+  // CHECK: @_ZN21ModifyStaticTemporary1cE = global %"struct.ModifyStaticTemporary::A" zeroinitializer
   // CHECK: @_ZGRN21ModifyStaticTemporary1cE_ = internal global i32 10
-  // CHECK: @_ZN21ModifyStaticTemporary1cE ={{.*}} global {{.*}} zeroinitializer
 }
 
 // CHECK: @_ZGRN28VariableTemplateWithConstRef1iIvEE_ = linkonce_odr constant i32 5, align 4
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1211,15 +1211,6 @@
 return Visit(DIE->getExpr(), T);
   }
 
-  llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
-return Visit(E->getSubExpr(), T);
-  }
-
-  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
-QualType T) {
-return Visit(E->getSubExpr(), T);
-  }
-
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
 assert(CAT && "can't emit array init for non-constant-bound array");
@@ -1657,18 +1648,6 @@
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (APValue *value = D.evaluateValue())
-return tryEmitPrivateForMemory(*value, destType);
-
-  // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
-  // reference is a constant expression, and the reference binds to a temporary,
-  // then constant initialization is performed. ConstExprEmitter will
-  // incorrectly em

[PATCH] D151581: [clang][modules] NFCI: Distinguish written/effective umbrella directories

2023-05-26 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Basic/Module.h:655
+  /// Retrieve the explicitly written umbrella directory for this module.
+  DirectoryName getWrittenUmbrellaDir() const {
+if (const auto *ME = Umbrella.dyn_cast())

Nit: I would prefer we use the same `...AsWritten` naming scheme for these 
methods that we use for the `UmbrellaAsWritten` field.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151581

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


[clang-tools-extra] 785b30b - [clang-tidy] Check for specific return types on all functions

2023-05-26 Thread NagaChaitanya Vellanki via cfe-commits

Author: NagaChaitanya Vellanki
Date: 2023-05-26T13:59:18-07:00
New Revision: 785b30b8a33a394a677b1b8ce35c66ba482db169

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

LOG: [clang-tidy] Check for specific return types on all functions

Extend the check to all functions with return types like
 std::error_code, std::expected, boost::system::error_code, 
abseil::Status...

 Resolves issue https://github.com/llvm/llvm-project/issues/62884

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index 6049569b5f581..f8139381d7e01 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "UnusedReturnValueCheck.h"
+#include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -27,7 +28,6 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
   return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node,
   Finder, Builder);
 }
-
 } // namespace
 
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
@@ -124,19 +124,30 @@ 
UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
"::sigismember;"
"::strcasecmp;"
"::strsignal;"
-   "::ttyname")) {}
+   "::ttyname")),
+  CheckedReturnTypes(utils::options::parseStringList(
+  Options.get("CheckedReturnTypes", "::std::error_code;"
+"::std::expected;"
+"::boost::system::error_code;"
+"::abseil::Status"))) {}
 
 void UnusedReturnValueCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "CheckedFunctions", CheckedFunctions);
+  Options.store(Opts, "CheckedReturnTypes",
+utils::options::serializeStringList(CheckedReturnTypes));
 }
 
 void UnusedReturnValueCheck::registerMatchers(MatchFinder *Finder) {
   auto FunVec = utils::options::parseStringList(CheckedFunctions);
+
   auto MatchedCallExpr = expr(ignoringImplicit(ignoringParenImpCasts(
   callExpr(callee(functionDecl(
// Don't match void overloads of checked functions.
unless(returns(voidType())),
-   isInstantiatedFrom(hasAnyName(FunVec)
+   anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
+ returns(hasCanonicalType(hasDeclaration(
+ namedDecl(matchers::matchesAnyListedName(
+ CheckedReturnTypes)
   .bind("match";
 
   auto UnusedInCompoundStmt =

diff  --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
index f16815b0f839e..15881e12ca0c3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
@@ -27,6 +27,7 @@ class UnusedReturnValueCheck : public ClangTidyCheck {
 
 private:
   std::string CheckedFunctions;
+  const std::vector CheckedReturnTypes;
 };
 
 } // namespace clang::tidy::bugprone

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 980be4869ead8..1eb8c5ba4b71b 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -248,6 +248,10 @@ Changes in existing checks
   constructor initializers. Correctly handle constructor arguments as being
   sequenced when constructor call is written as list-initialization.
 
+- Extend :doc:`bugprone-unused-return-value
+  ` check to check for all 
functions
+  with specified return types using the ``CheckedReturnTypes`` option.
+
 - Deprecated :doc:`cert-dcl21-cpp
   ` check.
 

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/u

  1   2   >