[PATCH] D152645: [clangd] Handle DependentNameType in HeuristicResolver::resolveTypeToRecordDecl()

2023-06-10 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Depends on D152500 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152645

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


[PATCH] D152645: [clangd] Handle DependentNameType in HeuristicResolver::resolveTypeToRecordDecl()

2023-06-10 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
nridge added reviewers: hokein, sammccall.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
nridge requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152645

Files:
  clang-tools-extra/clangd/HeuristicResolver.cpp
  clang-tools-extra/clangd/HeuristicResolver.h
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -877,6 +877,22 @@
 }
   )cpp";
   EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
+
+  Code = R"cpp(
+template 
+struct Waldo {
+  void find();
+};
+template 
+struct MetaWaldo {
+  using Type = Waldo;
+};
+template 
+void foo(typename MetaWaldo::Type w) {
+  w.[[find]]();
+}
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
 }
 
 TEST_F(TargetDeclTest, DependentTypes) {
Index: clang-tools-extra/clangd/HeuristicResolver.h
===
--- clang-tools-extra/clangd/HeuristicResolver.h
+++ clang-tools-extra/clangd/HeuristicResolver.h
@@ -94,6 +94,14 @@
   // `E`.
   const Type *resolveExprToType(const Expr *E) const;
   std::vector resolveExprToDecls(const Expr *E) const;
+
+  // Helper function for HeuristicResolver::resolveDependentMember()
+  // which takes a possibly-dependent type `T` and heuristically
+  // resolves it to a CXXRecordDecl in which we can try name lookup.
+  CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) const;
+
+  const Type *
+  resolveDeclsToType(const std::vector &Decls) const;
 };
 
 } // namespace clangd
Index: clang-tools-extra/clangd/HeuristicResolver.cpp
===
--- clang-tools-extra/clangd/HeuristicResolver.cpp
+++ clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -10,6 +10,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/Type.h"
 
 namespace clang {
 namespace clangd {
@@ -29,15 +30,35 @@
   return isa(D);
 };
 
+const Type *HeuristicResolver::resolveDeclsToType(
+const std::vector &Decls) const {
+  if (Decls.size() != 1) // Names an overload set -- just bail.
+return nullptr;
+  if (const auto *TD = dyn_cast(Decls[0])) {
+return Ctx.getTypeDeclType(TD).getTypePtr();
+  }
+  if (const auto *VD = dyn_cast(Decls[0])) {
+return VD->getType().getTypePtrOrNull();
+  }
+  return nullptr;
+}
+
 // Helper function for HeuristicResolver::resolveDependentMember()
 // which takes a possibly-dependent type `T` and heuristically
 // resolves it to a CXXRecordDecl in which we can try name lookup.
-CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
+CXXRecordDecl *HeuristicResolver::resolveTypeToRecordDecl(const Type *T) const {
   assert(T);
 
   // Unwrap type sugar such as type aliases.
   T = T->getCanonicalTypeInternal().getTypePtr();
 
+  if (const auto *DNT = T->getAs()) {
+T = resolveDeclsToType(resolveDependentNameType(DNT));
+if (!T)
+  return nullptr;
+T = T->getCanonicalTypeInternal().getTypePtr();
+  }
+
   if (const auto *RT = T->getAs())
 return dyn_cast(RT->getDecl());
 
@@ -185,18 +206,6 @@
   DTST->getIdentifier(), TemplateFilter);
 }
 
-const Type *resolveDeclsToType(const std::vector &Decls) {
-  if (Decls.size() != 1) // Names an overload set -- just bail.
-return nullptr;
-  if (const auto *TD = dyn_cast(Decls[0])) {
-return TD->getTypeForDecl();
-  }
-  if (const auto *VD = dyn_cast(Decls[0])) {
-return VD->getType().getTypePtrOrNull();
-  }
-  return nullptr;
-}
-
 std::vector
 HeuristicResolver::resolveExprToDecls(const Expr *E) const {
   if (const auto *ME = dyn_cast(E)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D142630: [clang][Interp] Implement virtual function calls

2023-06-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/test/AST/Interp/records.cpp:650
+};
+#endif

aaron.ballman wrote:
> We should also have test cases for calling virtual functions from within a 
> constructor and a destructor, as that has special semantics. e.g., 
> https://godbolt.org/z/snaj1zfM5
That's broken right now of course. I'l add the test and adjust the expected 
output. I'll probably have to save a few bits for "things we're currently 
doing" (like evaluating a constructor), but in a later patch.

FWIW, I expanded your test a bit: https://godbolt.org/z/vq5xT3xvq and it only 
fails in clang - with a reference:
```
  // CWG issue 1517: we're constructing a base class of the object described by
  // 'This', so that object has not yet begun its period of construction and
  // any polymorphic operation on it results in undefined behavior.
```


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

https://reviews.llvm.org/D142630

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


[PATCH] D152632: [Clang] Add warnings for CWG2521

2023-06-10 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill requested changes to this revision.
Endill added a comment.
This revision now requires changes to proceed.

Thank you for working on this!

In D152632#4411587 , @rZhBoYao wrote:

> Few questions:
> I think this applies to all the language modes?

Yes, we rarely limit the scope of DRs, and I'm looking forward to get rid of 
exceptions from this approach (grep "since" in cxx_dr_status.html 
).

> Somehow, https://wg21.link/CWG2521 is not redirecting to 
> https://cplusplus.github.io/CWG/issues/2521.html. Is this normal?

It happens, especially with recently updated DRs. I see it in CWG index 
, so you can 
ignore broken wg21.link.




Comment at: clang/www/cxx_dr_status.html:14936
 User-defined literals and reserved identifiers
-Unknown
+Clang 17
   

This file shouldn't be edited manually. You should write a test in 
`clang/test/CXX/drs/dr25xx.cpp`, and then run `clang/www/make_cxx_dr_status` 
script that updates `cxx_dr_status.html`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152632

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


[PATCH] D152500: [clangd] Handle alias template in HeuristicResolver::resolveTypeToRecordDecl()

2023-06-10 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
Herald added subscribers: jeroen.dobbelaere, kadircet, arphaman.
Herald added a project: All.
nridge updated this revision to Diff 530279.
nridge added a comment.
nridge published this revision for review.
nridge added reviewers: hokein, sammccall.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Make the approach more general


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152500

Files:
  clang-tools-extra/clangd/HeuristicResolver.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp


Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -863,6 +863,20 @@
   )cpp";
   EXPECT_DECLS("CXXDependentScopeMemberExpr",
"template  T convert() const");
+
+  Code = R"cpp(
+template 
+struct Waldo {
+  void find();
+};
+template 
+using Wally = Waldo;
+template 
+void foo(Wally w) {
+  w.[[find]]();
+}
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
 }
 
 TEST_F(TargetDeclTest, DependentTypes) {
Index: clang-tools-extra/clangd/HeuristicResolver.cpp
===
--- clang-tools-extra/clangd/HeuristicResolver.cpp
+++ clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -35,6 +35,9 @@
 CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
   assert(T);
 
+  // Unwrap type sugar such as type aliases.
+  T = T->getCanonicalTypeInternal().getTypePtr();
+
   if (const auto *RT = T->getAs())
 return dyn_cast(RT->getDecl());
 


Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -863,6 +863,20 @@
   )cpp";
   EXPECT_DECLS("CXXDependentScopeMemberExpr",
"template  T convert() const");
+
+  Code = R"cpp(
+template 
+struct Waldo {
+  void find();
+};
+template 
+using Wally = Waldo;
+template 
+void foo(Wally w) {
+  w.[[find]]();
+}
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
 }
 
 TEST_F(TargetDeclTest, DependentTypes) {
Index: clang-tools-extra/clangd/HeuristicResolver.cpp
===
--- clang-tools-extra/clangd/HeuristicResolver.cpp
+++ clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -35,6 +35,9 @@
 CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
   assert(T);
 
+  // Unwrap type sugar such as type aliases.
+  T = T->getCanonicalTypeInternal().getTypePtr();
+
   if (const auto *RT = T->getAs())
 return dyn_cast(RT->getDecl());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9bf9ac8 - [CodeGen] Remove unused declaration createNVPTXRuntimeFunction

2023-06-10 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-06-10T21:52:49-07:00
New Revision: 9bf9ac87d6ddf4d956bc2233c75d40b1f0e83f0b

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

LOG: [CodeGen] Remove unused declaration createNVPTXRuntimeFunction

The corresponding definition was removed by:

  commit 3cc1f1fc1d97952136185f4eafb827694875de17
  Author: Joseph Huber 
  Date:   Thu Oct 8 12:03:11 2020 -0400

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntimeGPU.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
index 5ef4ce1cfd093..c4559b3226bcf 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
@@ -256,12 +256,6 @@ class CGOpenMPRuntimeGPU : public CGOpenMPRuntime {
  ArrayRef ReductionOps,
  ReductionOptionsTy Options) override;
 
-  /// Returns specified OpenMP runtime function for the current OpenMP
-  /// implementation.  Specialized for the NVPTX device.
-  /// \param Function OpenMP runtime function.
-  /// \return Specified function.
-  llvm::FunctionCallee createNVPTXRuntimeFunction(unsigned Function);
-
   /// Translates the native parameter of outlined function if this is required
   /// for target.
   /// \param FD Field decl from captured record for the parameter.



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


[PATCH] D143971: [clang-tidy] Flag more buggy string constructor cases

2023-06-10 Thread Chris Cotter via Phabricator via cfe-commits
ccotter added a comment.

bump please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143971

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


[PATCH] D152634: [Sema] Remove unused isNonTypeNestedNameSpecifier

2023-06-10 Thread Kazu Hirata via Phabricator via cfe-commits
kazu created this revision.
Herald added a project: All.
kazu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The last use was removed by:

  commit 04f131da0b19abff611773c03be9bafb53c753ce
  Author: Richard Smith 
  Date:   Fri Jan 24 15:14:25 2020 -0800


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152634

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaCXXScopeSpec.cpp


Index: clang/lib/Sema/SemaCXXScopeSpec.cpp
===
--- clang/lib/Sema/SemaCXXScopeSpec.cpp
+++ clang/lib/Sema/SemaCXXScopeSpec.cpp
@@ -415,51 +415,6 @@
   return nullptr;
 }
 
-bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
-NestedNameSpecInfo &IdInfo) {
-  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
-  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
- LookupNestedNameSpecifierName);
-
-  // Determine where to perform name lookup
-  DeclContext *LookupCtx = nullptr;
-  bool isDependent = false;
-  if (!ObjectType.isNull()) {
-// This nested-name-specifier occurs in a member access expression, e.g.,
-// x->B::f, and we are looking into the type of the object.
-assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
-LookupCtx = computeDeclContext(ObjectType);
-isDependent = ObjectType->isDependentType();
-  } else if (SS.isSet()) {
-// This nested-name-specifier occurs after another nested-name-specifier,
-// so long into the context associated with the prior 
nested-name-specifier.
-LookupCtx = computeDeclContext(SS, false);
-isDependent = isDependentScopeSpecifier(SS);
-Found.setContextRange(SS.getRange());
-  }
-
-  if (LookupCtx) {
-// Perform "qualified" name lookup into the declaration context we
-// computed, which is either the type of the base of a member access
-// expression or the declaration context associated with a prior
-// nested-name-specifier.
-
-// The declaration context must be complete.
-if (!LookupCtx->isDependentContext() &&
-RequireCompleteDeclContext(SS, LookupCtx))
-  return false;
-
-LookupQualifiedName(Found, LookupCtx);
-  } else if (isDependent) {
-return false;
-  } else {
-LookupName(Found, S);
-  }
-  Found.suppressDiagnostics();
-
-  return Found.getAsSingle();
-}
-
 namespace {
 
 // Callback to only accept typo corrections that can be a valid C++ member
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -6994,9 +6994,6 @@
 }
   };
 
-  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
-NestedNameSpecInfo &IdInfo);
-
   bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,


Index: clang/lib/Sema/SemaCXXScopeSpec.cpp
===
--- clang/lib/Sema/SemaCXXScopeSpec.cpp
+++ clang/lib/Sema/SemaCXXScopeSpec.cpp
@@ -415,51 +415,6 @@
   return nullptr;
 }
 
-bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
-NestedNameSpecInfo &IdInfo) {
-  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
-  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
- LookupNestedNameSpecifierName);
-
-  // Determine where to perform name lookup
-  DeclContext *LookupCtx = nullptr;
-  bool isDependent = false;
-  if (!ObjectType.isNull()) {
-// This nested-name-specifier occurs in a member access expression, e.g.,
-// x->B::f, and we are looking into the type of the object.
-assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
-LookupCtx = computeDeclContext(ObjectType);
-isDependent = ObjectType->isDependentType();
-  } else if (SS.isSet()) {
-// This nested-name-specifier occurs after another nested-name-specifier,
-// so long into the context associated with the prior nested-name-specifier.
-LookupCtx = computeDeclContext(SS, false);
-isDependent = isDependentScopeSpecifier(SS);
-Found.setContextRange(SS.getRange());
-  }
-
-  if (LookupCtx) {
-// Perform "qualified" name lookup into the declaration context we
-// computed, which is either the type of the base of a member access
-// expression or the declaration context associated with a prior
-// nested-name-specifier.
-
-// The declaration context must be complete.
-if (!LookupCtx->isDependentContext() &&
-RequireCompleteDeclContext(SS, LookupCtx))
-  return false;
-
-LookupQualifiedName(Found, LookupCtx);
-  } else if (isDependent) {
-return false;
-  } else {
-

[PATCH] D137872: Implement lambdas with inalloca parameters by forwarding to function without inalloca calling convention.

2023-06-10 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CGClass.cpp:3097
+  FD->getLocation(), FD->getLocation());
+CGF.EmitFunctionBody(FD->getBody());
+CGF.FinishFunction();

Is there any way we can use GenerateCode as the entrypoint here, instead of 
calling EmitFunctionBody directly?  Without this patch, EmitFunctionBody has 
exactly one caller, so this makes the control flow and special cases more 
complicated to reason about.  For example, there's some special coroutine 
handling in GenerateCode.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:1472
+// the call operator body.
+EmitLambdaStaticInvokeBody(cast(FD));
   } else if (FD->isDefaulted() && isa(FD) &&

Does this pass the correct value of "this"?  EmitLambdaStaticInvokeBody creates 
a new alloca to represent "this", but it's already an argument to the function.

Granted, it only matters in really obscure cases, but still.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137872

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


[PATCH] D152632: [Clang] Add warnings for CWG2521

2023-06-10 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao added a reviewer: clang-language-wg.
rZhBoYao added a comment.

Few questions:
I think this applies to all the language modes?
Somehow, https://wg21.link/CWG2521 is not redirecting to 
https://cplusplus.github.io/CWG/issues/2521.html. Is this normal?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152632

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


[PATCH] D152632: [Clang] Add warnings for CWG2521

2023-06-10 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao created this revision.
rZhBoYao added a reviewer: serge-sans-paille.
Herald added a project: All.
rZhBoYao requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

1. Teach -Wuser-defined-literals to warn on using double underscores in literal 
suffix identifiers.
2. Add -Wdeprecated-literal-operator to warn about the use of the first grammar 
production of literal-operator-id, which defaults to off.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152632

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CXX/drs/dr17xx.cpp
  clang/test/CXX/lex/lex.literal/lex.ext/p1.cpp
  clang/test/CXX/lex/lex.literal/lex.ext/p10.cpp
  clang/test/Parser/cxx0x-literal-operators.cpp
  clang/test/SemaCXX/deprecated-literal-operator.cpp
  clang/test/SemaCXX/no-warn-user-defined-literals-in-system-headers.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -14933,7 +14933,7 @@
 https://cplusplus.github.io/CWG/issues/2521.html";>2521
 DR
 User-defined literals and reserved identifiers
-Unknown
+Clang 17
   
   
 https://cplusplus.github.io/CWG/issues/2522.html";>2522
Index: clang/test/SemaCXX/no-warn-user-defined-literals-in-system-headers.cpp
===
--- clang/test/SemaCXX/no-warn-user-defined-literals-in-system-headers.cpp
+++ clang/test/SemaCXX/no-warn-user-defined-literals-in-system-headers.cpp
@@ -2,4 +2,4 @@
 
 #include 
 
-void operator "" bar(long double); // expected-warning{{user-defined literal suffixes not starting with '_' are reserved}}
+void operator "" bar(long double); // expected-warning{{user-defined literal suffixes containing '__' or not starting with '_' are reserved}}
Index: clang/test/SemaCXX/deprecated-literal-operator.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/deprecated-literal-operator.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=c++23 %s -verify -Wdeprecated-literal-operator
+// RUN: %clang_cc1 -std=c++23 %s -verify -Wdeprecated
+
+namespace depr {
+
+decltype(sizeof 0) operator ""  _\u{3C0}___(long double); // \
+expected-warning{{identifier '_π___' preceded by space(s) in the literal operator declaration is deprecated}} \
+expected-warning{{user-defined literal suffixes containing '__' or not starting with '_' are reserved}}
+
+template  consteval auto
+operator""   _div() { return (... / (Chars - '0')); } // OK, deprecated \
+expected-warning{{identifier '_div' preceded by space(s) in the literal operator declaration is deprecated}}
+
+} // namespace depr
+
+using depr::operator"" _\u{3C0}___, depr::operator""_div; // \
+expected-warning{{identifier '_π___' preceded by space(s) in the literal operator declaration is deprecated}}
+
+[[maybe_unused]] constexpr auto div = 841_div;
Index: clang/test/Parser/cxx0x-literal-operators.cpp
===
--- clang/test/Parser/cxx0x-literal-operators.cpp
+++ clang/test/Parser/cxx0x-literal-operators.cpp
@@ -3,6 +3,6 @@
 void operator "" (const char *); // expected-error {{expected identifier}}
 void operator "k" foo(const char *); // \
   expected-error {{string literal after 'operator' must be '""'}} \
-  expected-warning{{user-defined literal suffixes not starting with '_' are reserved}}
+  expected-warning{{user-defined literal suffixes containing '__' or not starting with '_' are reserved}}
 void operator "" tester (const char *); // \
-  expected-warning{{user-defined literal suffixes not starting with '_' are reserved}}
+  expected-warning{{user-defined literal suffixes containing '__' or not starting with '_' are reserved}}
Index: clang/test/CXX/lex/lex.literal/lex.ext/p10.cpp
===
--- clang/test/CXX/lex/lex.literal/lex.ext/p10.cpp
+++ clang/test/CXX/lex/lex.literal/lex.ext/p10.cpp
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
 using size_t = decltype(sizeof(int));
-void operator "" wibble(const char *); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}}
-void operator "" wibble(const char *, size_t); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}}
+void operator "" wibble(const char *); // expected-warning {{user-defined literal suffixes containing '__' or not starting with '_' are reserved; no literal will invoke this operator}}
+void operator "" wibble(const char *, size_t); // expected-warning {{user-defined literal suff

[PATCH] D70401: [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs

2023-06-10 Thread David Sawatzke via Phabricator via cfe-commits
david-sawatzke added a comment.

Thank you for the reply, I've compiled this with the most recent patch and also 
didn't see a problem (but can't get it running with rustc). Building the .ll 
with the older patch, the same issue also occurs, so I *do* think its the old 
patch version?
Here is the log output for the riscv32e
F27886013: llvm_output 

(and as a sanity check riscv32i)
F27886014: llvm_output_riscv32i 

The errant code seems to get introduced here:

  # *** IR Dump After Prologue/Epilogue Insertion & Frame Finalization 
(prologepilog) ***:
  # Machine code for function _ZN13miscomp_repro4test17h065760f827b95d43E: 
NoPHIs, TracksLiveness, NoVRegs, TiedOpsRewritten, TracksDebugUserValues
  
  bb.0.start:
$x2 = frame-destroy ADDI $x8, 0
PseudoRET


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70401

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


[PATCH] D152628: [RISCV] Add __builtin_riscv_zip/unzip for Zbkb to match gcc.

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

We used zip_32/unzip_32, but gcc omitted the _32. Since we lack
an intrinsic header for Zk* it seemed like we should support the
same builtin names.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152628

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbkb.c
  clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbkb-error.c

Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbkb-error.c
===
--- clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbkb-error.c
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbkb-error.c
@@ -1,12 +1,22 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -triple riscv64 -target-feature +zbkb -verify %s -o -
 
-int zip(int rs1)
+long zip(long rs1)
+{
+  return __builtin_riscv_zip(rs1); // expected-error {{builtin requires: 'RV32'}}
+}
+
+long unzip(long rs1)
+{
+  return __builtin_riscv_unzip(rs1); // expected-error {{builtin requires: 'RV32'}}
+}
+
+int zip_32(int rs1)
 {
   return __builtin_riscv_zip_32(rs1); // expected-error {{builtin requires: 'RV32'}}
 }
 
-int unzip(int rs1)
+int unzip_32(int rs1)
 {
   return __builtin_riscv_unzip_32(rs1); // expected-error {{builtin requires: 'RV32'}}
 }
Index: clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbkb.c
===
--- clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbkb.c
+++ clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbkb.c
@@ -23,9 +23,9 @@
 // RV32ZBKB-NEXT:[[TMP1:%.*]] = call i32 @llvm.riscv.zip.i32(i32 [[TMP0]])
 // RV32ZBKB-NEXT:ret i32 [[TMP1]]
 //
-int zip(int rs1)
+long zip(long rs1)
 {
-  return __builtin_riscv_zip_32(rs1);
+  return __builtin_riscv_zip(rs1);
 }
 
 // RV32ZBKB-LABEL: @unzip(
@@ -36,7 +36,33 @@
 // RV32ZBKB-NEXT:[[TMP1:%.*]] = call i32 @llvm.riscv.unzip.i32(i32 [[TMP0]])
 // RV32ZBKB-NEXT:ret i32 [[TMP1]]
 //
-int unzip(int rs1)
+long unzip(long rs1)
+{
+  return __builtin_riscv_unzip(rs1);
+}
+
+// RV32ZBKB-LABEL: @zip_32(
+// RV32ZBKB-NEXT:  entry:
+// RV32ZBKB-NEXT:[[RS1_ADDR:%.*]] = alloca i32, align 4
+// RV32ZBKB-NEXT:store i32 [[RS1:%.*]], ptr [[RS1_ADDR]], align 4
+// RV32ZBKB-NEXT:[[TMP0:%.*]] = load i32, ptr [[RS1_ADDR]], align 4
+// RV32ZBKB-NEXT:[[TMP1:%.*]] = call i32 @llvm.riscv.zip.i32(i32 [[TMP0]])
+// RV32ZBKB-NEXT:ret i32 [[TMP1]]
+//
+int zip_32(int rs1)
+{
+  return __builtin_riscv_zip_32(rs1);
+}
+
+// RV32ZBKB-LABEL: @unzip_32(
+// RV32ZBKB-NEXT:  entry:
+// RV32ZBKB-NEXT:[[RS1_ADDR:%.*]] = alloca i32, align 4
+// RV32ZBKB-NEXT:store i32 [[RS1:%.*]], ptr [[RS1_ADDR]], align 4
+// RV32ZBKB-NEXT:[[TMP0:%.*]] = load i32, ptr [[RS1_ADDR]], align 4
+// RV32ZBKB-NEXT:[[TMP1:%.*]] = call i32 @llvm.riscv.unzip.i32(i32 [[TMP0]])
+// RV32ZBKB-NEXT:ret i32 [[TMP1]]
+//
+int unzip_32(int rs1)
 {
   return __builtin_riscv_unzip_32(rs1);
 }
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -20173,6 +20173,8 @@
   case RISCV::BI__builtin_riscv_xperm4:
   case RISCV::BI__builtin_riscv_xperm8:
   case RISCV::BI__builtin_riscv_brev8:
+  case RISCV::BI__builtin_riscv_zip:
+  case RISCV::BI__builtin_riscv_unzip:
   case RISCV::BI__builtin_riscv_zip_32:
   case RISCV::BI__builtin_riscv_unzip_32: {
 switch (BuiltinID) {
@@ -20216,9 +20218,11 @@
 case RISCV::BI__builtin_riscv_brev8:
   ID = Intrinsic::riscv_brev8;
   break;
+case RISCV::BI__builtin_riscv_zip:
 case RISCV::BI__builtin_riscv_zip_32:
   ID = Intrinsic::riscv_zip;
   break;
+case RISCV::BI__builtin_riscv_unzip:
 case RISCV::BI__builtin_riscv_unzip_32:
   ID = Intrinsic::riscv_unzip;
   break;
Index: clang/include/clang/Basic/BuiltinsRISCV.def
===
--- clang/include/clang/Basic/BuiltinsRISCV.def
+++ clang/include/clang/Basic/BuiltinsRISCV.def
@@ -36,6 +36,8 @@
 TARGET_BUILTIN(__builtin_riscv_brev8, "LiLi", "nc", "zbkb")
 TARGET_BUILTIN(__builtin_riscv_zip_32, "ZiZi", "nc", "zbkb,32bit")
 TARGET_BUILTIN(__builtin_riscv_unzip_32, "ZiZi", "nc", "zbkb,32bit")
+TARGET_BUILTIN(__builtin_riscv_zip, "LiLi", "nc", "zbkb,32bit")
+TA

[PATCH] D152623: [clang-format] Indent Verilog struct literal on new line

2023-06-10 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

So I assume your `'` is a 'DictLiteral`? Does it have to be one? I don't know 
what else maybe a `DictLiteral` in what language and am not so comfortable with 
this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152623

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


[PATCH] D152627: [RISCV] Change the immediate argument to Zvk intrinsics/builtins to i8.

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

This matches gcc. It also lets us fix a bug that the byteselect
predicate was not being evaluated in tablegen. We can't have i8
TImmLeaf in tablegen because i8 isn't a type for any register class.

I've added AutoUpgrade support for the IR intrinsics.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152627

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/test/CodeGen/RISCV/rvk-intrinsics/riscv32-zknd.c
  clang/test/CodeGen/RISCV/rvk-intrinsics/riscv32-zkne.c
  clang/test/CodeGen/RISCV/rvk-intrinsics/riscv32-zksed.c
  clang/test/CodeGen/RISCV/rvk-intrinsics/riscv64-zksed.c
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoZk.td
  llvm/test/CodeGen/RISCV/rv32zknd-intrinsic-autoupgrade.ll
  llvm/test/CodeGen/RISCV/rv32zknd-intrinsic.ll
  llvm/test/CodeGen/RISCV/rv32zkne-intrinsic-autoupgrade.ll
  llvm/test/CodeGen/RISCV/rv32zkne-intrinsic.ll
  llvm/test/CodeGen/RISCV/rv32zksed-intrinsic-autoupgrade.ll
  llvm/test/CodeGen/RISCV/rv32zksed-intrinsic.ll
  llvm/test/CodeGen/RISCV/rv64zksed-intrinsic-autoupgrade.ll
  llvm/test/CodeGen/RISCV/rv64zksed-intrinsic.ll

Index: llvm/test/CodeGen/RISCV/rv64zksed-intrinsic.ll
===
--- llvm/test/CodeGen/RISCV/rv64zksed-intrinsic.ll
+++ llvm/test/CodeGen/RISCV/rv64zksed-intrinsic.ll
@@ -2,24 +2,24 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+zksed -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s -check-prefix=RV64ZKSED
 
-declare i64 @llvm.riscv.sm4ks.i64(i64, i64, i8);
+declare i64 @llvm.riscv.sm4ks.i64(i64, i64, i32);
 
 define i64 @sm4ks_i64(i64 %a, i64 %b) nounwind {
 ; RV64ZKSED-LABEL: sm4ks_i64:
 ; RV64ZKSED:   # %bb.0:
 ; RV64ZKSED-NEXT:sm4ks a0, a0, a1, 0
 ; RV64ZKSED-NEXT:ret
-  %val = call i64 @llvm.riscv.sm4ks.i64(i64 %a, i64 %b, i8 0)
+  %val = call i64 @llvm.riscv.sm4ks.i64(i64 %a, i64 %b, i32 0)
   ret i64 %val
 }
 
-declare i64 @llvm.riscv.sm4ed.i64(i64, i64, i8);
+declare i64 @llvm.riscv.sm4ed.i64(i64, i64, i32);
 
 define i64 @sm4ed_i64(i64 %a, i64 %b) nounwind {
 ; RV64ZKSED-LABEL: sm4ed_i64:
 ; RV64ZKSED:   # %bb.0:
 ; RV64ZKSED-NEXT:sm4ed a0, a0, a1, 1
 ; RV64ZKSED-NEXT:ret
-  %val = call i64 @llvm.riscv.sm4ed.i64(i64 %a, i64 %b, i8 1)
+  %val = call i64 @llvm.riscv.sm4ed.i64(i64 %a, i64 %b, i32 1)
   ret i64 %val
 }
Index: llvm/test/CodeGen/RISCV/rv32zksed-intrinsic.ll
===
--- llvm/test/CodeGen/RISCV/rv32zksed-intrinsic.ll
+++ llvm/test/CodeGen/RISCV/rv32zksed-intrinsic.ll
@@ -2,24 +2,24 @@
 ; RUN: llc -mtriple=riscv32 -mattr=+zksed -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s -check-prefix=RV32ZKSED
 
-declare i32 @llvm.riscv.sm4ks.i32(i32, i32, i8);
+declare i32 @llvm.riscv.sm4ks.i32(i32, i32, i32);
 
 define i32 @sm4ks_i32(i32 %a, i32 %b) nounwind {
 ; RV32ZKSED-LABEL: sm4ks_i32:
 ; RV32ZKSED:   # %bb.0:
 ; RV32ZKSED-NEXT:sm4ks a0, a0, a1, 2
 ; RV32ZKSED-NEXT:ret
-  %val = call i32 @llvm.riscv.sm4ks.i32(i32 %a, i32 %b, i8 2)
+  %val = call i32 @llvm.riscv.sm4ks.i32(i32 %a, i32 %b, i32 2)
   ret i32 %val
 }
 
-declare i32 @llvm.riscv.sm4ed.i32(i32, i32, i8);
+declare i32 @llvm.riscv.sm4ed.i32(i32, i32, i32);
 
 define i32 @sm4ed_i32(i32 %a, i32 %b) nounwind {
 ; RV32ZKSED-LABEL: sm4ed_i32:
 ; RV32ZKSED:   # %bb.0:
 ; RV32ZKSED-NEXT:sm4ed a0, a0, a1, 3
 ; RV32ZKSED-NEXT:ret
-  %val = call i32 @llvm.riscv.sm4ed.i32(i32 %a, i32 %b, i8 3)
+  %val = call i32 @llvm.riscv.sm4ed.i32(i32 %a, i32 %b, i32 3)
   ret i32 %val
 }
Index: llvm/test/CodeGen/RISCV/rv32zkne-intrinsic.ll
===
--- llvm/test/CodeGen/RISCV/rv32zkne-intrinsic.ll
+++ llvm/test/CodeGen/RISCV/rv32zkne-intrinsic.ll
@@ -2,24 +2,24 @@
 ; RUN: llc -mtriple=riscv32 -mattr=+zkne -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s -check-prefix=RV32ZKNE
 
-declare i32 @llvm.riscv.aes32esi(i32, i32, i8);
+declare i32 @llvm.riscv.aes32esi(i32, i32, i32);
 
 define i32 @aes32esi(i32 %a, i32 %b) nounwind {
 ; RV32ZKNE-LABEL: aes32esi:
 ; RV32ZKNE:   # %bb.0:
 ; RV32ZKNE-NEXT:aes32esi a0, a0, a1, 2
 ; RV32ZKNE-NEXT:ret
-%val = call i32 @llvm.riscv.aes32esi(i32 %a, i32 %b, i8 2)
+%val = call i32 @llvm.riscv.aes32esi(i32 %a, i32 %b, i32 2)
  

[PATCH] D152625: run-clang-tidy: forward warnings-as-errors argument

2023-06-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D152625

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


[clang] 0e7cfa5 - [CodeGen] Remove mentions of OLDPM

2023-06-10 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-06-10T10:40:43-07:00
New Revision: 0e7cfa59ebe9d87029ebf75bb4a05316dd3c3d63

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

LOG: [CodeGen] Remove mentions of OLDPM

We stopped testing with -check-prefix=SAMPLEPGO-OLDPM and
-check-prefix=THINLTO-OLDPM as of:

  commit 8a7a28075b7fa70d56b131c10a4d1add777d5830
  Author: Thomas Preud'homme 
  Date:   Fri Sep 17 10:23:40 2021 +0100

Added: 


Modified: 
clang/test/CodeGen/pgo-sample-thinlto-summary.c

Removed: 




diff  --git a/clang/test/CodeGen/pgo-sample-thinlto-summary.c 
b/clang/test/CodeGen/pgo-sample-thinlto-summary.c
index f29180eab3b6c..23233c8f44f5c 100644
--- a/clang/test/CodeGen/pgo-sample-thinlto-summary.c
+++ b/clang/test/CodeGen/pgo-sample-thinlto-summary.c
@@ -14,20 +14,9 @@ void foo(int n) {
 // SAMPLEPGO:   Running pass: PGOIndirectCallPromotion on [module]
 // SAMPLEPGO:   Running pass: LoopUnrollPass on bar
 
-// SAMPLEPGO-OLDPM: PGOIndirectCallPromotion
-// SAMPLEPGO-OLDPM: Unroll loops
-// SAMPLEPGO-OLDPM: Unroll loops
-
 // THINLTO-NOT: Running pass: PGOIndirectCallPromotion on [module]
 // THINLTO-NOT: Running pass: LoopUnrollPass on bar
 
-// THINLTO-OLDPM-NOT:   PGOIndirectCallPromotion
-// The first Unroll loop pass is the createSimpleLoopUnrollPass that unrolls 
and peels
-// loops with small constant trip counts. The second one is skipped by ThinLTO.
-// THINLTO-OLDPM:   Unroll loops
-// THINLTO-OLDPM-NOT:   Unroll loops
-
-
 // Checks if hot call is inlined by normal compile, but not inlined by
 // thinlto compile.
 // SAMPLEPGO-LABEL: define {{(dso_local )?}}void @bar



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


[PATCH] D152625: run-clang-tidy: forward warnings-as-errors argument

2023-06-10 Thread Maxim Kolesnikov via Phabricator via cfe-commits
indev29 created this revision.
indev29 added reviewers: cfe-commits, njames93.
Herald added subscribers: PiotrZSL, carlosgalvezp.
Herald added a project: All.
indev29 requested review of this revision.
Herald added a project: clang-tools-extra.

Forward `warnings-as-errors` argument to clang-tidy.


https://reviews.llvm.org/D152625

Files:
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -105,6 +105,7 @@
 line_filter,
 use_color,
 plugins,
+warnings_as_errors,
 ):
 """Gets a command line for clang-tidy."""
 start = [clang_tidy_binary]
@@ -141,6 +142,8 @@
 start.append("-config=" + config)
 for plugin in plugins:
 start.append("-load=" + plugin)
+if warnings_as_errors:
+start.append("--warnings-as-errors=" + warnings_as_errors)
 start.append(f)
 return start
 
@@ -224,6 +227,7 @@
 args.line_filter,
 args.use_color,
 args.plugins,
+args.warnings_as_errors,
 )
 
 proc = subprocess.Popen(
@@ -363,6 +367,11 @@
 default=[],
 help="Load the specified plugin in clang-tidy.",
 )
+parser.add_argument(
+"-warnings-as-errors",
+default=None,
+help="Upgrades warnings to errors. Same format as " "'-checks'",
+)
 args = parser.parse_args()
 
 db_path = "compile_commands.json"
@@ -399,6 +408,7 @@
 args.line_filter,
 args.use_color,
 args.plugins,
+args.warnings_as_errors,
 )
 invocation.append("-list-checks")
 invocation.append("-")


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -105,6 +105,7 @@
 line_filter,
 use_color,
 plugins,
+warnings_as_errors,
 ):
 """Gets a command line for clang-tidy."""
 start = [clang_tidy_binary]
@@ -141,6 +142,8 @@
 start.append("-config=" + config)
 for plugin in plugins:
 start.append("-load=" + plugin)
+if warnings_as_errors:
+start.append("--warnings-as-errors=" + warnings_as_errors)
 start.append(f)
 return start
 
@@ -224,6 +227,7 @@
 args.line_filter,
 args.use_color,
 args.plugins,
+args.warnings_as_errors,
 )
 
 proc = subprocess.Popen(
@@ -363,6 +367,11 @@
 default=[],
 help="Load the specified plugin in clang-tidy.",
 )
+parser.add_argument(
+"-warnings-as-errors",
+default=None,
+help="Upgrades warnings to errors. Same format as " "'-checks'",
+)
 args = parser.parse_args()
 
 db_path = "compile_commands.json"
@@ -399,6 +408,7 @@
 args.line_filter,
 args.use_color,
 args.plugins,
+args.warnings_as_errors,
 )
 invocation.append("-list-checks")
 invocation.append("-")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bb4d583 - Fix CodeGen HIP test case failing on some targets

2023-06-10 Thread via cfe-commits

Author: Vikram
Date: 2023-06-10T13:28:33-04:00
New Revision: bb4d5833e564f4995db5888950a05c3ff1272ee9

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

LOG: Fix CodeGen HIP test case failing on some targets

Added: 


Modified: 
clang/test/Driver/hip-options.hip

Removed: 




diff  --git a/clang/test/Driver/hip-options.hip 
b/clang/test/Driver/hip-options.hip
index 9ecde6cd3fbaf..1da5ce15ea13c 100644
--- a/clang/test/Driver/hip-options.hip
+++ b/clang/test/Driver/hip-options.hip
@@ -22,7 +22,7 @@
 // PTH: "-cc1"{{.*}} "-fgpu-default-stream=per-thread" {{.*}}"-x" 
"hip-cpp-output"
 
 // Check -mprintf-kind=hostcall
-// RUN: %clang -### -mprintf-kind=hostcall  %s -save-temps 2>&1 | FileCheck 
-check-prefix=HOSTC %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -mprintf-kind=hostcall  
%s -save-temps 2>&1 | FileCheck -check-prefix=HOSTC %s
 // HOSTC: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}}"-mprintf-kind=hostcall" 
"-Werror=format-invalid-specifier" "-E" {{.*}}
 // HOSTC: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}} "-mprintf-kind=hostcall" 
"-Werror=format-invalid-specifier" {{.*}}"-x" "hip-cpp-output"
 // HOSTC: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}} "-mprintf-kind=hostcall" 
"-Werror=format-invalid-specifier" {{.*}}"-x" "ir"
@@ -30,7 +30,7 @@
 // HOSTC: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "ir"
 
 // Check -mprintf-kind=buffered
-// RUN: %clang -### -mprintf-kind=buffered  %s -save-temps 2>&1 | FileCheck 
-check-prefix=BUFF %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -mprintf-kind=buffered  
%s -save-temps 2>&1 | FileCheck -check-prefix=BUFF %s
 // BUFF: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}}"-mprintf-kind=buffered" 
"-Werror=format-invalid-specifier" "-E" {{.*}}
 // BUFF: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}} "-mprintf-kind=buffered" 
"-Werror=format-invalid-specifier" {{.*}}"-x" "hip-cpp-output"
 // BUFF: "-cc1" "-triple" "amdgcn-amd-amdhsa"{{.*}} "-mprintf-kind=buffered" 
"-Werror=format-invalid-specifier" {{.*}}"-x" "ir"



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


[PATCH] D152109: Update clang-repl documentation

2023-06-10 Thread Krishna Narayanan via Phabricator via cfe-commits
Krishna-13-cyber updated this revision to Diff 530227.
Krishna-13-cyber added a comment.

- Update with addressing the comments
- Update with example of Dynamic library usage in repl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152109

Files:
  clang/docs/ClangRepl.rst

Index: clang/docs/ClangRepl.rst
===
--- clang/docs/ClangRepl.rst
+++ clang/docs/ClangRepl.rst
@@ -16,22 +16,6 @@
 of Cling upstream, making them useful and available to a broader audience.
 
 
-
-Clang-Repl Usage
-
-
-
-.. code-block:: text
-
-  clang-repl> #include 
-  clang-repl> int f() { std::cout << "Hello Interpreted World!\n"; return 0; }
-  clang-repl> auto r = f();
-  // Prints Hello Interpreted World!
-
-Note that the implementation is not complete and highly experimental. We do
-not yet support statements on the global scope, for example.
-
-
 Clang-Repl Basic Data Flow
 ==
 
@@ -63,14 +47,170 @@
 
 8. The machine code is then executed.
 
+===
+Build Instructions:
+===
+
+
+.. code-block:: console
+
+
+   $ cd llvm-project
+   $ mkdir build
+   $ cd build
+   $ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" ../llvm
+
+**Note here**, above RelWithDebInfo - Debug / Release
+
+.. code-block:: console
+
+   cmake --build . --target clang clang-repl -j n
+  OR
+   cmake --build . --target clang clang-repl
+
+**Clang-repl** is built under llvm-project/build/bin. Proceed into the directory **llvm-project/build/bin**
+
+.. code-block:: console
+
+   ./clang-repl
+   clang-repl>
+
+
+
+Clang-Repl Usage
+
+
+**Clang-Repl** is an interactive C++ interpreter that allows for incremental
+compilation. It supports interactive programming for C++ in a
+read-evaluate-print-loop (REPL) style. It uses Clang as a library to compile the
+high level programming language into LLVM IR. Then the LLVM IR is executed by
+the LLVM just-in-time (JIT) infrastructure.
+
+
+Basic:
+==
+
+
+.. code-block:: text
+
+  clang-repl> #include 
+  clang-repl> int f() { std::cout << "Hello Interpreted World!\n"; return 0; }
+  clang-repl> auto r = f();
+   // Prints Hello Interpreted World!
+
+.. code-block:: text
+
+   clang-repl> #include
+   clang-repl> using namespace std;
+   clang-repl> std::cout << "Welcome to CLANG-REPL" << std::endl;
+   Welcome to CLANG-REPL
+   // Prints Welcome to CLANG-REPL
+
+
+Function Definitions and Calls:
+===
+
+
+.. code-block:: text
+
+   clang-repl> #include
+   clang-repl> int sum(int a, int b){ return a+b; };
+   clang-repl> int c = sum(9,10);
+   clang-repl> std::cout << c;
+   19clang-repl>
+
+Iterative Structures:
+=
+
+
+.. code-block:: text
+
+   clang-repl> #include
+   clang-repl> for (int i = 0;i < 3;i++){ std::cout << i << std::endl;}
+   0
+   1
+   2
+   clang-repl> while(i < 7){ i++; std::cout << i << std::endl;}
+   4
+   5
+   6
+   7
+
+Classes and Structures:
+===
+
+
+.. code-block:: text
+
+   clang-repl> #include
+   clang-repl> class Rectangle {int width, height; public: void set_values (int,int);\
+   clang-repl... int area() {return width*height;}};
+   clang-repl>  void Rectangle::set_values (int x, int y) { width = x;height = y;}
+   clang-repl> int main () { Rectangle rect;rect.set_values (3,4);\
+   clang-repl... std::cout << "area: " << rect.area();return 0;}
+   clang-repl> main();
+   area: 12clang-repl>
+   // Note: This '\' can be used for continuation of the statements in the next line
+
+Lamdas:
+===
+
+
+.. code-block:: text
+
+   clang-repl> #include
+   clang-repl> using namespace std;
+   clang-repl> auto welcome = []()  { std::cout << "Welcome to REPL" << std::endl;};
+   clang-repl> welcome();
+   Welcome to REPL
+
+Using Dynamic Library:
+==
+
+.. code-block:: text
+
+   clang-repl> %lib print.so
+   clang-repl> #include"print.hpp"
+   clang-repl> print(9);
+   9
+
+**Generation of dynamic library**
+
+.. code-block:: text
+
+
+   // print.cpp
+   #include
+   #include"print.hpp"
+
+   void print(int a)
+   {
+  std::cout << a << std::endl;
+   }
+
+   // print.hpp
+   void print (int a);
+
+   // Commands
+   clang++-17  -c -o print.o print.cpp
+   clang-17 -shared print.o -o print.so
+
+
+Closure or Termination:
+===
+
+
+.. code-block:: text
+
+   clang-repl>%quit
+
 
-Just like Clang, Clang-Repl can be integrated in existing applications as a
-library (via using the clangInterpreter library). This turning your C++ compiler
-into a service which incrementally can consume and execute code. The
-**Compiler as A Service** (**CaaS**) concept helps supporting move advanced use
-cases such as template instantiations on demand and automatic language
-interoperability. It also hel

[PATCH] D151373: [libclang] Expose arguments of clang::annotate{_type}

2023-06-10 Thread Fridtjof Mund via Phabricator via cfe-commits
fridtjof updated this revision to Diff 530219.
fridtjof added a comment.

- Deduplicated code by using templates (looks a bit ridicilous though)
- Release notes entry added
- Unit test added


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

https://reviews.llvm.org/D151373

Files:
  clang/docs/ReleaseNotes.rst
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CursorVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -1172,6 +1172,48 @@
   });
 }
 
+TEST_F(LibclangParseTest, ExposedAnnotateArgs) {
+  // TODO
+  const char testSource[] = R"cpp(
+int [[clang::annotate_type("category_type", 42)]] f;
+
+[[clang::annotate("category", 42)]]
+void func() {}
+)cpp";
+  std::string fileName = "main.cpp";
+  WriteFile(fileName, testSource);
+
+  const char *Args[] = {"-xc++"};
+  ClangTU = clang_parseTranslationUnit(Index, fileName.c_str(), Args, 1,
+   nullptr, 0, TUFlags);
+
+  Traverse([&](CXCursor cursor, CXCursor parent) -> CXChildVisitResult {
+if (cursor.kind != CXCursor_AnnotateAttr)
+  return CXChildVisit_Recurse;
+
+int childCount = 0;
+
+clang_visitChildren(
+cursor,
+[](CXCursor child, CXCursor, CXClientData data) -> CXChildVisitResult {
+  int *pcount = static_cast(data);
+
+  // we only expect one argument here, so bail
+  EXPECT_EQ(*pcount, 0);
+
+  auto *result = clang_Cursor_Evaluate(child);
+  EXPECT_NE(result, nullptr);
+  EXPECT_EQ(clang_EvalResult_getAsInt(result), 42);
+  ++*pcount;
+
+  return CXChildVisit_Recurse;
+},
+&childCount);
+
+return CXChildVisit_Continue;
+  });
+}
+
 class LibclangRewriteTest : public LibclangParseTest {
 public:
   CXRewriter Rew = nullptr;
Index: clang/tools/libclang/CursorVisitor.h
===
--- clang/tools/libclang/CursorVisitor.h
+++ clang/tools/libclang/CursorVisitor.h
@@ -276,7 +276,9 @@
   bool IsInRegionOfInterest(CXCursor C);
   bool RunVisitorWorkList(VisitorWorkList &WL);
   void EnqueueWorkList(VisitorWorkList &WL, const Stmt *S);
+  void EnqueueWorkList(VisitorWorkList &WL, const Attr *A);
   LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S);
+  LLVM_ATTRIBUTE_NOINLINE bool Visit(const Attr *A);
 
 private:
   std::optional handleDeclForVisitation(const Decl *D);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -22,6 +22,7 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -526,6 +527,13 @@
 return false;
   }
 
+  if (clang_isAttribute(Cursor.kind)) {
+if (const Attr *A = getCursorAttr(Cursor))
+  return Visit(A);
+
+return false;
+  }
+
   if (clang_isTranslationUnit(Cursor.kind)) {
 CXTranslationUnit TU = getCursorTU(Cursor);
 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
@@ -2088,7 +2096,8 @@
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor {
+class EnqueueVisitor : public ConstStmtVisitor,
+   public ConstAttrVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList &WL;
   CXCursor Parent;
@@ -2230,6 +2239,10 @@
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
+  // Attributes
+  void VisitAnnotateAttr(const AnnotateAttr *A);
+  void VisitAnnotateTypeAttr(const AnnotateTypeAttr *A);
+
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2241,6 +2254,11 @@
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
+  template ::value ||
+ std::is_same::value,
+ bool> = true>
+  void EnqueueChildren(const AnnAttr *A);
 };
 } // namespace
 
@@ -2730,6 +2748,24 @@
   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   std::reverse(I, E);
 }
+
+template ::value ||
+   std::is_same::value,
+   bool>>
+void EnqueueVisitor::EnqueueChildren(const AnnAttr *A) {
+  unsigned size = WL.size();
+  for (const Expr *Arg : A->args()) {
+VisitStmt(Arg);
+  }
+  if (size == WL.size())
+return;
+  // Now reverse the entries we just added.  This will match the DFS
+  // ordering performed by the worklist.
+  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
+  s

[PATCH] D152623: [clang-format] Indent Verilog struct literal on new line

2023-06-10 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, owenpan, MyDeveloperDay.
sstwcw requested review of this revision.

Before:

  c = //
  '{default: 0};

After:

  c = //
  '{default: 0};

If the line has to be broken, the continuation part should be
indented.  Before this fix, it was not the case if the continuation
part was a struct literal.  The rule that caused the problem was added
in 783bac6b.  It was intended for aligning the field labels in
ProtoBuf.  The type `TT_DictLiteral` was only for colons back then, so
the program didn't have to check whether the token was a colon when it
was already type `TT_DictLiteral`.  Now the type applies to more
things including the braces enclosing a dictionary literal.  In
Verilog, struct literals start with a quote.  The quote is regarded as
an identifier by the program.  So the rule for aligning the fields in
ProtoBuf applied to this situation by mistake.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D152623

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/unittests/Format/FormatTestVerilog.cpp


Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -1172,6 +1172,15 @@
   verifyFormat("c = '{a : 0, b : 0.0, default : 0};", Style);
   verifyFormat("c = ab'{a : 0, b : 0.0};", Style);
   verifyFormat("c = ab'{cd : cd'{1, 1.0}, ef : ef'{2, 2.0}};", Style);
+
+  // It should be indented correctly when the line has to break.
+  verifyFormat("c = //\n"
+   "'{default: 0};");
+  Style = getDefaultStyle();
+  Style.ContinuationIndentWidth = 2;
+  verifyFormat("c = //\n"
+   "  '{default: 0};",
+   Style);
 }
 
 TEST_F(FormatTestVerilog, StructuredProcedure) {
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -1172,8 +1172,12 @@
   }
   if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
 return State.Stack[State.Stack.size() - 2].LastSpace;
+  // Field labels in a nested type should be aligned to the brace. For example
+  // in ProtoBuf:
+  //   optional int32 b = 2 [(foo_options) = {aaa: 123,
+  //  :"baz"}];
   if (Current.is(tok::identifier) && Current.Next &&
-  (Current.Next->is(TT_DictLiteral) ||
+  ((Current.Next->is(tok::colon) && Current.Next->is(TT_DictLiteral)) ||
((Style.Language == FormatStyle::LK_Proto ||
  Style.Language == FormatStyle::LK_TextProto) &&
 Current.Next->isOneOf(tok::less, tok::l_brace {


Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -1172,6 +1172,15 @@
   verifyFormat("c = '{a : 0, b : 0.0, default : 0};", Style);
   verifyFormat("c = ab'{a : 0, b : 0.0};", Style);
   verifyFormat("c = ab'{cd : cd'{1, 1.0}, ef : ef'{2, 2.0}};", Style);
+
+  // It should be indented correctly when the line has to break.
+  verifyFormat("c = //\n"
+   "'{default: 0};");
+  Style = getDefaultStyle();
+  Style.ContinuationIndentWidth = 2;
+  verifyFormat("c = //\n"
+   "  '{default: 0};",
+   Style);
 }
 
 TEST_F(FormatTestVerilog, StructuredProcedure) {
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -1172,8 +1172,12 @@
   }
   if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
 return State.Stack[State.Stack.size() - 2].LastSpace;
+  // Field labels in a nested type should be aligned to the brace. For example
+  // in ProtoBuf:
+  //   optional int32 b = 2 [(foo_options) = {aaa: 123,
+  //  :"baz"}];
   if (Current.is(tok::identifier) && Current.Next &&
-  (Current.Next->is(TT_DictLiteral) ||
+  ((Current.Next->is(tok::colon) && Current.Next->is(TT_DictLiteral)) ||
((Style.Language == FormatStyle::LK_Proto ||
  Style.Language == FormatStyle::LK_TextProto) &&
 Current.Next->isOneOf(tok::less, tok::l_brace {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D150427: [AMDGPU] Non hostcall printf support for HIP

2023-06-10 Thread Vikram Hegde 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 rG631c965483e0: [AMDGPU] Non hostcall printf support for HIP 
(authored by vikramRH).

Changed prior to commit:
  https://reviews.llvm.org/D150427?vs=529865&id=530207#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150427

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/TargetOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGGPUBuiltin.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenHIP/default-attributes.hip
  clang/test/CodeGenHIP/printf-kind-module-flag.hip
  clang/test/CodeGenHIP/printf_nonhostcall.cpp
  clang/test/CodeGenHIP/sanitize-undefined-null.hip
  clang/test/Driver/hip-options.hip
  llvm/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h
  llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp

Index: llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
===
--- llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
+++ llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
@@ -17,6 +17,9 @@
 #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
 #include "llvm/ADT/SparseBitVector.h"
 #include "llvm/Analysis/ValueTracking.h"
+#include "llvm/Support/DataExtractor.h"
+#include "llvm/Support/MD5.h"
+#include "llvm/Support/MathExtras.h"
 
 using namespace llvm;
 
@@ -179,11 +182,7 @@
 
 // Scan the format string to locate all specifiers, and mark the ones that
 // specify a string, i.e, the "%s" specifier with optional '*' characters.
-static void locateCStrings(SparseBitVector<8> &BV, Value *Fmt) {
-  StringRef Str;
-  if (!getConstantStringInfo(Fmt, Str) || Str.empty())
-return;
-
+static void locateCStrings(SparseBitVector<8> &BV, StringRef Str) {
   static const char ConvSpecifiers[] = "diouxXfFeEgGaAcspn";
   size_t SpecPos = 0;
   // Skip the first argument, the format string.
@@ -207,14 +206,319 @@
   }
 }
 
-Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder,
-  ArrayRef Args) {
+// helper struct to package the string related data
+struct StringData {
+  StringRef Str;
+  Value *RealSize = nullptr;
+  Value *AlignedSize = nullptr;
+  bool IsConst = true;
+
+  StringData(StringRef ST, Value *RS, Value *AS, bool IC)
+  : Str(ST), RealSize(RS), AlignedSize(AS), IsConst(IC) {}
+};
+
+// Calculates frame size required for current printf expansion and allocates
+// space on printf buffer. Printf frame includes following contents
+// [ ControlDWord , format string/Hash , Arguments (each aligned to 8 byte) ]
+static Value *callBufferedPrintfStart(
+IRBuilder<> &Builder, ArrayRef Args, Value *Fmt,
+bool isConstFmtStr, SparseBitVector<8> &SpecIsCString,
+SmallVectorImpl &StringContents, Value *&ArgSize) {
+  Module *M = Builder.GetInsertBlock()->getModule();
+  Value *NonConstStrLen = nullptr;
+  Value *LenWithNull = nullptr;
+  Value *LenWithNullAligned = nullptr;
+  Value *TempAdd = nullptr;
+
+  // First 4 bytes to be reserved for control dword
+  size_t BufSize = 4;
+  if (isConstFmtStr)
+// First 8 bytes of MD5 hash
+BufSize += 8;
+  else {
+LenWithNull = getStrlenWithNull(Builder, Fmt);
+
+// Align the computed length to next 8 byte boundary
+TempAdd = Builder.CreateAdd(LenWithNull,
+ConstantInt::get(LenWithNull->getType(), 7U));
+NonConstStrLen = Builder.CreateAnd(
+TempAdd, ConstantInt::get(LenWithNull->getType(), ~7U));
+
+StringContents.push_back(
+StringData(StringRef(), LenWithNull, NonConstStrLen, false));
+  }
+
+  for (size_t i = 1; i < Args.size(); i++) {
+if (SpecIsCString.test(i)) {
+  StringRef ArgStr;
+  if (getConstantStringInfo(Args[i], ArgStr)) {
+auto alignedLen = alignTo(ArgStr.size() + 1, 8);
+StringContents.push_back(StringData(
+ArgStr,
+/*RealSize*/ nullptr, /*AlignedSize*/ nullptr, /*IsConst*/ true));
+BufSize += alignedLen;
+  } else {
+LenWithNull = getStrlenWithNull(Builder, Args[i]);
+
+// Align the computed length to next 8 byte boundary
+TempAdd = Builder.CreateAdd(
+LenWithNull, ConstantInt::get(LenWithNull->getType(), 7U));
+LenWithNullAligned = Builder.CreateAnd(
+TempAdd, ConstantInt::get(LenWithNull->getType(), ~7U));
+
+if (NonConstStrLen) {
+  auto Val = Builder.CreateAdd(LenWithNullAligned, NonConstStrLen,
+   "cumulativeAdd");
+  NonConstStrLen = Val;
+} else
+  NonConstStrLen = LenWithNullAligned;
+
+StringContents.push_back(
+StringData(StringRef(), LenWithNull, LenWithNullAligned, false));
+  }
+} else {
+  int AllocSize = M->getDataLayout().getType

[clang] 631c965 - [AMDGPU] Non hostcall printf support for HIP

2023-06-10 Thread via cfe-commits

Author: Vikram
Date: 2023-06-10T09:55:00-04:00
New Revision: 631c965483e03355cdc1dba578e787b259c4d79d

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

LOG: [AMDGPU] Non hostcall printf support for HIP

This is an alternative to currently existing hostcall implementation and uses 
printf buffer similar to OpenCL,
The data stored in the buffer (i.e the data frame) for each printf call are as 
follows,
1. Control DWord - contains info regarding stream, format string constness and 
size of data frame
2. Hash of the format string (if constant) else the format string itself
3. Printf arguments (each aligned to 8 byte boundary)

The format string Hash is generated using LLVM's MD5 Message-Digest Algorithm 
implementation and only low 64 bits are used.
The implementation still uses amdhsa metadata and hash is stored as part of 
format string itself to ensure
minimal changes in runtime.

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

Added: 
clang/test/CodeGenHIP/printf-kind-module-flag.hip
clang/test/CodeGenHIP/printf_nonhostcall.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/TargetOptions.h
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/CGGPUBuiltin.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/CodeGenHIP/default-attributes.hip
clang/test/CodeGenHIP/sanitize-undefined-null.hip
clang/test/Driver/hip-options.hip
llvm/include/llvm/Transforms/Utils/AMDGPUEmitPrintf.h
llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 58e1039c4f133..dd31bc6bf3fa3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -588,6 +588,12 @@ AMDGPU Support
   --undefined`` if using an offloading language.
 - The deprecated ``-mcode-object-v3`` and ``-mno-code-object-v3`` command-line
   options have been removed.
+- A new option ``-mprintf-kind`` has been introduced that controls printf 
lowering
+  scheme. It is currently supported only for HIP and takes following values,
+  ``hostcall`` - printing happens during kernel execution via series of 
hostcalls,
+  The scheme requires the system to support pcie atomics.(default)
+  ``buffered`` - Scheme uses a debug buffer to populate printf varargs, does 
not
+  rely on pcie atomics support.
 
 X86 Support
 ^^^

diff  --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index 9197282f3b566..b192c856384b9 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -90,6 +90,19 @@ class TargetOptions {
   /// \brief Code object version for AMDGPU.
   CodeObjectVersionKind CodeObjectVersion = CodeObjectVersionKind::COV_None;
 
+  /// \brief Enumeration values for AMDGPU printf lowering scheme
+  enum class AMDGPUPrintfKind {
+/// printf lowering scheme involving hostcalls, currently used by HIP
+/// programs by default
+Hostcall = 0,
+
+/// printf lowering scheme involving implicit printf buffers,
+Buffered = 1,
+  };
+
+  /// \brief AMDGPU Printf lowering scheme
+  AMDGPUPrintfKind AMDGPUPrintfKindVal = AMDGPUPrintfKind::Hostcall;
+
   // The code model to be used as specified by the user. Corresponds to
   // CodeModel::Model enum defined in include/llvm/Support/CodeGen.h, plus
   // "default" for the case when the user has not explicitly specified a

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0af3b7f12fd8f..27a4bc080b8c0 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1037,6 +1037,17 @@ defm cuda_short_ptr : BoolFOption<"cuda-short-ptr",
   TargetOpts<"NVPTXUseShortPointers">, DefaultFalse,
   PosFlag,
   NegFlag>;
+def mprintf_kind_EQ : Joined<["-"], "mprintf-kind=">, Group,
+  HelpText<"Specify the printf lowering scheme (AMDGPU only), allowed values 
are "
+  "\"hostcall\"(printing happens during kernel execution, this scheme "
+  "relies on hostcalls which require system to support pcie atomics) "
+  "and \"buffered\"(printing happens after all kernel threads exit, "
+  "this uses a printf buffer and does not rely on pcie atomic support)">,
+  Flags<[CC1Option]>,
+  Values<"hostcall,buffered">,
+  NormalizedValuesScope<"TargetOptions::AMDGPUPrintfKind">,
+  NormalizedValues<["Hostcall", "Buffered"]>,
+  MarshallingInfoEnum, "Hostcall">;
 def fgpu_default_stream_EQ : Joined<["-"], "fgpu-default-stream=">,
   HelpText<"Specify default stream. The default value is 'legacy'. (HIP 
only)">,
   Flags<[CC1Option]>,

diff  --git a/clang/lib/CodeGen/CGGPUBuiltin.cpp 
b/clang/lib/CodeGen/CGGPUBuiltin.cpp
index 8451ebe

[PATCH] D139010: [clang][WebAssembly] Implement support for table types and builtins

2023-06-10 Thread Paulo Matos 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 rG55aeb23fe008: [clang][WebAssembly] Implement support for 
table types and builtins (authored by pmatos).

Changed prior to commit:
  https://reviews.llvm.org/D139010?vs=526578&id=530204#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139010

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Type.cpp
  clang/lib/Basic/Targets/WebAssembly.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/WebAssembly/builtins-table.c
  clang/test/Sema/builtins-wasm.c
  clang/test/Sema/wasm-refs-and-table-ped.c
  clang/test/Sema/wasm-refs-and-tables.c
  clang/test/Sema/wasm-refs.c
  clang/test/SemaCXX/wasm-refs-and-tables.cpp
  clang/test/SemaCXX/wasm-refs.cpp
  llvm/include/llvm/CodeGen/WasmAddressSpaces.h
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

Index: llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
@@ -62,8 +62,9 @@
   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
 PtrToIntInst *PTI = dyn_cast(&*I);
 IntToPtrInst *ITP = dyn_cast(&*I);
-if (!(PTI && WebAssembly::isRefType(PTI->getPointerOperand()->getType())) &&
-!(ITP && WebAssembly::isRefType(ITP->getDestTy(
+if (!(PTI && WebAssembly::isWebAssemblyReferenceType(
+ PTI->getPointerOperand()->getType())) &&
+!(ITP && WebAssembly::isWebAssemblyReferenceType(ITP->getDestTy(
   continue;
 
 UndefValue *U = UndefValue::get(I->getType());
Index: llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
@@ -1214,8 +1214,8 @@
 
   // Lastly, if this is a call to a funcref we need to add an instruction
   // table.set to the chain and transform the call.
-  if (CLI.CB &&
-  WebAssembly::isFuncrefType(CLI.CB->getCalledOperand()->getType())) {
+  if (CLI.CB && WebAssembly::isWebAssemblyFuncrefType(
+CLI.CB->getCalledOperand()->getType())) {
 // In the absence of function references proposal where a funcref call is
 // lowered to call_ref, using reference types we generate a table.set to set
 // the funcref to a special table used solely for this purpose, followed by
Index: llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
===
--- llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
+++ llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
@@ -18,6 +18,7 @@
 #include "MCTargetDesc/WebAssemblyMCTypeUtilities.h"
 #include "llvm/BinaryFormat/Wasm.h"
 #include "llvm/CodeGen/MachineValueType.h"
+#include "llvm/CodeGen/WasmAddressSpaces.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/MC/MCSymbolWasm.h"
 
@@ -27,41 +28,21 @@
 
 namespace WebAssembly {
 
-enum WasmAddressSpace : unsigned {
-  // Default address space, for pointers to linear memory (stack, heap, data).
-  WASM_ADDRESS_SPACE_DEFAULT = 0,
-  // A non-integral address space for pointers to named objects outside of
-  // linear memory: WebAssembly globals or WebAssembly locals.  Loads and stores
-  // to these pointers are lowered to global.get / global.set or local.get /
-  // local.set, as appropriate.
-  WASM_ADDRESS_SPACE_VAR = 1,
-  // A non-integral address space for externref values
-  WASM_ADDRESS_SPACE_EXTERNREF = 10,
-  // A non-integral address space for funcref values
-  WASM_ADDRESS_SPACE_FUNCREF = 20,
-};
-
-inline bool isDefaultAddressSpace(unsigned AS) {
-  return AS == WASM_ADDRESS_SPACE_DEFAULT;
-}
-inline bool isWasmVarAddressSpace(unsigned AS) {
-  return AS == WASM_ADDRESS_SPACE_VAR;
-}
-inline bool isValidAddressSpace(unsigned AS) {
-  return isDefaultAddressSpace(AS) || isWasmVarAddressSpace(AS);
+/// Return

[clang] 55aeb23 - [clang][WebAssembly] Implement support for table types and builtins

2023-06-10 Thread Paulo Matos via cfe-commits

Author: Paulo Matos
Date: 2023-06-10T15:53:13+02:00
New Revision: 55aeb23fe0084d930ecd7335092d712bd71694c7

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

LOG: [clang][WebAssembly] Implement support for table types and builtins

This commit implements support for WebAssembly table types and
respective builtins. Table tables are WebAssembly objects to store
reference types. They have a large amount of semantic restrictions
including, but not limited to, only being allowed to be declared
at the top-level as static arrays of zero-length. Not being arguments
or result of functions, not being stored ot memory, etc.

This commit introduces the __attribute__((wasm_table)) to attach to
arrays of WebAssembly reference types. And the following builtins to
manage tables:

* ref   __builtin_wasm_table_get(table, idx)
* void  __builtin_wasm_table_set(table, idx, ref)
* uint  __builtin_wasm_table_size(table)
* uint  __builtin_wasm_table_grow(table, ref, uint)
* void  __builtin_wasm_table_fill(table, idx, ref, uint)
* void  __builtin_wasm_table_copy(table, table, uint, uint, uint)

This commit also enables reference-types feature at bleeding-edge.

This is joint work with Alex Bradbury (@asb).

Reviewed By: aaron.ballman

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

Added: 
clang/test/CodeGen/WebAssembly/builtins-table.c
clang/test/Sema/builtins-wasm.c
clang/test/Sema/wasm-refs-and-table-ped.c
clang/test/Sema/wasm-refs-and-tables.c
clang/test/SemaCXX/wasm-refs-and-tables.cpp
llvm/include/llvm/CodeGen/WasmAddressSpaces.h

Modified: 
clang/docs/LanguageExtensions.rst
clang/include/clang/AST/Type.h
clang/include/clang/Basic/BuiltinsWebAssembly.def
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/Type.cpp
clang/lib/Basic/Targets/WebAssembly.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/Sema/SemaCast.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExceptionSpec.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaType.cpp
llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp
llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

Removed: 
clang/test/Sema/wasm-refs.c
clang/test/SemaCXX/wasm-refs.cpp



diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index b36f2f8e3e45f..f37db774a0f7b 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2313,6 +2313,138 @@ targets.
 atomic_add(a, 1);
   }
 
+WebAssembly Features
+
+
+Clang supports the WebAssembly features documented below. For further 
+information related to the semantics of the builtins, please refer to the 
`WebAssembly Specification `_.
+In this section, when we refer to reference types, we are referring to 
+WebAssembly reference types, not C++ reference types unless stated
+otherwise.
+
+``__builtin_wasm_table_set``
+
+
+This builtin function stores a value in a WebAssembly table. 
+It takes three arguments.
+The first argument is the table to store a value into, the second 
+argument is the index to which to store the value into, and the
+third argument is a value of reference type to store in the table.
+It returns nothing.
+
+.. code-block:: c++
+
+  static __externref_t table[0];
+  extern __externref_t JSObj;
+
+  void store(int index) {
+__builtin_wasm_table_set(table, index, JSObj);
+  } 
+
+``__builtin_wasm_table_get``
+
+
+This builtin function is the counterpart to ``__builtin_wasm_table_set``
+and loads a value from a WebAssembly table of reference typed values.
+It takes 2 arguments.
+The first argument is a table of reference typed values and the 
+second argument is an index from which to load the value. It returns
+the loaded reference typed value.
+
+.. code-block:: c++
+
+  static __externref_t table[0];
+  
+  __externref_t load(int index) {
+__externref_t Obj = __builtin_wasm_table_get(table, index);
+return Obj;
+  }
+
+``__builtin_wasm_table_size``
+-
+
+This builtin function returns the size of the WebAssembly table.
+Takes the table as an argument and returns an unsigned integer (``size_t``)
+with the current table size.
+
+.. code-block:: c++
+
+  typedef void (*__funcref funcref_t)();
+  static __fun

[PATCH] D139010: [clang][WebAssembly] Implement support for table types and builtins

2023-06-10 Thread Paulo Matos via Phabricator via cfe-commits
pmatos added a comment.

In D139010#4400303 , @aaron.ballman 
wrote:

> Spotted a typo in the docs, but otherwise LGTM (thanks for your patience 
> while I was out last week).

Thanks for your time one this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139010

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


[PATCH] D151785: [clangd] Desugar dependent type aliases for auto type hints

2023-06-10 Thread Younan Zhang via Phabricator via cfe-commits
zyounan added a comment.

Thank you very much for the insightful review! Regarding to your suggestion,

> We have an existing heuristic here, should we move the logic into 
> maybeDesugar() so it's all in one place?

once we merge these two functions, the overloaded `addTypeHint` without a 
PrintingPolicy parameter will merely remains one line for forwarding. As we're 
going to use a single `PrintingPolicy` after D152520 
, I think it would be better to eventually 
drop the parameter `PrintingPolicy` in `addTypeHint` in that patch.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:198
+bool isDependentOrTrivialSugaredType(QualType QT) {
+  static auto PeelQualifier = [](QualType QT) {
+// Neither `PointerType` nor `ReferenceType` is considered as sugared

nridge wrote:
> nit: it sounds like this name (`PeelQualifier`) is using "qualifier" to mean 
> "pointer or reference", which is different from the meaning of the word in 
> "QualType" (where it means "const or volatile")
> 
> maybe `PeelWrappers` would be a better name, since we can think of 
> `PointerType` and `ReferenceType` as wrapping an underlying type?
Good catch! I looked up the standard and found out that pointers or references 
are of compound types, and that 'qualified' usually goes along with 'const or 
volatile'.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:201
+// type. Peel it.
+QualType Last = QT;
+for (QT = QT->getPointeeType(); !QT.isNull();

nridge wrote:
> a possible reformulation:
> 
> ```
> QualType Next;
> while (!(Next = QT->getPointeeType()).isNull()) {
>   QT = Next;
> }
> return QT;
> ```
> 
> this seems slightly cleaner to me, but I'll leave it up to you
Rephrased as the suggestion. (TBH, I didn't realize storing the Next instead of 
the Prev could make it more terse. Thanks for the hint!)



Comment at: clang-tools-extra/clangd/InlayHints.cpp:207
+  };
+  for (QualType Desugared =
+   PeelQualifier(QT->getLocallyUnqualifiedSingleStepDesugaredType());

nridge wrote:
> this loop can also be reformulated to avoid repeating the update step:
> 
> ```
> while (true) {
>   QualType Desugared = Peel(...);
>   if (Desugared == QT)
> break;
>   if (Desugared->getAs<...>)
> return true;
>   QT = Desugared;
> }
> ```
Cool.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:215
+  return true;
+if (Desugared->getAs())
+  return true;

nridge wrote:
> The only test case that seems to rely on this `BuiltinType` heuristic is 
> getting `int` instead of `size_type` for `array.size()`.
> 
> `size_type` doesn't seem so bad, maybe we can leave this out for now? Or do 
> you have a more compelling motivating case for it?
Not that I could think of except that case. It's possible that `size_type` 
varies across different platforms, so it seems okay to remove it.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:235
+// parameter QT.
+QualType tryDesugar(ASTContext &AST, QualType QT) {
+  if (isDependentOrTrivialSugaredType(QT))

nridge wrote:
> name suggestion: `maybeDesugar`
> 
> (`try` sounds like it might fail and return something that needs to be 
> checked like `optional` or `Expected`)
Frankly speaking I used to mix up these two and just learned the differences. 
Thank you!



Comment at: clang-tools-extra/clangd/InlayHints.cpp:267
 StructuredBindingPolicy = TypeHintPolicy;
 StructuredBindingPolicy.PrintCanonicalTypes = true;
   }

nridge wrote:
> zyounan wrote:
> > nridge wrote:
> > > zyounan wrote:
> > > > `PrintCanonicalTypes` turns on printing default template arguments, 
> > > > which would prevent the patch from printing, e.g., 
> > > > `std::basic_string`, within the default length limitation.
> > > > 
> > > > ```
> > > > std::map Map;
> > > > 
> > > > for (auto &[Key, Value] : Map) // Key: basic_string > > > char_traits, allocator>, whose length exceeds the default 
> > > > threshold.
> > > > 
> > > > ```
> > > > 
> > > > Is it safe to drop it now? I believe this patch can handle the case the 
> > > > comment mentioned.
> > > Unfortunately, I don't think it works in general. I tried commenting out 
> > > this line and 
> > > `TypeHints.StructuredBindings_TupleLike` failed.
> > > 
> > > (Note, this was with the `BuiltinType` heuristic removed. If we keep the 
> > > `BuilinType` heuristic, a modified version of the testcase (e.g. struct 
> > > members are changed from `int` to a class type) still fails.)
> > > 
> > Thank you for providing me with the case. I think the flag 
> > `PrintCanonicalTypes` actually controls two aspects of styles, if I 
> > understand TypePrinter correctly:
> > 
> > 1. For type aliases (a.k.a. typedefs and using alias), the 'canonical' type 
> > (i.e., the "most" desugared type) is [[ 
> > https://searchfox.org/ll

[PATCH] D151785: [clangd] Desugar dependent type aliases for auto type hints

2023-06-10 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 530201.
zyounan marked 7 inline comments as done.
zyounan added a comment.

Address many comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151785

Files:
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1417,6 +1417,82 @@
   ExpectedHint{": int", "h"}, ExpectedHint{": int", "i"});
 }
 
+TEST(TypeHints, SubstTemplateParameterAliases) {
+  assertTypeHints(
+  R"cpp(
+  template  struct allocator {};
+
+  template 
+  struct vector_base {
+using pointer = T*;
+  };
+
+  template 
+  struct internal_iterator_type_template_we_dont_expect {};
+
+  struct my_iterator {};
+
+  template >
+  struct vector : vector_base {
+using base = vector_base;
+typedef T value_type;
+typedef base::pointer pointer;
+using allocator_type = A;
+using size_type = int;
+using iterator = internal_iterator_type_template_we_dont_expect;
+using non_template_iterator = my_iterator;
+
+value_type& operator[](int index) { return elements[index]; }
+const value_type& at(int index) const { return elements[index]; }
+pointer data() { return &elements[0]; }
+allocator_type get_allocator() { return A(); }
+size_type size() const { return 10; }
+iterator begin() { return iterator(); }
+non_template_iterator end() { return non_template_iterator(); }
+
+T elements[10];
+  };
+
+  vector array;
+
+  auto $no_modifier[[by_value]] = array[3];
+  auto* $ptr_modifier[[ptr]] = &array[3];
+  auto& $ref_modifier[[ref]] = array[3];
+  auto& $at[[immutable]] = array.at(3);
+
+  auto $data[[data]] = array.data();
+  auto $allocator[[alloc]] = array.get_allocator();
+  auto $size[[size]] = array.size();
+  auto $begin[[begin]] = array.begin();
+  auto $end[[end]] = array.end();
+
+
+  // If the type alias is not of substituted template parameter type,
+  // do not show desugared type.
+  using VeryLongLongTypeName = my_iterator;
+  using Short = VeryLongLongTypeName;
+
+  auto $short_name[[my_value]] = Short();
+
+  // Same applies with templates.
+  template 
+  using basic_static_vector = vector;
+  template 
+  using static_vector = basic_static_vector>;
+
+  auto $vector_name[[vec]] = static_vector();
+  )cpp",
+  ExpectedHint{": int", "no_modifier"},
+  ExpectedHint{": int *", "ptr_modifier"},
+  ExpectedHint{": int &", "ref_modifier"},
+  ExpectedHint{": const int &", "at"}, ExpectedHint{": int *", "data"},
+  ExpectedHint{": allocator", "allocator"},
+  ExpectedHint{": size_type", "size"}, ExpectedHint{": iterator", "begin"},
+  ExpectedHint{": non_template_iterator", "end"},
+  ExpectedHint{": Short", "short_name"},
+  ExpectedHint{": static_vector", "vector_name"});
+}
+
 TEST(DesignatorHints, Basic) {
   assertDesignatorHints(R"cpp(
 struct S { int x, y, z; };
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -11,10 +11,12 @@
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
 #include "SourceCode.h"
+#include "clang/AST/ASTDiagnostic.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -190,6 +192,64 @@
   return Designators;
 }
 
+// Determines if any intermediate type in desugaring QualType QT is of
+// substituted template parameter. Ignore pointer or reference wrappers.
+bool isSugaredTemplateParameter(QualType QT) {
+  static auto PeelWrappers = [](QualType QT) {
+// Neither `PointerType` nor `ReferenceType` is considered as sugared
+// type. Peel it.
+QualType Next;
+while (!(Next = QT->getPointeeType()).isNull())
+  QT = Next;
+return QT;
+  };
+  while (true) {
+QualType Desugared =
+PeelWrappers(QT->getLocallyUnqualifiedSingleStepDesugaredType());
+if (Desugared == QT)
+  break;
+if (Desugared->getAs())
+  return true;
+QT = Desugared;
+  }
+  return false;
+}
+
+// A simple wrapper for `clang::desugarForDiagnostic` that provides optional
+// semantic.
+std::optional desugar(ASTContext &AST, QualType QT) {
+  bool ShouldAKA;
+  auto Desugared = clang::desugarForDiagnostic(AST, QT, ShouldAKA);
+  if (!ShouldAKA)
+return std::nullopt;
+  return Desugared;
+}
+
+// Apply a series of heuristic methods to determine whether or not a QualType QT
+// is sui

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

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

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151594

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
@@ -26,6 +26,10 @@
 
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void onEndOfTranslationUnit() override;
+  std::optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
   struct ContextInfo {
 const DeclContext *PrimaryContext;
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
@@ -11,6 +11,7 @@
 
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ConvertUTF.h"
 
 namespace {
@@ -45,14 +46,13 @@
 // We're skipping 1. and 3. for the sake of simplicity, but this can lead to
 // false positive.
 
-static std::string skeleton(StringRef Name) {
+static llvm::SmallString<64U> skeleton(StringRef Name) {
   using namespace llvm;
-  std::string SName = Name.str();
-  std::string Skeleton;
-  Skeleton.reserve(1 + Name.size());
+  SmallString<64U> Skeleton;
+  Skeleton.reserve(1U + Name.size());
 
-  const char *Curr = SName.c_str();
-  const char *End = Curr + SName.size();
+  const char *Curr = Name.data();
+  const char *End = Curr + Name.size();
   while (Curr < End) {
 
 const char *Prev = Curr;
@@ -99,8 +99,6 @@
 
 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);
 }
 
@@ -117,16 +115,23 @@
   const ConfusableIdentifierCheck::ContextInfo *DC0,
   const NamedDecl *ND1,
   const ConfusableIdentifierCheck::ContextInfo *DC1) {
-  if (!DC0->Bases.empty() && ND1->getAccess() != AS_private &&
-  isMemberOf(DC1, DC0))
-return true;
-  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));
+  if (!DC0->Bases.empty() && !DC1->Bases.empty()) {
+// if any of the declaration is a non-private member of the other
+// declaration, it's shadowed by the former
+
+if (ND1->getAccess() != AS_private && isMemberOf(DC1, DC0))
+  return true;
+
+if (ND0->getAccess() != AS_private && isMemberOf(DC0, DC1))
+  return true;
+  }
+
+  if (!mayShadowImpl(DC0->NonTransparentContext, DC1->NonTransparentContext) &&
+  !mayShadowImpl(ND0, ND1))
+return false;
+
+  return enclosesContext(DC0, DC1);
 }
 
 const ConfusableIdentifierCheck::ContextInfo *
@@ -172,26 +177,41 @@
 
 void ConfusableIdentifierCheck::check(
 const ast_matchers::MatchFinder::MatchResult &Result) {
-  if (const auto *ND = Result.Nodes.getNodeAs("nameddecl")) {
-if (IdentifierInfo *NDII = ND->getIdentifier()) {
-  const ContextInfo *Info = getContextInfo(ND->getDeclContext());
-  StringRef NDName = NDII->getName();
-  llvm::SmallVector &Mapped = Mapper[skeleton(NDName)];
-  for (const Entry &E : Mapped) {
-const IdentifierInfo *ONDII = E.Declaration->getIdentifier();
-if (mayShadow(ND, Info, E.Declaration, E.Info)) {
-  StringRef ONDName = ONDII->getName();
-  if (ONDName != NDName) {
-diag(ND->getLocation(), "%0 is confusable with %1")
-<< ND << E.Declaration;
-diag(E.Declaration->getLocation(), "other declaration found here",
- DiagnosticIDs::Note);
-  }
-}
-  }
-  Mapped.push_back({ND, Info});
-}
+  const auto *ND = Result.Nodes.getNodeAs("nameddecl");
+  if (!ND)
+return;
+
+  IdentifierInfo *NDII = ND->getIdentifier();
+  if (!NDII)
+return;
+
+  StringRef NDName = NDII->getName();
+  if (NDName.empty())
+return;
+
+  const ContextInfo *Info = getContextInfo(ND->getDeclContext());
+

[clang-tools-extra] 8fdedcd - [clang-tidy] Optimize misc-confusable-identifiers

2023-06-10 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-06-10T11:06:49Z
New Revision: 8fdedcd1a242f6b54eec969e72e35ac0a68b7ea1

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

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

This is final optimization for this check. Main
improvements comes from changing a logic order
in mayShadow function, to first validate result
of mayShadowImpl, then search primary context in
a vectors. Secondary improvement comes from excluding
all implicit code by using TK_IgnoreUnlessSpelledInSource.
All other changes are just cosmetic improvements.

Tested on Cataclysm-DDA open source project, result in
check execution time reduction from 3682 seconds to
100 seconds (~0.25s per TU). That's 97.2% reduction for
this change alone. Resulting in cumulative improvement for
this check around -99.6%, finally bringing this check
into a cheap category.

Reviewed By: serge-sans-paille

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

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 63ba663aaca9a..c2f72c8fc20a0 100644
--- a/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
@@ -11,6 +11,7 @@
 
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ConvertUTF.h"
 
 namespace {
@@ -45,14 +46,13 @@ ConfusableIdentifierCheck::~ConfusableIdentifierCheck() = 
default;
 // We're skipping 1. and 3. for the sake of simplicity, but this can lead to
 // false positive.
 
-static std::string skeleton(StringRef Name) {
+static llvm::SmallString<64U> skeleton(StringRef Name) {
   using namespace llvm;
-  std::string SName = Name.str();
-  std::string Skeleton;
-  Skeleton.reserve(1 + Name.size());
+  SmallString<64U> Skeleton;
+  Skeleton.reserve(1U + Name.size());
 
-  const char *Curr = SName.c_str();
-  const char *End = Curr + SName.size();
+  const char *Curr = Name.data();
+  const char *End = Curr + Name.size();
   while (Curr < End) {
 
 const char *Prev = Curr;
@@ -99,8 +99,6 @@ static bool mayShadowImpl(const NamedDecl *ND0, const 
NamedDecl *ND1) {
 
 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);
 }
 
@@ -117,16 +115,23 @@ 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;
-  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));
+  if (!DC0->Bases.empty() && !DC1->Bases.empty()) {
+// if any of the declaration is a non-private member of the other
+// declaration, it's shadowed by the former
+
+if (ND1->getAccess() != AS_private && isMemberOf(DC1, DC0))
+  return true;
+
+if (ND0->getAccess() != AS_private && isMemberOf(DC0, DC1))
+  return true;
+  }
+
+  if (!mayShadowImpl(DC0->NonTransparentContext, DC1->NonTransparentContext) &&
+  !mayShadowImpl(ND0, ND1))
+return false;
+
+  return enclosesContext(DC0, DC1);
 }
 
 const ConfusableIdentifierCheck::ContextInfo *
@@ -172,26 +177,41 @@ ConfusableIdentifierCheck::getContextInfo(const 
DeclContext *DC) {
 
 void ConfusableIdentifierCheck::check(
 const ast_matchers::MatchFinder::MatchResult &Result) {
-  if (const auto *ND = Result.Nodes.getNodeAs("nameddecl")) {
-if (IdentifierInfo *NDII = ND->getIdentifier()) {
-  const ContextInfo *Info = getContextInfo(ND->getDeclContext());
-  StringRef NDName = NDII->getName();
-  llvm::SmallVector &Mapped = Mapper[skeleton(NDName)];
-  for (const Entry &E : Mapped) {
-const IdentifierInfo *ONDII = E.Declaration->getIdentifier();
-if (mayShadow(ND, Info, E.Declaration, E.Info)) {
-  StringRef ONDName = ONDII->getName();
-  if (ONDName != NDName) {
-diag(ND->getLocation(), "%0 is confusable with %1")
-

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

2023-06-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 530185.
PiotrZSL added a comment.

Add comment to code


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151594

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
@@ -26,6 +26,10 @@
 
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void onEndOfTranslationUnit() override;
+  std::optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
   struct ContextInfo {
 const DeclContext *PrimaryContext;
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
@@ -11,6 +11,7 @@
 
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ConvertUTF.h"
 
 namespace {
@@ -45,14 +46,13 @@
 // We're skipping 1. and 3. for the sake of simplicity, but this can lead to
 // false positive.
 
-static std::string skeleton(StringRef Name) {
+static llvm::SmallString<64U> skeleton(StringRef Name) {
   using namespace llvm;
-  std::string SName = Name.str();
-  std::string Skeleton;
-  Skeleton.reserve(1 + Name.size());
+  SmallString<64U> Skeleton;
+  Skeleton.reserve(1U + Name.size());
 
-  const char *Curr = SName.c_str();
-  const char *End = Curr + SName.size();
+  const char *Curr = Name.data();
+  const char *End = Curr + Name.size();
   while (Curr < End) {
 
 const char *Prev = Curr;
@@ -99,8 +99,6 @@
 
 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);
 }
 
@@ -117,16 +115,23 @@
   const ConfusableIdentifierCheck::ContextInfo *DC0,
   const NamedDecl *ND1,
   const ConfusableIdentifierCheck::ContextInfo *DC1) {
-  if (!DC0->Bases.empty() && ND1->getAccess() != AS_private &&
-  isMemberOf(DC1, DC0))
-return true;
-  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));
+  if (!DC0->Bases.empty() && !DC1->Bases.empty()) {
+// if any of the declaration is a non-private member of the other
+// declaration, it's shadowed by the former
+
+if (ND1->getAccess() != AS_private && isMemberOf(DC1, DC0))
+  return true;
+
+if (ND0->getAccess() != AS_private && isMemberOf(DC0, DC1))
+  return true;
+  }
+
+  if (!mayShadowImpl(DC0->NonTransparentContext, DC1->NonTransparentContext) &&
+  !mayShadowImpl(ND0, ND1))
+return false;
+
+  return enclosesContext(DC0, DC1);
 }
 
 const ConfusableIdentifierCheck::ContextInfo *
@@ -172,26 +177,41 @@
 
 void ConfusableIdentifierCheck::check(
 const ast_matchers::MatchFinder::MatchResult &Result) {
-  if (const auto *ND = Result.Nodes.getNodeAs("nameddecl")) {
-if (IdentifierInfo *NDII = ND->getIdentifier()) {
-  const ContextInfo *Info = getContextInfo(ND->getDeclContext());
-  StringRef NDName = NDII->getName();
-  llvm::SmallVector &Mapped = Mapper[skeleton(NDName)];
-  for (const Entry &E : Mapped) {
-const IdentifierInfo *ONDII = E.Declaration->getIdentifier();
-if (mayShadow(ND, Info, E.Declaration, E.Info)) {
-  StringRef ONDName = ONDII->getName();
-  if (ONDName != NDName) {
-diag(ND->getLocation(), "%0 is confusable with %1")
-<< ND << E.Declaration;
-diag(E.Declaration->getLocation(), "other declaration found here",
- DiagnosticIDs::Note);
-  }
-}
-  }
-  Mapped.push_back({ND, Info});
-}
+  const auto *ND = Result.Nodes.getNodeAs("nameddecl");
+  if (!ND)
+return;
+
+  IdentifierInfo *NDII = ND->getIdentifier();
+  if (!NDII)
+return;
+
+  StringRef NDName = NDII->getName();
+  if (NDName.empty())
+return;
+
+  const ContextInfo *Info = getContextInfo(ND->getDeclContext());
+
+  llvm::SmallVector &Mapped = Mapper[skeleton(NDName)];
+  for (const Entry &E : Mappe

[PATCH] D151761: clang-format: Add AlignConsecutiveShortCaseStatements

2023-06-10 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D151761#4410158 , @galenelias 
wrote:

> Yah, I think leaving it open would be my preference at this point.  Not sure 
> how to properly document that though?  Just be explicit in the tests?  
> Mention it in `alignConsecutiveShortCaseStatements`?  Should it be documented 
> in the generated documentation (that feels a bit heavy)?

It will be a known issue, and thus it should be documented explicitly in my 
opinion. Otherwise there will be bug reports. So I would do:

- Mention it in the options documentation.
- Add a FIXME comment where the fix most likely would be applied.
- Comment on test cases that they have to be changed once this is fixed - or 
add tests which are within an `#if 0`, don't know what @MyDeveloperDay or 
@owenpan like better.


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

https://reviews.llvm.org/D151761

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


[PATCH] D70401: [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs

2023-06-10 Thread Wang Pengcheng via Phabricator via cfe-commits
pcwang-thead added a comment.

In D70401#4409782 , @david-sawatzke 
wrote:

> Hey I've tried using this patch (roughly following 
> https://noxim.xyz/blog/rust-ch32v003/).
>
> It uses the older version of this patch for the rust llvm version (here the 
> llvm tree https://github.com/Noxime/llvm-project/tree/rv32e) and I use rust 
> commit 0939ec13 (together with the small patch for the RVE).
>
> I've experience some issues that results in corruption of $sp, the following 
> is the smallest reproduction (hopefully small enough):
> Code:
>
>   rust
>   #![no_std]
>   
>   pub fn test()  {
>   }
>
> which, with the following .ll for release builds:
>
>   source_filename = "miscomp_repro.8b6a426d3b54bd13-cgu.0"
>   target datalayout = "e-m:e-p:32:32-i64:64-n32-S128"
>   target triple = "riscv32"
>   
>   define dso_local void @_ZN13miscomp_repro4test17h065760f827b95d43E() 
> unnamed_addr #0 {
>   start:
> ret void
>   }
>   
>   attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone 
> willreturn "target-cpu"="generic-rv32" "target-features"="+e,+c" }
>
> results in this assembly:
>
>   .text
>   .attribute  4, 4
>   .attribute  5, "rv32e1p9_c2p0"
>   .file   "miscomp_repro.8b6a426d3b54bd13-cgu.0"
>   .section
> .text._ZN13miscomp_repro4test17h065760f827b95d43E,"ax",@progbits
>   .globl  _ZN13miscomp_repro4test17h065760f827b95d43E
>   .p2align1
>   .type   _ZN13miscomp_repro4test17h065760f827b95d43E,@function
>   _ZN13miscomp_repro4test17h065760f827b95d43E:
>   mv  sp, s0
>   ret
>   .Lfunc_end0:
>   .size   _ZN13miscomp_repro4test17h065760f827b95d43E, 
> .Lfunc_end0-_ZN13miscomp_repro4test17h065760f827b95d43E
>   
>   .section".note.GNU-stack","",@progbits
>
> Since s0 isn't required to have any specific contents (and in the larger 
> project this was extracted from doesn't), this corrupts the stack pointer. 
> Large functions using the stack first save sp to  0, so not all functions 
> have this issue. This also happens (but more verbose) in debug builds, but 
> works fine with the exact same toolchain using the riscv32i target.
>
> Here is the repro with some further output, I hope this patch and not 
> something else is to blame (if so, sorry in advance).
>
> F27877626: miscomp_repro.zip 

Thanks for reporting this.
I tried to compile your .ll on my local machine with newest patch, I didn't see 
the problem. I don't know if it is the bug in older version of this patch, so I 
suggest you to update the patch and try again. :-)
By the way, you can provide the log when you compile the .ll with `-mllvm 
-print-after-all` option (and `-mllvm -debug` if your llvm is a debug build). 
It can be helpful for me to figure out which part is wrong.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70401

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


[PATCH] D152246: [clang][ThreadSafety] Analyze known function pointer values

2023-06-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 530177.
tbaeder marked an inline comment as done.

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

https://reviews.llvm.org/D152246

Files:
  clang/lib/Analysis/ThreadSafety.cpp


Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2063,10 +2063,22 @@
 examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
   }
 
-  auto *D = dyn_cast_or_null(Exp->getCalleeDecl());
-  if(!D || !D->hasAttrs())
+  const auto *ND = dyn_cast_if_present(Exp->getCalleeDecl());
+  if (!ND)
 return;
-  handleCall(Exp, D);
+
+  // For function pointers, try to get the currently known
+  // value of the pointer.
+  if (const auto *VD = dyn_cast(ND)) {
+if (const Expr *E = Analyzer->LocalVarMap.lookupExpr(ND, LVarCtx)) {
+  if (const auto *DRE = dyn_cast(E->IgnoreParenImpCasts()))
+ND = DRE->getDecl();
+}
+  }
+
+  if (!ND->hasAttrs())
+return;
+  handleCall(Exp, ND);
 }
 
 void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {


Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2063,10 +2063,22 @@
 examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
   }
 
-  auto *D = dyn_cast_or_null(Exp->getCalleeDecl());
-  if(!D || !D->hasAttrs())
+  const auto *ND = dyn_cast_if_present(Exp->getCalleeDecl());
+  if (!ND)
 return;
-  handleCall(Exp, D);
+
+  // For function pointers, try to get the currently known
+  // value of the pointer.
+  if (const auto *VD = dyn_cast(ND)) {
+if (const Expr *E = Analyzer->LocalVarMap.lookupExpr(ND, LVarCtx)) {
+  if (const auto *DRE = dyn_cast(E->IgnoreParenImpCasts()))
+ND = DRE->getDecl();
+}
+  }
+
+  if (!ND->hasAttrs())
+return;
+  handleCall(Exp, ND);
 }
 
 void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152589: [clang-tidy] Add readability test for not allowing relative includes

2023-06-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

Even with that for me for example, I would consider `#include "xyz"` be fine, 
but `#include "../xyz"` would be a red flag, so please consider adding 
`StrictMode` option to check so if `StrictMode` is not set then includes from 
same directory, or subdirectory would be allowed, but includes that contain 
`..` would not.
With that settings, I could use that check, and probably many other users could.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152589

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


[PATCH] D152589: [clang-tidy] Add readability test for not allowing relative includes

2023-06-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

One more comment, according to this whitepaper you should actually check if 
include is relative, simply if `current file directory + include` exists and 
it's actually a file that is included, then its relative include.
Currently you checking only `""` and its not a thing that should be done, 
because include like this `#include "hello/utility.hpp" is also valid.
Therefor you should be checking included path, not an include style, and this 
is main problem of this check.
In such case proper name for it would be misc-no-relative-includes, and entire 
implementation of the check should be updated.
Also note that some projects put header files in same folder as source file, 
and uses "" include for them, this is one of the ways to deal with 
private/public includes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152589

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


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

2023-06-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/Analysis/CFG.cpp:1945
+  auto DRE =
+  DeclRefExpr::Create(*Context, {}, {}, VD, false, SourceLocation(),
+  VD->getType(), VK_PRValue);

NoQ wrote:
> Is there a way to attach some valid source locations here, like the source 
> location of the attribute's identifier argument?
> 
> I'm worried that the static analyzer may be unable to consume the CFG without 
> them, it typically requires source locations for almost arbitrary statements. 
> I'm still not sure how it'll react to synthetic statements, maybe turning 
> them into a custom `CFGElement` subclass (like destructors) would be safer as 
> it'll let all clients of the CFG to treat these in a custom manner. Otherwise 
> it makes it look like a completely normal call-expression to the clients, 
> which is not necessarily a good thing.
Look like I can't query the attribute for any locations except its entire 
range; I can also just pass `VD->getLocation()` to all locations here.

I thought doing this without creating fake AST nodes is better as well but I 
wasn't sure how to do that properly, or if I have to update all consumers of 
the CFG.



Comment at: clang/lib/Analysis/CFG.cpp:1951-1952
+
+  SmallVector Args;
+  Args.push_back(DRE);
+  auto A = CallExpr::Create(*Context, F, Args, FD->getType(), VK_PRValue,

NoQ wrote:
> Shouldn't there be a unary operator `&` here somewhere? In your example the 
> variable is `int` but the function accepts `int *`.
Hm, I think you are right, but it doesn't make difference for the CFG (at least 
not for thread anysis), does it? Is there a way for me to test that I pass the 
right parameter value?


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

https://reviews.llvm.org/D152504

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


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

2023-06-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 530175.

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

https://reviews.llvm.org/D152504

Files:
  clang/lib/Analysis/CFG.cpp
  clang/test/Sema/warn-thread-safety-analysis.c

Index: clang/test/Sema/warn-thread-safety-analysis.c
===
--- clang/test/Sema/warn-thread-safety-analysis.c
+++ clang/test/Sema/warn-thread-safety-analysis.c
@@ -22,6 +22,7 @@
 #define SHARED_LOCKS_REQUIRED(...) \
   __attribute__ ((shared_locks_required(__VA_ARGS__)))
 #define NO_THREAD_SAFETY_ANALYSIS  __attribute__ ((no_thread_safety_analysis))
+#define CLEANUP(A) __attribute__ ((cleanup(A)))
 
 // Define the mutex struct.
 // Simplified only for test purpose.
@@ -72,6 +73,11 @@
   return *p;
 }
 
+void cleanup_int(int *unused) __attribute__((release_capability(mu1))) {
+  (void)unused;
+  mutex_exclusive_unlock(&mu1);
+}
+
 int main(void) {
 
   Foo_fun1(1); // expected-warning{{calling function 'Foo_fun1' requires holding mutex 'mu2'}} \
@@ -127,6 +133,15 @@
 // expected-note@-1{{mutex released here}}
   mutex_shared_unlock(&mu1);// expected-warning {{releasing mutex 'mu1' that was not held}}
 
+
+  {
+mutex_exclusive_lock(&mu1);
+int CLEANUP(cleanup_int) i;
+
+Bar_fun1(3);
+  }
+  Bar_fun1(4); // expected-warning {{calling function 'Bar_fun1' requires holding mutex 'mu1' exclusively}}
+
   return 0;
 }
 
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -1907,7 +1907,8 @@
 Decls.push_back(*I);
 
   for (VarDecl *VD : llvm::reverse(Decls)) {
-if (hasTrivialDestructor(VD)) {
+bool HasCleanupAttr = VD->hasAttr();
+if (hasTrivialDestructor(VD) && !HasCleanupAttr) {
   // If AddScopes is enabled and *I is a first variable in a scope, add a
   // ScopeEnd marker in a Block.
   if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) {
@@ -1925,7 +1926,8 @@
 }
 Ty = Context->getBaseElementType(Ty);
 
-if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
+bool IsCXXRecordType = Ty->getAsCXXRecordDecl() != nullptr;
+if (IsCXXRecordType && Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
   Block = createNoReturnBlock();
 else
   autoCreateBlock();
@@ -1933,7 +1935,27 @@
 // Add ScopeEnd just after automatic obj destructor.
 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD))
   appendScopeEnd(Block, VD, S);
-appendAutomaticObjDtor(Block, VD, S);
+
+if (HasCleanupAttr) {
+  // Create a fake CallExpr for the cleanup function.
+  const CleanupAttr *CA = VD->getAttr();
+  FunctionDecl *FD = CA->getFunctionDecl();
+  SourceLocation Loc = VD->getLocation();
+  assert(FD);
+  auto *InstanceRef = DeclRefExpr::Create(*Context, {}, {}, VD, false, Loc,
+  VD->getType(), VK_PRValue);
+
+  auto *FuncRef = DeclRefExpr::Create(*Context, {}, {}, FD, false, Loc,
+  FD->getType(), VK_LValue);
+
+  SmallVector Args{InstanceRef};
+  auto *CE = CallExpr::Create(*Context, FuncRef, Args, FD->getType(),
+  VK_PRValue, Loc, FPOptionsOverride());
+  appendCall(Block, CE);
+}
+
+if (IsCXXRecordType)
+  appendAutomaticObjDtor(Block, VD, S);
   }
 }
 
@@ -2090,7 +2112,8 @@
 return Scope;
 
   if (BuildOpts.AddImplicitDtors) {
-if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
+if (!hasTrivialDestructor(VD) || VD->hasAttr() ||
+BuildOpts.AddScopes) {
   // Add the variable to scope
   Scope = createOrReuseLocalScope(Scope);
   Scope->addVar(VD);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152589: [clang-tidy] Add readability test for not allowing relative includes

2023-06-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL requested changes to this revision.
PiotrZSL added a comment.
This revision now requires changes to proceed.

First this looks like "misc" check, not as "readability" one. So please move it 
to proper module. There is no "readability" aspect of it.
Second thing this is not an "absolute", absolute would be #include 
"/usr/includes/stdio", with this style you can still use relative paths like 
#include <../something>
Proper names then would be one of: misc-no-quote-includes or 
misc-use-angle-bracket-includes (this one looks to sound better), choose one, 
any.

and again naming, those are not relative and absolute, those are quote and 
angle-bracket, avoid confusion with path put into include.




Comment at: 
clang-tools-extra/clang-tidy/readability/AbsoluteIncludesOnlyCheck.cpp:43
+
+void AbsoluteIncludesOnlyPPCallbacks::InclusionDirective(
+SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,

inline this method in AbsoluteIncludesOnlyPPCallbacks  no need to keep it out 
of class.



Comment at: 
clang-tools-extra/clang-tidy/readability/AbsoluteIncludesOnlyCheck.cpp:48
+SrcMgr::CharacteristicKind FileType) {
+  if (IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import)
+return;

i think that `Imported!=nullptr` should also do a trick, but this way shoud be 
fine. Check if getIdentifierInfo is not null to be sure



Comment at: 
clang-tools-extra/clang-tidy/readability/AbsoluteIncludesOnlyCheck.cpp:51
+
+  SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(0);
+  if (!IsAngled) {

`getLocWithOffset(0)` does nothing, remove



Comment at: 
clang-tools-extra/clang-tidy/readability/AbsoluteIncludesOnlyCheck.cpp:53-54
+  if (!IsAngled) {
+Check.diag(DiagLoc, "relative include found, use only absolute includes",
+   DiagnosticIDs::Warning);
+  }

1. You could provide auto-fix here, but if you do not want to do that its fine.
2. Warning is a default, no need to specify it.
3. put included header name into message, it will make way easier for reader to 
find out whats going on
4. consider excluding includes included from system headers on this level, 
otherwise check may generate lot of includes that going to be filter out later 
in process, but that still may be costly.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:188
+Finds relative includes in your code and warn about them. for example
+don't use "readability/absolute-includes-only", use 

+

sounds like "do not eat cheese, eat cheese", align later this documentation 
with check name



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/absolute-includes-only.rst:11
+This is relevant for the canonical project structure specified in paper 
p1204r0.
+The relevant part is the src-dir where relative includes are discussed: 
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1204r0.html#src-dir
+

format this url properly, look into other checks how they do it in documentation



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/absolute-includes-only.rst:11
+This is relevant for the canonical project structure specified in paper 
p1204r0.
+The relevant part is the src-dir where relative includes are discussed: 
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1204r0.html#src-dir
+

PiotrZSL wrote:
> format this url properly, look into other checks how they do it in 
> documentation
80 characters limit



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/absolute-includes-only.rst:17
+
+  // #include "utility.hpp"   // Wrong.
+  // #include// Wrong.

uncomment those includes



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/absolute-includes-only.rst:18
+  // #include "utility.hpp"   // Wrong.
+  // #include// Wrong.
+  // #include "../hello/utility.hpp"  // Wrong.

whats wrong here ? check wont raise warning here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152589

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


[clang] 8e580b7 - [NFC][SetVector] Update some usages of SetVector to SmallSetVector

2023-06-10 Thread Dhruv Chawla via cfe-commits

Author: Dhruv Chawla
Date: 2023-06-10T12:36:43+05:30
New Revision: 8e580b7edd15e3a7fcf5951be14fb3fed519349a

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

LOG: [NFC][SetVector] Update some usages of SetVector to SmallSetVector

This patch is a continuation of D152497. It updates usages of SetVector
that were found in llvm/ and clang/ which were originally specifying either
SmallPtrSet or SmallVector to just using SmallSetVector, as the overhead
of SetVector is reduced with D152497.

This also helps clean up the code a fair bit, and gives a decent speed
boost at -O0 (~0.2%):
https://llvm-compile-time-tracker.com/compare.php?from=9ffdabecabcddde298ff313f5353f9e06590af62&to=97f1c0cde42ba85eaa67cbe89bec8fe45b801f21&stat=instructions%3Au

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaStmt.cpp
llvm/include/llvm/ADT/GenericCycleInfo.h
llvm/include/llvm/CodeGen/LiveRangeEdit.h
llvm/include/llvm/Transforms/Scalar/SROA.h
llvm/lib/Analysis/InlineCost.cpp
llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index b335a04dc473a..18da1ffb9402e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -792,8 +792,7 @@ class Sema final {
   /// we won't know until all lvalue-to-rvalue and discarded value conversions
   /// have been applied to all subexpressions of the enclosing full expression.
   /// This is cleared at the end of each full expression.
-  using MaybeODRUseExprSet = llvm::SetVector,
- llvm::SmallPtrSet>;
+  using MaybeODRUseExprSet = llvm::SmallSetVector;
   MaybeODRUseExprSet MaybeODRUseExprs;
 
   std::unique_ptr CachedFunctionScope;

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 18f09e5a42e9b..14361d85cf182 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -8024,8 +8024,7 @@ namespace {
 /// enumeration types.
 class BuiltinCandidateTypeSet  {
   /// TypeSet - A set of types.
-  typedef llvm::SetVector,
-  llvm::SmallPtrSet> TypeSet;
+  typedef llvm::SmallSetVector TypeSet;
 
   /// PointerTypes - The set of pointer types that will be used in the
   /// built-in candidates.

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index bc9490ad04bf8..a87b0d9501930 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -1729,9 +1729,7 @@ Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
 
 namespace {
   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
-  using DeclSetVector =
-  llvm::SetVector,
-  llvm::SmallPtrSet>;
+  using DeclSetVector = llvm::SmallSetVector;
 
   // This visitor will traverse a conditional statement and store all
   // the evaluated decls into a vector.  Simple is set to true if none

diff  --git a/llvm/include/llvm/ADT/GenericCycleInfo.h 
b/llvm/include/llvm/ADT/GenericCycleInfo.h
index 5dec7c97a0688..7df50f4a0ec17 100644
--- a/llvm/include/llvm/ADT/GenericCycleInfo.h
+++ b/llvm/include/llvm/ADT/GenericCycleInfo.h
@@ -28,10 +28,10 @@
 #ifndef LLVM_ADT_GENERICCYCLEINFO_H
 #define LLVM_ADT_GENERICCYCLEINFO_H
 
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/GenericSSAContext.h"
 #include "llvm/ADT/GraphTraits.h"
 #include "llvm/ADT/SetVector.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -64,7 +64,7 @@ template  class GenericCycle {
   /// Basic blocks that are contained in the cycle, including entry blocks,
   /// and including blocks that are part of a child cycle.
   using BlockSetVectorT = SetVector,
-SmallPtrSet>;
+DenseSet, 8>;
   BlockSetVectorT Blocks;
 
   /// Depth of the cycle in the tree. The root "cycle" is at depth 0.

diff  --git a/llvm/include/llvm/CodeGen/LiveRangeEdit.h 
b/llvm/include/llvm/CodeGen/LiveRangeEdit.h
index fe7af0a8fb45b..0950c20325fb0 100644
--- a/llvm/include/llvm/CodeGen/LiveRangeEdit.h
+++ b/llvm/include/llvm/CodeGen/LiveRangeEdit.h
@@ -97,8 +97,7 @@ class LiveRangeEdit : private MachineRegisterInfo::Delegate {
   /// a load, eliminate the register by folding the def into the use.
   bool foldAsLoad(LiveInterval *LI, SmallVectorImpl &Dead);
 
-  using ToShrinkSet = SetVector,
-SmallPtrSet>;
+  using ToShrinkSet = SmallSetVector;
 
   /// Helper for eliminateDeadDefs.
   void eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink);

diff  --git a/llvm/include

[PATCH] D152522: [NFC][SetVector] Update some usages of SetVector to SmallSetVector

2023-06-10 Thread Dhruv Chawla 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 rG8e580b7edd15: [NFC][SetVector] Update some usages of 
SetVector to SmallSetVector (authored by 0xdc03).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152522

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaStmt.cpp
  llvm/include/llvm/ADT/GenericCycleInfo.h
  llvm/include/llvm/CodeGen/LiveRangeEdit.h
  llvm/include/llvm/Transforms/Scalar/SROA.h
  llvm/lib/Analysis/InlineCost.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h

Index: llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
===
--- llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
+++ llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
@@ -318,9 +318,7 @@
 
   /// This is a collection of subprogram MDNodes that are processed to
   /// create DIEs.
-  SetVector,
-SmallPtrSet>
-  ProcessedSPNodes;
+  SmallSetVector ProcessedSPNodes;
 
   /// If nonnull, stores the current machine function we're processing.
   const MachineFunction *CurFn = nullptr;
Index: llvm/lib/Analysis/InlineCost.cpp
===
--- llvm/lib/Analysis/InlineCost.cpp
+++ llvm/lib/Analysis/InlineCost.cpp
@@ -2680,9 +2680,7 @@
   // basic blocks in a breadth-first order as we insert live successors. To
   // accomplish this, prioritizing for small iterations because we exit after
   // crossing our threshold, we use a small-size optimized SetVector.
-  typedef SetVector,
-SmallPtrSet>
-  BBSetVector;
+  typedef SmallSetVector BBSetVector;
   BBSetVector BBWorklist;
   BBWorklist.insert(&F.getEntryBlock());
 
Index: llvm/include/llvm/Transforms/Scalar/SROA.h
===
--- llvm/include/llvm/Transforms/Scalar/SROA.h
+++ llvm/include/llvm/Transforms/Scalar/SROA.h
@@ -105,7 +105,7 @@
   /// directly promoted. Finally, each time we rewrite a use of an alloca other
   /// the one being actively rewritten, we add it back onto the list if not
   /// already present to ensure it is re-visited.
-  SetVector> Worklist;
+  SmallSetVector Worklist;
 
   /// A collection of instructions to delete.
   /// We try to batch deletions to simplify code and make things a bit more
@@ -120,7 +120,7 @@
   ///
   /// Note that we have to be very careful to clear allocas out of this list in
   /// the event they are deleted.
-  SetVector> PostPromotionWorklist;
+  SmallSetVector PostPromotionWorklist;
 
   /// A collection of alloca instructions we can directly promote.
   std::vector PromotableAllocas;
@@ -130,7 +130,7 @@
   /// All of these PHIs have been checked for the safety of speculation and by
   /// being speculated will allow promoting allocas currently in the promotable
   /// queue.
-  SetVector> SpeculatablePHIs;
+  SmallSetVector SpeculatablePHIs;
 
   /// A worklist of select instructions to rewrite prior to promoting
   /// allocas.
Index: llvm/include/llvm/CodeGen/LiveRangeEdit.h
===
--- llvm/include/llvm/CodeGen/LiveRangeEdit.h
+++ llvm/include/llvm/CodeGen/LiveRangeEdit.h
@@ -97,8 +97,7 @@
   /// a load, eliminate the register by folding the def into the use.
   bool foldAsLoad(LiveInterval *LI, SmallVectorImpl &Dead);
 
-  using ToShrinkSet = SetVector,
-SmallPtrSet>;
+  using ToShrinkSet = SmallSetVector;
 
   /// Helper for eliminateDeadDefs.
   void eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink);
Index: llvm/include/llvm/ADT/GenericCycleInfo.h
===
--- llvm/include/llvm/ADT/GenericCycleInfo.h
+++ llvm/include/llvm/ADT/GenericCycleInfo.h
@@ -28,10 +28,10 @@
 #ifndef LLVM_ADT_GENERICCYCLEINFO_H
 #define LLVM_ADT_GENERICCYCLEINFO_H
 
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/GenericSSAContext.h"
 #include "llvm/ADT/GraphTraits.h"
 #include "llvm/ADT/SetVector.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -64,7 +64,7 @@
   /// Basic blocks that are contained in the cycle, including entry blocks,
   /// and including blocks that are part of a child cycle.
   using BlockSetVectorT = SetVector,
-SmallPtrSet>;
+DenseSet, 8>;
   BlockSetVectorT Blocks;
 
   /// Depth of the cycle in the tree. The root "cycle" is at depth 0.
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -1729,9 +1729,7 @@
 
 namespace {
   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
-  using DeclSetVe

[PATCH] D152090: [clang][Driver] Add -fcaret-diagnostics-max-lines as a driver option

2023-06-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 530168.

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

https://reviews.llvm.org/D152090

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/caret-diagnostics-max-lines.cpp
  clang/test/FixIt/fixit-function-call.cpp
  clang/test/Misc/caret-diags-multiline.cpp
  clang/test/Sema/caret-diags-complex-init.cpp


Index: clang/test/Sema/caret-diags-complex-init.cpp
===
--- clang/test/Sema/caret-diags-complex-init.cpp
+++ clang/test/Sema/caret-diags-complex-init.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -std=c++11 -fsyntax-only 
-fno-diagnostics-show-line-numbers -fcaret-diagnostics-max-lines 5 %s 2>&1 | 
FileCheck %s -strict-whitespace
+// RUN: not %clang_cc1 -std=c++11 -fsyntax-only 
-fno-diagnostics-show-line-numbers -fcaret-diagnostics-max-lines=5 %s 2>&1 | 
FileCheck %s -strict-whitespace
 
 
 //CHECK: {{.*}}: error: excess elements in scalar initializer
Index: clang/test/Misc/caret-diags-multiline.cpp
===
--- clang/test/Misc/caret-diags-multiline.cpp
+++ clang/test/Misc/caret-diags-multiline.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -std=c++11 -fno-diagnostics-show-line-numbers 
-fcaret-diagnostics-max-lines 5 -Wsometimes-uninitialized %s 2>&1 | FileCheck 
%s --strict-whitespace
+// RUN: not %clang_cc1 -std=c++11 -fno-diagnostics-show-line-numbers 
-fcaret-diagnostics-max-lines=5 -Wsometimes-uninitialized %s 2>&1 | FileCheck 
%s --strict-whitespace
 
 void line(int);
 
Index: clang/test/FixIt/fixit-function-call.cpp
===
--- clang/test/FixIt/fixit-function-call.cpp
+++ clang/test/FixIt/fixit-function-call.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -fdiagnostics-parseable-fixits 
-fno-diagnostics-show-line-numbers -fcaret-diagnostics-max-lines 1 -x c++ %s 2> 
%t
+// RUN: not %clang_cc1 -fdiagnostics-parseable-fixits 
-fno-diagnostics-show-line-numbers -fcaret-diagnostics-max-lines=1 -x c++ %s 2> 
%t
 // RUN: FileCheck %s < %t
 // PR5941
 // END.
Index: clang/test/Driver/caret-diagnostics-max-lines.cpp
===
--- /dev/null
+++ clang/test/Driver/caret-diagnostics-max-lines.cpp
@@ -0,0 +1,3 @@
+//RUN: %clang++ -### -fcaret-diagnostics-max-lines=2 %s 2>&1 | FileCheck %s
+
+// CHECK: "-fcaret-diagnostics-max-lines=2"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6045,6 +6045,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
 
   // Pass -fmessage-length=.
   unsigned MessageLength = 0;
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2301,6 +2301,11 @@
   Group, Flags<[NoXarchOption, CC1Option, CoreOption]>,
   HelpText<"Set the maximum number of entries to print in a macro expansion 
backtrace (0 = no limit)">,
   MarshallingInfoInt, 
"DiagnosticOptions::DefaultMacroBacktraceLimit">;
+def fcaret_diagnostics_max_lines_EQ :
+  Joined<["-"], "fcaret-diagnostics-max-lines=">,
+  Group, Flags<[NoXarchOption, CC1Option, CoreOption]>,
+  HelpText<"Set the maximum number of source lines to show in a caret 
diagnostic (0 = no limit).">,
+  MarshallingInfoInt, 
"DiagnosticOptions::DefaultSnippetLineLimit">;
 defm merge_all_constants : BoolFOption<"merge-all-constants",
   CodeGenOpts<"MergeAllConstants">, DefaultFalse,
   PosFlag, NegFlag,
@@ -5993,10 +5998,6 @@
 def ferror_limit : Separate<["-"], "ferror-limit">, MetaVarName<"">,
   HelpText<"Set the maximum number of errors to emit before stopping (0 = no 
limit).">,
   MarshallingInfoInt>;
-def fcaret_diagnostics_max_lines :
-  Separate<["-"], "fcaret-diagnostics-max-lines">, MetaVarName<"">,
-  HelpText<"Set the maximum number of source lines to show in a caret 
diagnostic">,
-  MarshallingInfoInt, 
"DiagnosticOptions::DefaultSnippetLineLimit">;
 def verify_EQ : CommaJoined<["-"], "verify=">,
   MetaVarName<"">,
   HelpText<"Verify diagnostic output using comment directives that start with"
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -230,9 +230,11 @@
 --
 - The flag ``-std=c++23`` has been added. This behaves the same as the existing
   flag ``-std=c++2b``.
-
 - ``-dumpdir`` has been implemented to s