[clang] [clang][analyzer][NFC] Add more information to CallDescriptions in StreamChecker (PR #70540)

2023-10-28 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/70540

'tmpfile' has only one form that it has no argument.

>From 043fbf02975dcc1adb894ae87f6c21dfd5f8479d Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Sat, 28 Oct 2023 14:57:44 +0800
Subject: [PATCH] [clang][analyzer][NFC] Add more information to
 CallDescriptions in StreamChecker

'tmpfile' has only one form that it has no argument.
---
 clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 4b7103c20557cc4..34df62f073e9a8c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -241,7 +241,7 @@ class StreamChecker : public Checkerhttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer][NFC] Add more information to CallDescriptions in StreamChecker (PR #70540)

2023-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ben Shi (benshi001)


Changes

'tmpfile' has only one form that it has no argument.

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+1-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 4b7103c20557cc4..34df62f073e9a8c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -241,7 +241,7 @@ class StreamChecker : public Checker


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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits

https://github.com/serge-sans-paille created 
https://github.com/llvm/llvm-project/pull/70543

None

>From 3fe63f81fcb999681daa11b2890c82fda3aaeef5 Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Thu, 26 Oct 2023 22:31:43 +0200
Subject: [PATCH 1/2] [clang] Change representation of CurLexerKind

Previous representation used an enumeration combined to a switch to
dispatch to the appropriate lexer.

Use function pointer so that the dispatching is just an indirect call,
which is actually better because lexing is a costly task compared to a
function call.

This also makes the code slightly cleaner, speedup on
compile time tracker are consistent and range form -0.05% to -0.20%
for NewPM-O0-g, see


https://llvm-compile-time-tracker.com/compare.php?from=f9906508bc4f05d3950e2219b4c56f6c078a61ef&to=608c85ec1283638db949d73e062bcc3355001ce4&stat=instructions:u

Considering just the preprocessing task, preprocessing the sqlite
amalgametion takes -0.6% instructions (according to valgrind
--tool=callgrind)
---
 clang/include/clang/Lex/Preprocessor.h| 46 +++-
 clang/lib/Lex/PPCaching.cpp   |  8 +--
 clang/lib/Lex/PPLexerChange.cpp   | 20 +++
 clang/lib/Lex/Preprocessor.cpp| 67 ++-
 clang/utils/ClangVisualizers/clang.natvis |  2 +-
 5 files changed, 62 insertions(+), 81 deletions(-)

diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 18d88407ae12c90..634d3924aa2248b 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -751,13 +751,8 @@ class Preprocessor {
   std::unique_ptr CurTokenLexer;
 
   /// The kind of lexer we're currently working with.
-  enum CurLexerKind {
-CLK_Lexer,
-CLK_TokenLexer,
-CLK_CachingLexer,
-CLK_DependencyDirectivesLexer,
-CLK_LexAfterModuleImport
-  } CurLexerKind = CLK_Lexer;
+  typedef bool (*LexerCallback)(Preprocessor &, Token &);
+  LexerCallback CurLexerCallback = &CLK_Lexer;
 
   /// If the current lexer is for a submodule that is being built, this
   /// is that submodule.
@@ -767,7 +762,7 @@ class Preprocessor {
   /// \#included, and macros currently being expanded from, not counting
   /// CurLexer/CurTokenLexer.
   struct IncludeStackInfo {
-enum CurLexerKind   CurLexerKind;
+LexerCallback CurLexerCallback;
 Module *TheSubmodule;
 std::unique_ptr  TheLexer;
 PreprocessorLexer  *ThePPLexer;
@@ -776,12 +771,12 @@ class Preprocessor {
 
 // The following constructors are completely useless copies of the default
 // versions, only needed to pacify MSVC.
-IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule,
+IncludeStackInfo(LexerCallback CurLexerCallback, Module *TheSubmodule,
  std::unique_ptr &&TheLexer,
  PreprocessorLexer *ThePPLexer,
  std::unique_ptr &&TheTokenLexer,
  ConstSearchDirIterator TheDirLookup)
-: CurLexerKind(std::move(CurLexerKind)),
+: CurLexerCallback(std::move(CurLexerCallback)),
   TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)),
   ThePPLexer(std::move(ThePPLexer)),
   TheTokenLexer(std::move(TheTokenLexer)),
@@ -1901,7 +1896,7 @@ class Preprocessor {
   /// Determine whether it's possible for a future call to Lex to produce an
   /// annotation token created by a previous call to EnterAnnotationToken.
   bool mightHavePendingAnnotationTokens() {
-return CurLexerKind != CLK_Lexer;
+return CurLexerCallback != CLK_Lexer;
   }
 
   /// Update the current token to represent the provided
@@ -1914,7 +1909,7 @@ class Preprocessor {
 
   /// Recompute the current lexer kind based on the CurLexer/
   /// CurTokenLexer pointers.
-  void recomputeCurLexerKind();
+  void recomputeCurLexerCallback();
 
   /// Returns true if incremental processing is enabled
   bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
@@ -2430,8 +2425,9 @@ class Preprocessor {
   friend void TokenLexer::ExpandFunctionArguments();
 
   void PushIncludeMacroStack() {
-assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer");
-IncludeMacroStack.emplace_back(CurLexerKind, CurLexerSubmodule,
+assert(CurLexerCallback != CLK_CachingLexer &&
+   "cannot push a caching lexer");
+IncludeMacroStack.emplace_back(CurLexerCallback, CurLexerSubmodule,
std::move(CurLexer), CurPPLexer,
std::move(CurTokenLexer), CurDirLookup);
 CurPPLexer = nullptr;
@@ -2443,7 +2439,7 @@ class Preprocessor {
 CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer);
 CurDirLookup  = IncludeMacroStack.back().TheDirLookup;
 CurLexerSubmodule = IncludeMacroStack.back().TheSubmodule;
-CurLexerKind = IncludeMacroStack.back().CurLexerKi

[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits

https://github.com/serge-sans-paille updated 
https://github.com/llvm/llvm-project/pull/70543

>From c9d34dae319de3eed1a23c23ff7b6d7673a04b79 Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Fri, 27 Oct 2023 22:48:08 +0200
Subject: [PATCH] [clang] Change GetCharAndSizeSlow interface to by-value style

Instead of passing the Size by reference, assuming it is initialized,
return it along the expected char result as an std::pair.

This makes the interface less error prone: previous interface expected
the Size reference to be initialized, and it was often forgotten,
leading to uninitialized variable usage. This patch fixes the issue.

This also generates faster code, as the returned pair (a char and an
unsigned) fits in 64 bits. The speedup according to compile time tracker
reach -O.7%, with a good number of -0.4%. Details are available on


https://llvm-compile-time-tracker.com/compare.php?from=3fe63f81fcb999681daa11b2890c82fda3aaeef5&to=fc76a9202f737472ecad4d6e0b0bf87a013866f3&stat=instructions:u

And icing on the cake, on my setup it also shaves 2kB out of
libclang-cpp :-)
---
 clang/include/clang/Lex/Lexer.h   | 30 +++
 clang/lib/Lex/DependencyDirectivesScanner.cpp |  7 +-
 clang/lib/Lex/Lexer.cpp   | 80 +++
 3 files changed, 61 insertions(+), 56 deletions(-)

diff --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h
index ac0ef14c591bdd7..9565fbd0da7feb3 100644
--- a/clang/include/clang/Lex/Lexer.h
+++ b/clang/include/clang/Lex/Lexer.h
@@ -577,17 +577,15 @@ class Lexer : public PreprocessorLexer {
 
   /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
   /// emit a warning.
-  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
-  const LangOptions &LangOpts) {
+  static inline std::pair
+  getCharAndSizeNoWarn(const char *Ptr, const LangOptions &LangOpts) {
 // If this is not a trigraph and not a UCN or escaped newline, return
 // quickly.
 if (isObviouslySimpleCharacter(Ptr[0])) {
-  Size = 1;
-  return *Ptr;
+  return std::make_pair(*Ptr, 1u);
 }
 
-Size = 0;
-return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
+return getCharAndSizeSlowNoWarn(Ptr, LangOpts);
   }
 
   /// Returns the leading whitespace for line that corresponds to the given
@@ -665,8 +663,7 @@ class Lexer : public PreprocessorLexer {
 // quickly.
 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
 
-unsigned Size = 0;
-char C = getCharAndSizeSlow(Ptr, Size, &Tok);
+auto [C, Size] = getCharAndSizeSlow(Ptr, &Tok);
 Ptr += Size;
 return C;
   }
@@ -682,9 +679,7 @@ class Lexer : public PreprocessorLexer {
 
 // Otherwise, re-lex the character with a current token, allowing
 // diagnostics to be emitted and flags to be set.
-Size = 0;
-getCharAndSizeSlow(Ptr, Size, &Tok);
-return Ptr+Size;
+return Ptr + getCharAndSizeSlow(Ptr, &Tok).second;
   }
 
   /// getCharAndSize - Peek a single 'character' from the specified buffer,
@@ -699,14 +694,15 @@ class Lexer : public PreprocessorLexer {
   return *Ptr;
 }
 
-Size = 0;
-return getCharAndSizeSlow(Ptr, Size);
+auto CharAndSize = getCharAndSizeSlow(Ptr);
+Size = CharAndSize.second;
+return CharAndSize.first;
   }
 
   /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
   /// method.
-  char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
-  Token *Tok = nullptr);
+  std::pair getCharAndSizeSlow(const char *Ptr,
+   Token *Tok = nullptr);
 
   /// getEscapedNewLineSize - Return the size of the specified escaped newline,
   /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
@@ -720,8 +716,8 @@ class Lexer : public PreprocessorLexer {
 
   /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
   /// diagnostic.
-  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
-   const LangOptions &LangOpts);
+  static std::pair
+  getCharAndSizeSlowNoWarn(const char *Ptr, const LangOptions &LangOpts);
 
   
//======//
   // Other lexer functions.
diff --git a/clang/lib/Lex/DependencyDirectivesScanner.cpp 
b/clang/lib/Lex/DependencyDirectivesScanner.cpp
index 2bd2c5f8388c0dd..f32b0f6767b9319 100644
--- a/clang/lib/Lex/DependencyDirectivesScanner.cpp
+++ b/clang/lib/Lex/DependencyDirectivesScanner.cpp
@@ -565,10 +565,9 @@ Scanner::cleanStringIfNeeded(const 
dependency_directives_scan::Token &Tok) {
   const char *BufPtr = Input.begin() + Tok.Offset;
   const char *AfterIdent = Input.begin() + Tok.getEnd();
   while (BufPtr < AfterIdent) {
-unsigned Size;
-Spelling[SpellingLength++] =
-Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangO

[clang] 8db38bd - [analyzer] Extend EnumCastOutOfRange diagnostics (#68191)

2023-10-28 Thread via cfe-commits

Author: Endre Fülöp
Date: 2023-10-28T10:22:46+02:00
New Revision: 8db38bd34421f87cbe7813aeeca81bcbd935025d

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

LOG: [analyzer] Extend EnumCastOutOfRange diagnostics (#68191)

EnumCastOutOfRange checker now reports the name of the enum in the
warning message. Additionally, a note-tag is placed to highlight the
location of the declaration.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
clang/test/Analysis/enum-cast-out-of-range.c
clang/test/Analysis/enum-cast-out-of-range.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
index 89be6a47250a245..5844f4399100183 100644
--- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
@@ -59,7 +59,8 @@ class ConstraintBasedEQEvaluator {
 // value can be matching.
 class EnumCastOutOfRangeChecker : public Checker> {
   mutable std::unique_ptr EnumValueCastOutOfRange;
-  void reportWarning(CheckerContext &C) const;
+  void reportWarning(CheckerContext &C, const CastExpr *CE,
+ const EnumDecl *E) const;
 
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
@@ -72,21 +73,38 @@ EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
   EnumValueVector DeclValues(
   std::distance(ED->enumerator_begin(), ED->enumerator_end()));
   llvm::transform(ED->enumerators(), DeclValues.begin(),
- [](const EnumConstantDecl *D) { return D->getInitVal(); });
+  [](const EnumConstantDecl *D) { return D->getInitVal(); });
   return DeclValues;
 }
 } // namespace
 
-void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
+void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
+  const CastExpr *CE,
+  const EnumDecl *E) const {
+  assert(E && "valid EnumDecl* is expected");
   if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
 if (!EnumValueCastOutOfRange)
   EnumValueCastOutOfRange.reset(
   new BugType(this, "Enum cast out of range"));
-constexpr llvm::StringLiteral Msg =
-"The value provided to the cast expression is not in the valid range"
-" of values for the enum";
-C.emitReport(std::make_unique(
-*EnumValueCastOutOfRange, Msg, N));
+
+llvm::SmallString<128> Msg{"The value provided to the cast expression is "
+   "not in the valid range of values for "};
+StringRef EnumName{E->getName()};
+if (EnumName.empty()) {
+  Msg += "the enum";
+} else {
+  Msg += '\'';
+  Msg += EnumName;
+  Msg += '\'';
+}
+
+auto BR = 
std::make_unique(*EnumValueCastOutOfRange,
+   Msg, N);
+bugreporter::trackExpressionValue(N, CE->getSubExpr(), *BR);
+BR->addNote("enum declared here",
+PathDiagnosticLocation::create(E, C.getSourceManager()),
+{E->getSourceRange()});
+C.emitReport(std::move(BR));
   }
 }
 
@@ -138,13 +156,13 @@ void EnumCastOutOfRangeChecker::checkPreStmt(const 
CastExpr *CE,
 return;
 
   // Check if any of the enum values possibly match.
-  bool PossibleValueMatch = llvm::any_of(
-  DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
+  bool PossibleValueMatch =
+  llvm::any_of(DeclValues, ConstraintBasedEQEvaluator(C, *ValueToCast));
 
   // If there is no value that can possibly match any of the enum values, then
   // warn.
   if (!PossibleValueMatch)
-reportWarning(C);
+reportWarning(C, CE, ED);
 }
 
 void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {

diff  --git a/clang/test/Analysis/enum-cast-out-of-range.c 
b/clang/test/Analysis/enum-cast-out-of-range.c
index 3282cba653d7125..4e5c9bb9ffdec41 100644
--- a/clang/test/Analysis/enum-cast-out-of-range.c
+++ b/clang/test/Analysis/enum-cast-out-of-range.c
@@ -1,7 +1,9 @@
 // RUN: %clang_analyze_cc1 \
 // RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
+// RUN:   -analyzer-output text \
 // RUN:   -verify %s
 
+// expected-note@+1 + {{enum declared here}}
 enum En_t {
   En_0 = -4,
   En_1,
@@ -11,17 +13,23 @@ enum En_t {
 };
 
 void unscopedUnspecifiedCStyle(void) {
-  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range}}
+  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range of values for 'En_t'}}
+// expected-note@-1 {{not in the valid 
range of valu

[clang] [analyzer] Extend EnumCastOutOfRange diagnostics (PR #68191)

2023-10-28 Thread Endre Fülöp via cfe-commits

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits

cor3ntin wrote:

Do you have benchmarks?
I wonder if we should use a small struct instead of pair, it would be slightly 
easier to maintain I think.
Looks good otherwise.

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


[clang] 4f6757c - [JITLink][RISCV] Implement eh_frame handling (#68253)

2023-10-28 Thread via cfe-commits

Author: Jonas Hahnfeld
Date: 2023-10-28T11:30:43+02:00
New Revision: 4f6757ce4bc78b7f56e4cb2a84c35444cd71c145

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

LOG: [JITLink][RISCV] Implement eh_frame handling (#68253)

This requires adding a `NegDelta32` edge kind that cannot be mapped to
existing relocations.

Co-authored-by: Job Noorman 

Added: 
llvm/test/ExecutionEngine/JITLink/RISCV/ELF_ehframe.s
llvm/test/ExecutionEngine/JITLink/RISCV/ELF_ehframe.test

Modified: 
clang/test/Interpreter/simple-exception.cpp
clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
llvm/include/llvm/ExecutionEngine/JITLink/riscv.h
llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp
llvm/lib/ExecutionEngine/JITLink/riscv.cpp

Removed: 




diff  --git a/clang/test/Interpreter/simple-exception.cpp 
b/clang/test/Interpreter/simple-exception.cpp
index 8741886a0a621cc..6749acd6e6bd23b 100644
--- a/clang/test/Interpreter/simple-exception.cpp
+++ b/clang/test/Interpreter/simple-exception.cpp
@@ -1,7 +1,7 @@
 // clang-format off
 // UNSUPPORTED: system-aix
-// XFAIL for arm, arm64, riscv, or running on Windows.
-// XFAIL: target={{(arm|riscv).*}}, system-windows
+// XFAIL for arm and arm64, or running on Windows.
+// XFAIL: target=arm{{.*}}, system-windows
 // RUN: cat %s | clang-repl | FileCheck %s
 
 // Incompatible with msan. It passes with -O3 but fail -Oz. Interpreter

diff  --git 
a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp 
b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
index 7b47d93446192ba..2f1c4efb381f00b 100644
--- a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
+++ b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
@@ -122,11 +122,6 @@ extern "C" int throw_exception() {
   Triple.getArch() == llvm::Triple::aarch64_32))
 GTEST_SKIP();
 
-  // FIXME: RISC-V fails as .eh_frame handling is not yet implemented in
-  // JITLink for RISC-V. See PR #66067.
-  if (Triple.isRISCV())
-GTEST_SKIP();
-
   llvm::cantFail(Interp->ParseAndExecute(ExceptionCode));
   testing::internal::CaptureStdout();
   auto ThrowException =

diff  --git a/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h 
b/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h
index cb66289180880ce..a31f7d73b099f45 100644
--- a/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h
+++ b/llvm/include/llvm/ExecutionEngine/JITLink/riscv.h
@@ -214,6 +214,12 @@ enum EdgeKind_riscv : Edge::Kind {
   /// Linker relaxation will use this to ensure all code sequences are properly
   /// aligned and then remove these edges from the graph.
   AlignRelaxable,
+
+  /// 32-bit negative delta.
+  ///
+  /// Fixup expression:
+  ///   Fixup <- Fixup - Target + Addend
+  NegDelta32,
 };
 
 /// Returns a string name for the given riscv edge. For debugging purposes

diff  --git a/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp 
b/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp
index 35816ea66cf9bc3..d0701ba08bd9194 100644
--- a/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp
+++ b/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp
@@ -11,10 +11,12 @@
 
//===--===//
 
 #include "llvm/ExecutionEngine/JITLink/ELF_riscv.h"
+#include "EHFrameSupportImpl.h"
 #include "ELFLinkGraphBuilder.h"
 #include "JITLinkGeneric.h"
 #include "PerGraphGOTAndPLTStubsBuilder.h"
 #include "llvm/BinaryFormat/ELF.h"
+#include "llvm/ExecutionEngine/JITLink/DWARFRecordSectionSplitter.h"
 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
 #include "llvm/ExecutionEngine/JITLink/riscv.h"
 #include "llvm/Object/ELF.h"
@@ -456,6 +458,13 @@ class ELFJITLinker_riscv : public 
JITLinker {
 case AlignRelaxable:
   // Ignore when the relaxation pass did not run
   break;
+case NegDelta32: {
+  int64_t Value = FixupAddress - E.getTarget().getAddress() + 
E.getAddend();
+  if (LLVM_UNLIKELY(!isInRangeForImm(Value, 32)))
+return makeTargetOutOfRangeError(G, B, E);
+  *(little32_t *)FixupPtr = static_cast(Value);
+  break;
+}
 }
 return Error::success();
   }
@@ -958,6 +967,13 @@ void link_ELF_riscv(std::unique_ptr G,
   PassConfiguration Config;
   const Triple &TT = G->getTargetTriple();
   if (Ctx->shouldAddDefaultTargetPasses(TT)) {
+
+Config.PrePrunePasses.push_back(DWARFRecordSectionSplitter(".eh_frame"));
+Config.PrePrunePasses.push_back(EHFrameEdgeFixer(
+".eh_frame", G->getPointerSize(), Edge::Invalid, Edge::Invalid,
+Edge::Invalid, Edge::Invalid, NegDelta32));
+Config.PrePrunePasses.push_back(EHFrameNullTerminator(".eh_frame"));
+
 if (auto MarkLive = Ctx->getMarkLivePass(TT))
   

[clang] [JITLink][RISCV] Implement eh_frame handling (PR #68253)

2023-10-28 Thread Jonas Hahnfeld via cfe-commits

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


[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-10-28 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/66583

>From 8b8acedc0e6c432545744a113128cfcb4f2da7e5 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH 01/19] [clang-tidy] add modernize-use-std-numbers check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../modernize/UseStdNumbersCheck.cpp  | 377 ++
 .../clang-tidy/modernize/UseStdNumbersCheck.h |  37 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/use-std-numbers.rst  |  25 ++
 .../checkers/modernize/use-std-numbers.cpp| 205 ++
 8 files changed, 655 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-numbers.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-numbers.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..d82353d74fbd0d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  UseStdNumbersCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 73751cf2705068d..73584e20166f66a 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MacroToEnumCheck.h"
 #include "MakeSharedCheck.h"
 #include "MakeUniqueCheck.h"
+#include "UseStdNumbersCheck.h"
 #include "PassByValueCheck.h"
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
@@ -65,6 +66,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-macro-to-enum");
 CheckFactories.registerCheck("modernize-make-shared");
 CheckFactories.registerCheck("modernize-make-unique");
+CheckFactories.registerCheck(
+"modernize-use-std-numbers");
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck("modernize-use-std-print");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
new file mode 100644
index 000..c23dc6671013bc3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
@@ -0,0 +1,377 @@
+//===--- UseStdNumbersCheck.cpp - clang_tidy -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX_License_Identifier: Apache_2.0 WITH LLVM_exception
+//
+//===--===//
+
+#include "UseStdNumbersCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502

[clang] [Driver] Handle Flang in same manner between Gnu and *BSD/Solaris ToolChain (PR #70429)

2023-10-28 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/70429

>From 8e3e053c7b8048387efb39808429cef9802ea68f Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Fri, 27 Oct 2023 04:53:19 -0400
Subject: [PATCH] [Driver] Handle Flang in same manner between Gnu and
 *BSD/Solaris ToolChain

---
 clang/lib/Driver/ToolChains/Gnu.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 5237951f84cce03..f19107f2374ce9e 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -574,7 +574,9 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
   // to generate executables. As Fortran runtime depends on the C runtime,
   // these dependencies need to be listed before the C runtime below (i.e.
   // AddRunTimeLibs).
-  if (D.IsFlangMode()) {
+  if (D.IsFlangMode() &&
+  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
+   options::OPT_r)) {
 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
 addFortranRuntimeLibs(ToolChain, CmdArgs);
 CmdArgs.push_back("-lm");

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


[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-10-28 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

I rebased and force-pushed my branch to fix the formatting CI (fetch depth for 
comparison with head was too big).
I pushed no actual changes in that force-push (one documentation ordering 
change in `fix lexicographical ordering in some places after rename` became 
redundant).
@EugeneZelenko's comments were already addressed and, even without the 
force-push, had already lost the context.

I'm not sure what the issue on Windows is. It looks like nothing within the 
function template `baz` is matching.

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


[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-10-28 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

Nice, the rebase fixed the Windows failure

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


[PATCH] D86993: Document Clang's expectations of the C standard library.

2023-10-28 Thread Ralf via Phabricator via cfe-commits
RalfJung added a comment.

With everything moving to github PRs, what are the next steps for this patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86993

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


[clang] [clang-format][NFC] Delete TT_LambdaArrow (PR #70519)

2023-10-28 Thread via cfe-commits

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


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


[clang] [clang-format] Change LLVM style to BreakAfterAttributes == ABS_Leave (PR #70360)

2023-10-28 Thread via cfe-commits

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


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


[clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

https://github.com/LYP951018 created 
https://github.com/llvm/llvm-project/pull/70548

Modifications:

- Skipped the instantiation of the explicit-specifier during Decl substitution 
if we were deducing template arguments and the explicit-specifier was value 
dependent.

- Instantiated the explicit-specifier after the constraint checking completed.

- Made `instantiateExplicitSpecifier` a member function in order to instantiate 
the explicit-specifier in different stages.


This PR doesn’t defer the instantiation of the explicit specifier for deduction 
guides, because I’m not familiar with deduction guides yet. I’ll dig into it 
after this PR.

According to my local test, GCC 13 tuple works with this PR.

Fixes #59827.

From 627abdf3126e25242ee9e823ecbc235b5ef4e8ac Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sat, 28 Oct 2023 18:05:36 +0800
Subject: [PATCH] Defer the instantiation of explicit-specifier after
 constraint checking

---
 clang/docs/ReleaseNotes.rst   |  4 ++
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 56 +++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 40 -
 .../SemaCXX/cxx2a-explicit-bool-deferred.cpp  | 31 ++
 5 files changed, 120 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/cxx2a-explicit-bool-deferred.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..ad41a831477f66c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Clang now defers the instantiation of explicit specifier until constraint 
checking
+  completes (except deduction guides). Fixes: 
+  (`#59827 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1e9752345ffd173..93fd6507db3d78a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10430,6 +10430,9 @@ class Sema final {
   const CXXConstructorDecl *Tmpl,
 const MultiLevelTemplateArgumentList 
&TemplateArgs);
 
+  ExplicitSpecifier instantiateExplicitSpecifier(
+  const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier 
ES);
+
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   const MultiLevelTemplateArgumentList &TemplateArgs,
   bool FindingInstantiatedContext = false);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b3f0247ea3bee3..e75e46aa5228812 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3553,6 +3553,53 @@ static unsigned getPackIndexForParam(Sema &S,
   llvm_unreachable("parameter index would not be produced from template");
 }
 
+// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`
+// we try to instantiate and update its explicit specifier after constraint
+// checking.
+static Sema::TemplateDeductionResult
+tryInstantiateExplicitSpecifier(Sema &S, FunctionDecl *Specialization,
+const MultiLevelTemplateArgumentList 
&SubstArgs,
+TemplateDeductionInfo &Info,
+FunctionTemplateDecl *FunctionTemplate,
+ArrayRef DeducedArgs) {
+
+  const auto TryInstantiateExplicitSpecifierForSingleDecl =
+  [&](auto *ExplicitDecl) {
+ExplicitSpecifier ExplicitSpecifier =
+ExplicitDecl->getExplicitSpecifier();
+Expr *const Expr = ExplicitSpecifier.getExpr();
+if (!Expr) {
+  return Sema::TDK_Success;
+}
+if (!Expr->isValueDependent()) {
+  return Sema::TDK_Success;
+}
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FunctionTemplate, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
+Info);
+const auto Instantiated =
+S.instantiateExplicitSpecifier(SubstArgs, ExplicitSpecifier);
+if (Instantiated.isInvalid()) {
+  ExplicitDecl->setInvalidDecl(true);
+  return clang::Sema::TDK_SubstitutionFailure;
+}
+ExplicitDecl->setExplicitSpecifier(Instantiated);
+return clang::Sema::TDK_Success;
+  };
+  Sema::TemplateDeductionResult DeductionResult = clang::Sema::TDK_Success;
+  if (CXXConstructorDecl *ConstructorDecl =
+  dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierF

[clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: 刘雨培 (LYP951018)


Changes

Modifications:

- Skipped the instantiation of the explicit-specifier during Decl substitution 
if we were deducing template arguments and the explicit-specifier was value 
dependent.

- Instantiated the explicit-specifier after the constraint checking completed.

- Made `instantiateExplicitSpecifier` a member function in order to instantiate 
the explicit-specifier in different stages.


This PR doesn’t defer the instantiation of the explicit specifier for deduction 
guides, because I’m not familiar with deduction guides yet. I’ll dig into it 
after this PR.

According to my local test, GCC 13 tuple works with this PR.

Fixes #59827.

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


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+4) 
- (modified) clang/include/clang/Sema/Sema.h (+3) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+56) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+26-14) 
- (added) clang/test/SemaCXX/cxx2a-explicit-bool-deferred.cpp (+31) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..ad41a831477f66c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Clang now defers the instantiation of explicit specifier until constraint 
checking
+  completes (except deduction guides). Fixes: 
+  (`#59827 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1e9752345ffd173..93fd6507db3d78a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10430,6 +10430,9 @@ class Sema final {
   const CXXConstructorDecl *Tmpl,
 const MultiLevelTemplateArgumentList 
&TemplateArgs);
 
+  ExplicitSpecifier instantiateExplicitSpecifier(
+  const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier 
ES);
+
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   const MultiLevelTemplateArgumentList &TemplateArgs,
   bool FindingInstantiatedContext = false);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b3f0247ea3bee3..e75e46aa5228812 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3553,6 +3553,53 @@ static unsigned getPackIndexForParam(Sema &S,
   llvm_unreachable("parameter index would not be produced from template");
 }
 
+// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`
+// we try to instantiate and update its explicit specifier after constraint
+// checking.
+static Sema::TemplateDeductionResult
+tryInstantiateExplicitSpecifier(Sema &S, FunctionDecl *Specialization,
+const MultiLevelTemplateArgumentList 
&SubstArgs,
+TemplateDeductionInfo &Info,
+FunctionTemplateDecl *FunctionTemplate,
+ArrayRef DeducedArgs) {
+
+  const auto TryInstantiateExplicitSpecifierForSingleDecl =
+  [&](auto *ExplicitDecl) {
+ExplicitSpecifier ExplicitSpecifier =
+ExplicitDecl->getExplicitSpecifier();
+Expr *const Expr = ExplicitSpecifier.getExpr();
+if (!Expr) {
+  return Sema::TDK_Success;
+}
+if (!Expr->isValueDependent()) {
+  return Sema::TDK_Success;
+}
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FunctionTemplate, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
+Info);
+const auto Instantiated =
+S.instantiateExplicitSpecifier(SubstArgs, ExplicitSpecifier);
+if (Instantiated.isInvalid()) {
+  ExplicitDecl->setInvalidDecl(true);
+  return clang::Sema::TDK_SubstitutionFailure;
+}
+ExplicitDecl->setExplicitSpecifier(Instantiated);
+return clang::Sema::TDK_Success;
+  };
+  Sema::TemplateDeductionResult DeductionResult = clang::Sema::TDK_Success;
+  if (CXXConstructorDecl *ConstructorDecl =
+  dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConstructorDecl);
+  } else if (CXXConversionDecl *ConversionDecl =
+ dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConversionDecl);
+  }
+  return DeductionRe

[clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

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


[clang] [Clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

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


[clang] [Clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

https://github.com/LYP951018 updated 
https://github.com/llvm/llvm-project/pull/70548

From 4f8111b58324d5b670311717d36654f64e6dac01 Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sat, 28 Oct 2023 18:05:36 +0800
Subject: [PATCH] Defer the instantiation of explicit-specifier after
 constraint checking

---
 clang/docs/ReleaseNotes.rst   |  4 ++
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 56 +++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 40 -
 .../SemaCXX/cxx2a-explicit-bool-deferred.cpp  | 31 ++
 5 files changed, 120 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/cxx2a-explicit-bool-deferred.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..203111b829bd0c6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Clang now defers the instantiation of explicit specifier until constraint 
checking
+  completes (except deduction guides). Fixes:
+  (`#59827 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1e9752345ffd173..93fd6507db3d78a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10430,6 +10430,9 @@ class Sema final {
   const CXXConstructorDecl *Tmpl,
 const MultiLevelTemplateArgumentList 
&TemplateArgs);
 
+  ExplicitSpecifier instantiateExplicitSpecifier(
+  const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier 
ES);
+
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   const MultiLevelTemplateArgumentList &TemplateArgs,
   bool FindingInstantiatedContext = false);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b3f0247ea3bee3..e75e46aa5228812 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3553,6 +3553,53 @@ static unsigned getPackIndexForParam(Sema &S,
   llvm_unreachable("parameter index would not be produced from template");
 }
 
+// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`
+// we try to instantiate and update its explicit specifier after constraint
+// checking.
+static Sema::TemplateDeductionResult
+tryInstantiateExplicitSpecifier(Sema &S, FunctionDecl *Specialization,
+const MultiLevelTemplateArgumentList 
&SubstArgs,
+TemplateDeductionInfo &Info,
+FunctionTemplateDecl *FunctionTemplate,
+ArrayRef DeducedArgs) {
+
+  const auto TryInstantiateExplicitSpecifierForSingleDecl =
+  [&](auto *ExplicitDecl) {
+ExplicitSpecifier ExplicitSpecifier =
+ExplicitDecl->getExplicitSpecifier();
+Expr *const Expr = ExplicitSpecifier.getExpr();
+if (!Expr) {
+  return Sema::TDK_Success;
+}
+if (!Expr->isValueDependent()) {
+  return Sema::TDK_Success;
+}
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FunctionTemplate, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
+Info);
+const auto Instantiated =
+S.instantiateExplicitSpecifier(SubstArgs, ExplicitSpecifier);
+if (Instantiated.isInvalid()) {
+  ExplicitDecl->setInvalidDecl(true);
+  return clang::Sema::TDK_SubstitutionFailure;
+}
+ExplicitDecl->setExplicitSpecifier(Instantiated);
+return clang::Sema::TDK_Success;
+  };
+  Sema::TemplateDeductionResult DeductionResult = clang::Sema::TDK_Success;
+  if (CXXConstructorDecl *ConstructorDecl =
+  dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConstructorDecl);
+  } else if (CXXConversionDecl *ConversionDecl =
+ dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConversionDecl);
+  }
+  return DeductionResult;
+}
+
 /// Finish template argument deduction for a function template,
 /// checking the deduced template arguments for completeness and forming
 /// the function template specialization.
@@ -3682,6 +3729,15 @@ Sema::TemplateDeductionResult 
Sema::FinishTemplateArgumentDeduction(
 }
   }
 
+  // We skipped the instantiation of the explicit-specifier during subst the
+  // decl b

[clang] [Clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-28 Thread via cfe-commits

https://github.com/LYP951018 updated 
https://github.com/llvm/llvm-project/pull/70548

From a5929ddc33057416cee75d91f13a1252f4357524 Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sat, 28 Oct 2023 18:05:36 +0800
Subject: [PATCH] Defer the instantiation of explicit-specifier after
 constraint checking

---
 clang/docs/ReleaseNotes.rst   |  4 ++
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 59 +++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 40 -
 .../SemaCXX/cxx2a-explicit-bool-deferred.cpp  | 31 ++
 5 files changed, 123 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/cxx2a-explicit-bool-deferred.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..203111b829bd0c6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Clang now defers the instantiation of explicit specifier until constraint 
checking
+  completes (except deduction guides). Fixes:
+  (`#59827 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1e9752345ffd173..93fd6507db3d78a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10430,6 +10430,9 @@ class Sema final {
   const CXXConstructorDecl *Tmpl,
 const MultiLevelTemplateArgumentList 
&TemplateArgs);
 
+  ExplicitSpecifier instantiateExplicitSpecifier(
+  const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier 
ES);
+
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   const MultiLevelTemplateArgumentList &TemplateArgs,
   bool FindingInstantiatedContext = false);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b3f0247ea3bee3..f06332770f51d1f 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3553,6 +3553,56 @@ static unsigned getPackIndexForParam(Sema &S,
   llvm_unreachable("parameter index would not be produced from template");
 }
 
+// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`
+// we try to instantiate and update its explicit specifier after constraint
+// checking.
+static Sema::TemplateDeductionResult
+tryInstantiateExplicitSpecifier(Sema &S, FunctionDecl *Specialization,
+const MultiLevelTemplateArgumentList 
&SubstArgs,
+TemplateDeductionInfo &Info,
+FunctionTemplateDecl *FunctionTemplate,
+ArrayRef DeducedArgs) {
+
+  const auto TryInstantiateExplicitSpecifierForSingleDecl =
+  [&](auto *ExplicitDecl) {
+ExplicitSpecifier ExplicitSpecifier =
+ExplicitDecl->getExplicitSpecifier();
+Expr *const Expr = ExplicitSpecifier.getExpr();
+if (!Expr) {
+  return Sema::TDK_Success;
+}
+if (!Expr->isValueDependent()) {
+  return Sema::TDK_Success;
+}
+// TemplateDeclInstantiator::InitFunctionInstantiation set the
+// ActiveInstType to TemplateInstantiation, but we need
+// to enable SFINAE when instantiating explicit specifier.
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FunctionTemplate, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
+Info);
+const auto Instantiated =
+S.instantiateExplicitSpecifier(SubstArgs, ExplicitSpecifier);
+if (Instantiated.isInvalid()) {
+  ExplicitDecl->setInvalidDecl(true);
+  return clang::Sema::TDK_SubstitutionFailure;
+}
+ExplicitDecl->setExplicitSpecifier(Instantiated);
+return clang::Sema::TDK_Success;
+  };
+  Sema::TemplateDeductionResult DeductionResult = clang::Sema::TDK_Success;
+  if (CXXConstructorDecl *ConstructorDecl =
+  dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConstructorDecl);
+  } else if (CXXConversionDecl *ConversionDecl =
+ dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConversionDecl);
+  }
+  return DeductionResult;
+}
+
 /// Finish template argument deduction for a function template,
 /// checking the deduced template arguments for completeness and forming
 /// the function template speciali

[clang] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70551)

2023-10-28 Thread Michael Buch via cfe-commits

https://github.com/Michael137 created 
https://github.com/llvm/llvm-project/pull/70551

When an LLDB user asks for the value of a static data member, LLDB starts by
searching the Names accelerator table for the corresponding variable definition
DIE. For static data members with out-of-class definitions that works fine,
because those get represented as global variables with a location and making 
them
eligible to be added to the Names table. However, in-class definitions won’t get
indexed because we usually don't emit global variables for them. So in DWARF
we end up with a single `DW_TAG_member` that usually holds the constant 
initializer.
But we don't get a corresponding CU-level `DW_TAG_variable` like we do for
out-of-class definitions.

To make it more convenient for debuggers to get to the value of inline static 
data members,
this patch makes sure we emit definitions for static variables with constant 
initializers
the same way we do for other static variables. This also aligns Clang closer to 
GCC, which
produces CU-level definitions for inline statics and also emits these into 
`.debug_pubnames`.

The implementation keeps track of newly created static data members. Then in
`CGDebugInfo::finalize`, we emit a global `DW_TAG_variable` with a 
`DW_AT_const_value` for
any of those declarations that didn't end up with a definition in the 
`DeclCache`.

The newly emitted `DW_TAG_variable` will look as follows:
```
0x007b:   DW_TAG_structure_type
DW_AT_calling_convention(DW_CC_pass_by_value)
DW_AT_name  ("Foo")
...

0x008d: DW_TAG_member
  DW_AT_name("i")
  DW_AT_type(0x0062 "const int")
  DW_AT_external(true)
  DW_AT_declaration (true)
  DW_AT_const_value (4)

Newly added
v

0x009a:   DW_TAG_variable
DW_AT_specification (0x008d "i")
DW_AT_const_value   (4)
DW_AT_linkage_name  ("_ZN2t2IiE1iIfEE")
```

>From e02939572877cdc839894454a6fab36ab143d924 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:33:07 +0100
Subject: [PATCH 1/2] [clang][DebugInfo][NFC] Add createConstantValueExpression
 helper

This patch factors out the code to create a DIExpression from
an APValue into a separate helper function.

This will be useful in a follow-up patch where we re-use this
logic elsewhere.
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 44 ++-
 clang/lib/CodeGen/CGDebugInfo.h   |  5 
 2 files changed, 31 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index c430713b0d77d79..a109f140cca80c8 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5574,25 +5574,8 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue &Init) {
   auto &GV = DeclCache[VD];
   if (GV)
 return;
-  llvm::DIExpression *InitExpr = nullptr;
-  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
-// FIXME: Add a representation for integer constants wider than 64 bits.
-if (Init.isInt()) {
-  const llvm::APSInt &InitInt = Init.getInt();
-  std::optional InitIntOpt;
-  if (InitInt.isUnsigned())
-InitIntOpt = InitInt.tryZExtValue();
-  else if (auto tmp = InitInt.trySExtValue(); tmp.has_value())
-// Transform a signed optional to unsigned optional. When cpp 23 comes,
-// use std::optional::transform
-InitIntOpt = (uint64_t)tmp.value();
-  if (InitIntOpt)
-InitExpr = DBuilder.createConstantValueExpression(InitIntOpt.value());
-} else if (Init.isFloat())
-  InitExpr = DBuilder.createConstantValueExpression(
-  Init.getFloat().bitcastToAPInt().getZExtValue());
-  }
 
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
   llvm::MDTuple *TemplateParameters = nullptr;
 
   if (isa(VD))
@@ -5929,3 +5912,28 @@ llvm::DINode::DIFlags 
CGDebugInfo::getCallSiteRelatedAttrs() const {
 
   return llvm::DINode::FlagAllCallsDescribed;
 }
+
+llvm::DIExpression *
+CGDebugInfo::createConstantValueExpression(clang::ValueDecl const *VD,
+   const APValue &Val) {
+  llvm::DIExpression *ValExpr = nullptr;
+  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
+// FIXME: Add a representation for integer constants wider than 64 bits.
+if (Val.isInt()) {
+  const llvm::APSInt &ValInt = Val.getInt();
+  std::optional ValIntOpt;
+  if (ValInt.isUnsigned())
+ValIntOpt = ValInt.tryZExtValue();
+  else if (auto tmp = ValInt.trySExtValue(); tmp.has_value())
+// Transform a signed optional to unsigned optional. When cpp 23 comes,
+// use std::optional::transform
+ValIntOpt = (uint64_t)tmp.value();
+  

[clang] 497b2eb - [clang-format] Change LLVM style to BreakAfterAttributes == ABS_Leave (#70360)

2023-10-28 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2023-10-28T16:02:03+04:00
New Revision: 497b2ebb9edcfd5315586b796f47589e9820b4b9

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

LOG: [clang-format] Change LLVM style to BreakAfterAttributes == ABS_Leave 
(#70360)

This patch addresses some examples of bad formatting in Clang. The following 
commit contains only changes suggested by clang-format: 
https://github.com/llvm/llvm-project/pull/70349/commits/21689b56d1fc1db0b2263e8049ff656d3757ad36.
I believe it's a net negative on readability, with a couple of particularly bad 
cases. Highlights:
```diff
-[[clang::preferred_type(bool)]]
-mutable unsigned CachedLocalOrUnnamed : 1;
+[[clang::preferred_type(bool)]] mutable unsigned CachedLocalOrUnnamed : 1;
```
```diff
-[[clang::preferred_type(TypeDependence)]]
-unsigned Dependence : llvm::BitWidth;
+[[clang::preferred_type(TypeDependence)]] unsigned Dependence
+: llvm::BitWidth;
```
```diff
-[[clang::preferred_type(ExceptionSpecificationType)]]
-unsigned ExceptionSpecType : 4;
+[[clang::preferred_type(
+ExceptionSpecificationType)]] unsigned ExceptionSpecType : 4;
```
Style guides doesn't appear to have an opinion on this matter.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..bc28bb567f6932a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -820,6 +820,7 @@ clang-format
 
 - Add ``AllowBreakBeforeNoexceptSpecifier`` option.
 - Add ``AllowShortCompoundRequirementOnASingleLine`` option.
+- Change ``BreakAfterAttributes`` from ``Never`` to ``Leave`` in LLVM style.
 
 libclang
 

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index edb33f4af4defef..e1abcac5604a410 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1476,7 +1476,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
  /*SplitEmptyFunction=*/true,
  /*SplitEmptyRecord=*/true,
  /*SplitEmptyNamespace=*/true};
-  LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Never;
+  LLVMStyle.BreakAfterAttributes = FormatStyle::ABS_Leave;
   LLVMStyle.BreakAfterJavaFieldAnnotations = false;
   LLVMStyle.BreakArrays = true;
   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b2d84f2ee389551..15c12c2b8b0da3f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26179,7 +26179,6 @@ TEST_F(FormatTest, RemoveSemicolon) {
 
 TEST_F(FormatTest, BreakAfterAttributes) {
   FormatStyle Style = getLLVMStyle();
-  EXPECT_EQ(Style.BreakAfterAttributes, FormatStyle::ABS_Never);
 
   constexpr StringRef Code("[[nodiscard]] inline int f(int &i);\n"
"[[foo([[]])]] [[nodiscard]]\n"
@@ -26194,6 +26193,10 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"  return 1;\n"
"}");
 
+  EXPECT_EQ(Style.BreakAfterAttributes, FormatStyle::ABS_Leave);
+  verifyNoChange(Code, Style);
+
+  Style.BreakAfterAttributes = FormatStyle::ABS_Never;
   verifyFormat("[[nodiscard]] inline int f(int &i);\n"
"[[foo([[]])]] [[nodiscard]] int g(int &i);\n"
"[[nodiscard]] inline int f(int &i) {\n"
@@ -26206,9 +26209,6 @@ TEST_F(FormatTest, BreakAfterAttributes) {
"}",
Code, Style);
 
-  Style.BreakAfterAttributes = FormatStyle::ABS_Leave;
-  verifyNoChange(Code, Style);
-
   Style.BreakAfterAttributes = FormatStyle::ABS_Always;
   verifyFormat("[[nodiscard]]\n"
"inline int f(int &i);\n"



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


[clang] [clang-format] Change LLVM style to BreakAfterAttributes == ABS_Leave (PR #70360)

2023-10-28 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang][NFC] Assert not llvm_unreachable (PR #70149)

2023-10-28 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [RISCV] Add sched model for XiangShan-NanHu (PR #70232)

2023-10-28 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/70232

>From b34055dca42c23682bb9f0e9e022f17e9dbf2aca Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Sat, 28 Oct 2023 20:46:37 +0800
Subject: [PATCH] [RISCV] Add sched model for XiangShan-NanHu

Co-authored-by: SForeKeeper 
---
 clang/test/Driver/riscv-cpus.c|  14 +
 clang/test/Misc/target-invalid-cpu-note.c |   4 +-
 llvm/lib/Target/RISCV/RISCV.td|   1 +
 llvm/lib/Target/RISCV/RISCVProcessors.td  |  21 +
 .../Target/RISCV/RISCVSchedXiangShanNanHu.td  | 307 ++
 .../llvm-mca/RISCV/XiangShan/cascade-fma.s|  53 ++
 .../llvm-mca/RISCV/XiangShan/gpr-bypass.s | 527 ++
 .../llvm-mca/RISCV/XiangShan/load-to-alu.s|  73 +++
 8 files changed, 998 insertions(+), 2 deletions(-)
 create mode 100644 llvm/lib/Target/RISCV/RISCVSchedXiangShanNanHu.td
 create mode 100644 llvm/test/tools/llvm-mca/RISCV/XiangShan/cascade-fma.s
 create mode 100644 llvm/test/tools/llvm-mca/RISCV/XiangShan/gpr-bypass.s
 create mode 100644 llvm/test/tools/llvm-mca/RISCV/XiangShan/load-to-alu.s

diff --git a/clang/test/Driver/riscv-cpus.c b/clang/test/Driver/riscv-cpus.c
index 3eaceedce685fc6..70f0a63336bd478 100644
--- a/clang/test/Driver/riscv-cpus.c
+++ b/clang/test/Driver/riscv-cpus.c
@@ -20,6 +20,17 @@
 // MCPU-SYNTACORE-SCR1-MAX: "-target-feature" "+zicsr" "-target-feature" 
"+zifencei"
 // MCPU-SYNTACORE-SCR1-MAX: "-target-abi" "ilp32"
 
+// RUN: %clang --target=riscv64 -### -c %s 2>&1 -mcpu=xiangshan-nanhu | 
FileCheck -check-prefix=MCPU-XIANGSHAN-NANHU %s
+// MCPU-XIANGSHAN-NANHU: "-nostdsysteminc" "-target-cpu" "xiangshan-nanhu"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+m" "-target-feature" "+a" 
"-target-feature" "+f" "-target-feature" "+d"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+c"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+zicbom" "-target-feature" 
"+zicboz" "-target-feature" "+zicsr" "-target-feature" "+zifencei"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+zba" "-target-feature" "+zbb" 
"-target-feature" "+zbc"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+zbkb" "-target-feature" "+zbkc" 
"-target-feature" "+zbkx" "-target-feature" "+zbs"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+zkn" "-target-feature" "+zknd" 
"-target-feature" "+zkne" "-target-feature" "+zknh"
+// MCPU-XIANGSHAN-NANHU: "-target-feature" "+zks" "-target-feature" "+zksed" 
"-target-feature" "+zksh" "-target-feature" "+svinval"
+// MCPU-XIANGSHAN-NANHU: "-target-abi" "lp64d"
+
 // We cannot check much for -mcpu=native, but it should be replaced by a valid 
CPU string.
 // RUN: %clang --target=riscv64 -### -c %s -mcpu=native 2> %t.err || true
 // RUN: FileCheck --input-file=%t.err -check-prefix=MCPU-NATIVE %s
@@ -62,6 +73,9 @@
 // RUN: %clang --target=riscv64 -### -c %s 2>&1 -mtune=veyron-v1 | FileCheck 
-check-prefix=MTUNE-VEYRON-V1 %s
 // MTUNE-VEYRON-V1: "-tune-cpu" "veyron-v1"
 
+// RUN: %clang --target=riscv64 -### -c %s 2>&1 -mtune=xiangshan-nanhu | 
FileCheck -check-prefix=MTUNE-XIANGSHAN-NANHU %s
+// MTUNE-XIANGSHAN-NANHU: "-tune-cpu" "xiangshan-nanhu"
+
 // Check mtune alias CPU has resolved to the right CPU according XLEN.
 // RUN: %clang --target=riscv32 -### -c %s 2>&1 -mtune=generic | FileCheck 
-check-prefix=MTUNE-GENERIC-32 %s
 // MTUNE-GENERIC-32: "-tune-cpu" "generic"
diff --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index b2a04ebdbce628f..8e91eb4c62dd259 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -85,7 +85,7 @@
 
 // RUN: not %clang_cc1 -triple riscv64 -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix RISCV64
 // RISCV64: error: unknown target CPU 'not-a-cpu'
-// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, 
sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74, 
sifive-x280, veyron-v1{{$}}
+// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, 
sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, sifive-u74, 
sifive-x280, veyron-v1, xiangshan-nanhu{{$}}
 
 // RUN: not %clang_cc1 -triple riscv32 -tune-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix TUNE-RISCV32
 // TUNE-RISCV32: error: unknown target CPU 'not-a-cpu'
@@ -93,4 +93,4 @@
 
 // RUN: not %clang_cc1 -triple riscv64 -tune-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix TUNE-RISCV64
 // TUNE-RISCV64: error: unknown target CPU 'not-a-cpu'
-// TUNE-RISCV64-NEXT: note: valid target CPU values are: generic-rv64, 
rocket-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, 
sifive-u74, sifive-x280, veyron-v1, generic, rocket, sifive-7-series{{$}}
+// TUNE-RISCV64-NEXT: note: valid target CPU values are: generic-rv64, 
rocket-rv64, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, 
sifive-u74, sifive-x280, veyron-v1, xiangshan-nanhu, generic, rocket

[clang] [RISCV] Add sched model for XiangShan-NanHu (PR #70232)

2023-10-28 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

Rebased on top of #70241.

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


[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

2023-10-28 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/70176

>From 9b559ac5504593ab7aa21539b49ece7eea944eb5 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 25 Oct 2023 10:08:24 +0200
Subject: [PATCH 1/3] [Clang] Diagnose defaulted assignment operator with
 incompatible object parameter.

Per https://eel.is/c++draft/dcl.fct.def.default#2.2, the explicit object
parameter of a defaulted special member function must be of the same type
as the one of an equivalent implicitly defaulted function,
ignoring references.

Fixes #69233
---
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/lib/Sema/SemaDeclCXX.cpp| 19 
 clang/test/SemaCXX/cxx2b-deducing-this.cpp| 31 +++
 3 files changed, 53 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a673ce726d6c220..6e138683334c2c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9481,6 +9481,9 @@ def err_defaulted_special_member_return_type : Error<
 def err_defaulted_special_member_quals : Error<
   "an explicitly-defaulted %select{copy|move}0 assignment operator may not "
   "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">;
+def err_defaulted_special_member_explicit_object_mismatch : Error<
+  "the type of the explicit object parameter of an explicitly-defaulted "
+  "%select{copy|move}0 assignment operator should match the type of the class 
%1">;
 def err_defaulted_special_member_volatile_param : Error<
   "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 
"
   "may not be volatile">;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6ec..957171b75ba4958 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7748,6 +7748,25 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 HadError = true;
   }
 }
+// [C++23][dcl.fct.def.default]/p2.2
+// if F2 has an implicit object parameter of type “reference to C”,
+// F1 may be an explicit object member function whose explicit object
+// parameter is of (possibly different) type “reference to C”,
+// in which case the type of F1 would differ from the type of F2
+// in that the type of F1 has an additional parameter;
+if (!Context.hasSameType(
+ThisType.getNonReferenceType().getUnqualifiedType(),
+Context.getRecordType(RD))) {
+  if (DeleteOnTypeMismatch)
+ShouldDeleteForTypeMismatch = true;
+  else {
+Diag(MD->getLocation(),
+ diag::err_defaulted_special_member_explicit_object_mismatch)
+<< (CSM == CXXMoveAssignment) << RD
+<< MD->getSourceRange();
+HadError = true;
+  }
+}
   }
 
   // Check for parameter type matching.
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 535381e876da9c7..f9e73b41e2c330f 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -585,3 +585,34 @@ class Server : public Thing {
 S name_;
 };
 }
+
+namespace GH69233 {
+struct Base {};
+struct S : Base {
+int j;
+S& operator=(this Base& self, const S&) = default;
+// expected-warning@-1 {{explicitly defaulted copy assignment operator is 
implicitly deleted}}
+// expected-note@-2 {{function is implicitly deleted because its declared 
type does not match the type of an implicit copy assignment operator}}
+// expected-note@-3 {{explicitly defaulted function was implicitly deleted 
here}}
+};
+
+struct S2 {
+S2& operator=(this int&& self, const S2&);
+S2& operator=(this int&& self, S2&&);
+operator int();
+};
+
+S2& S2::operator=(this int&& self, const S2&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted copy assignment operator should match the type of the 
class 'S2'}}
+
+S2& S2::operator=(this int&& self, S2&&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted move assignment operator should match the type of the 
class 'S2'}}
+
+void test() {
+S s;
+s = s; // expected-error {{object of type 'S' cannot be assigned because 
its copy assignment operator is implicitly deleted}}
+S2 s2;
+s2 = s2;
+}
+
+}

>From e5f681590232af81edddc764b749ad644e1ef0b4 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 26 Oct 2023 15:48:15 +0200
Subject: [PATCH 2/3] add source range

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

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 957171b75ba4958..beb7e5b177c6e9a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7762,8 +

[clang] [Driver] Handle Flang in same manner between Gnu and *BSD/Solaris ToolChain (PR #70429)

2023-10-28 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

@brad0 Thanks for sending this - could you provide some context in the summary? 
Why update the GNU Toolchain rather than *BSD  - as in, what should be source 
of truth here? Also, could you add tests?

I will be OK next week, but am happy for this to be merged once my comments are 
addressed and @MaskRay is also happy with this. Thanks!

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


[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2023-10-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/AST/OpenMPClause.h:2525
+
+  OMPClause *FailMemoryOrderClause = nullptr;
+  SourceLocation ArgumentLoc;

I don't like the idea of a reference to another clause here, it may lead to 
many issues with serialization/deserialization, use-after-free etc. Better to 
keep a flag (kind of memory order clause?) that there is associated clause here 
and then just find it in the list of clauses, where required.


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

https://reviews.llvm.org/D123235

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread Timm Baeder via cfe-commits

tbaederr wrote:

> Do you have benchmarks? I wonder if we should use a small struct instead of 
> pair, it would be slightly easier to maintain I think. Looks good otherwise.

See the commit: 
https://github.com/llvm/llvm-project/pull/70543/commits/c9d34dae319de3eed1a23c23ff7b6d7673a04b79

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


[clang] [clang][Interp] Implement builtin_expect (PR #69713)

2023-10-28 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Ping

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-28 Thread James E T Smith via cfe-commits

https://github.com/jamesETsmith updated 
https://github.com/llvm/llvm-project/pull/68494

>From c4a3ccfbad090ad8314aa8ad53092edc8d5432bc Mon Sep 17 00:00:00 2001
From: James Smith 
Date: Thu, 28 Sep 2023 10:11:15 -0400
Subject: [PATCH 01/12] [libc++] Implement ranges::iota and
 ranges::out_value_result

---
 libcxx/include/CMakeLists.txt |   2 +
 libcxx/include/__algorithm/out_value_result.h |  52 +
 libcxx/include/__numeric/ranges_iota.h|  53 +
 libcxx/include/algorithm  |   4 +
 libcxx/include/numeric|   1 +
 libcxx/include/version|   2 +-
 .../out_value_result.pass.cpp | 102 ++
 .../numeric.iota/ranges.iota.pass.cpp |  52 +
 8 files changed, 267 insertions(+), 1 deletion(-)
 create mode 100644 libcxx/include/__algorithm/out_value_result.h
 create mode 100644 libcxx/include/__numeric/ranges_iota.h
 create mode 100644 
libcxx/test/std/algorithms/algorithms.results/out_value_result.pass.cpp
 create mode 100644 
libcxx/test/std/numerics/numeric.ops/numeric.iota/ranges.iota.pass.cpp

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 2ec755236dbaee2..c6eb03f1d68e984 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -63,6 +63,7 @@ set(files
   __algorithm/next_permutation.h
   __algorithm/none_of.h
   __algorithm/nth_element.h
+  __algorithm/out_value_result.h
   __algorithm/partial_sort.h
   __algorithm/partial_sort_copy.h
   __algorithm/partition.h
@@ -561,6 +562,7 @@ set(files
   __numeric/partial_sum.h
   __numeric/pstl_reduce.h
   __numeric/pstl_transform_reduce.h
+  __numeric/ranges_iota.h
   __numeric/reduce.h
   __numeric/transform_exclusive_scan.h
   __numeric/transform_inclusive_scan.h
diff --git a/libcxx/include/__algorithm/out_value_result.h 
b/libcxx/include/__algorithm/out_value_result.h
new file mode 100644
index 000..8baffec7b9ef4da
--- /dev/null
+++ b/libcxx/include/__algorithm/out_value_result.h
@@ -0,0 +1,52 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+#define _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
+
+#include <__concepts/convertible_to.h>
+#include <__config>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+
+namespace ranges {
+
+template 
+struct out_value_result {
+  _LIBCPP_NO_UNIQUE_ADDRESS _OutIter1 out;
+  _LIBCPP_NO_UNIQUE_ADDRESS _ValType1 value;
+
+  template 
+requires convertible_to && 
convertible_to
+  constexpr operator out_value_result<_OutIter2, _ValType2>() const& { return 
{out, value}; }
+
+  template 
+requires convertible_to<_OutIter1, _OutIter2> && convertible_to<_ValType1, 
_ValType2>
+  constexpr operator out_value_result<_OutIter2, _ValType2>() && { return 
{std::move(out), std::move(value)}; }
+};
+
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER >= 23
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_OUT_VALUE_RESULT_H
diff --git a/libcxx/include/__numeric/ranges_iota.h 
b/libcxx/include/__numeric/ranges_iota.h
new file mode 100644
index 000..20311a68c2a348c
--- /dev/null
+++ b/libcxx/include/__numeric/ranges_iota.h
@@ -0,0 +1,53 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {
+while (__first != __last) {
+  *__first = static_cast(__value);
+  ++__first;
+  ++__value;
+}
+return {std::move(__first), std::move(__valu

[clang] [Driver] Handle Flang in same manner between Gnu and *BSD/Solaris ToolChain (PR #70429)

2023-10-28 Thread Fangrui Song via cfe-commits

MaskRay wrote:

Seems fine to me once a test is added:)

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


[PATCH] D150083: [clang-format] ObjCPropertyAttributeOrder to sort ObjC property attributes

2023-10-28 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb updated this revision to Diff 557922.
jaredgrubb added a comment.

Address review feedback from @owenpan on Oct23. Thanks for helping me tune this 
patch!


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

https://reviews.llvm.org/D150083

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/Format.cpp
  clang/lib/Format/ObjCPropertyAttributeOrderFixer.cpp
  clang/lib/Format/ObjCPropertyAttributeOrderFixer.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp

Index: clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp
@@ -0,0 +1,393 @@
+//===- unittest/Format/ObjCPropertyAttributeOrderFixerTest.cpp - unit tests
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "../lib/Format/ObjCPropertyAttributeOrderFixer.h"
+#include "FormatTestBase.h"
+#include "TestLexer.h"
+
+#define DEBUG_TYPE "format-objc-property-attribute-order-fixer-test"
+
+namespace clang {
+namespace format {
+namespace test {
+namespace {
+
+#define CHECK_PARSE(TEXT, FIELD, VALUE)\
+  EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";  \
+  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());  \
+  EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
+
+#define FAIL_PARSE(TEXT, FIELD, VALUE) \
+  EXPECT_NE(0, parseConfiguration(TEXT, &Style).value());  \
+  EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
+
+class ObjCPropertyAttributeOrderFixerTest : public FormatTestBase {
+protected:
+  TokenList annotate(llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+return TestLexer(Allocator, Buffers, Style).annotate(Code);
+  }
+
+  llvm::SpecificBumpPtrAllocator Allocator;
+  std::vector> Buffers;
+};
+
+TEST_F(ObjCPropertyAttributeOrderFixerTest, ParsesStyleOption) {
+  FormatStyle Style = {};
+  Style.Language = FormatStyle::LK_ObjC;
+
+  CHECK_PARSE("ObjCPropertyAttributeOrder: [class]", ObjCPropertyAttributeOrder,
+  std::vector({"class"}));
+
+  CHECK_PARSE("ObjCPropertyAttributeOrder: ["
+  "class, direct, atomic, nonatomic, "
+  "assign, retain, strong, copy, weak, unsafe_unretained, "
+  "readonly, readwrite, getter, setter, "
+  "nullable, nonnull, null_resettable, null_unspecified"
+  "]",
+  ObjCPropertyAttributeOrder,
+  std::vector({
+  "class",
+  "direct",
+  "atomic",
+  "nonatomic",
+  "assign",
+  "retain",
+  "strong",
+  "copy",
+  "weak",
+  "unsafe_unretained",
+  "readonly",
+  "readwrite",
+  "getter",
+  "setter",
+  "nullable",
+  "nonnull",
+  "null_resettable",
+  "null_unspecified",
+  }));
+}
+
+TEST_F(ObjCPropertyAttributeOrderFixerTest, SortsSpecifiedAttributes) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ObjCPropertyAttributeOrder = {"a", "b", "c"};
+
+  verifyFormat("@property() int p;", Style);
+
+  // One: shouldn't move.
+  verifyFormat("@property(a) int p;", Style);
+  verifyFormat("@property(b) int p;", Style);
+  verifyFormat("@property(c) int p;", Style);
+
+  // Two in correct order already: no change.
+  verifyFormat("@property(a, b) int p;", Style);
+  verifyFormat("@property(a, c) int p;", Style);
+  verifyFormat("@property(b, c) int p;", Style);
+
+  // Three in correct order already: no change.
+  verifyFormat("@property(a, b, c) int p;", Style);
+
+  // Two wrong order.
+  verifyFormat("@property(a, b) int p;", "@property(b, a) int p;", Style);
+  verifyFormat("@property(a, c) int p;", "@property(c, a) int p;", Style);
+  verifyFormat("@property(b, c) int p;", "@property(c, b) int p;", Style);
+
+  // Three wrong order.
+  verifyFormat("@property(a, b, c) int p;", "@property(b, a, c) int p;", Style);
+  verifyFormat("@property(a, b, c) int p;", "@property(c, b, a) int p;", Style);
+}
+
+TEST_F(ObjCPropertyAttributeOrderFixerTest, SortsAttributesWithValues) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ObjCPropertyAttributeOrder = {"a", "getter", "c"};
+
+  // No change
+  verifyFor

[PATCH] D150083: [clang-format] ObjCPropertyAttributeOrder to sort ObjC property attributes

2023-10-28 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb added a comment.

Should I open a GitHub issue for this patch?


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

https://reviews.llvm.org/D150083

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


[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti created 
https://github.com/llvm/llvm-project/pull/70559

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297


>From b29eb35fe8597ceefc4c615817174181a16f3c4c Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 28 Oct 2023 18:08:51 +0200
Subject: [PATCH] [clang-tidy] fix match for binaryOperator in
 ExprMutationAnalyzer for misc-const-correctness

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checkers/misc/const-correctness-templates.cpp | 11 +++
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Analysis/ExprMutationAnalyzer.cpp   |  6 +++---
 clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp | 11 +++
 5 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5ce38ab48bf295f..bb75c9a3ce08125 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness
+  ` check to not warn on uses in
+  type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
+
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence, avoid
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
index 7b5ccabdd6ef611..415bb06020b9dc3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
@@ -20,3 +20,14 @@ void instantiate_template_cases() {
   type_dependent_variables();
   type_dependent_variables();
 }
+
+namespace gh57297{
+struct Stream {};
+// Explicitly not declaring a (templated) stream operator
+// so the `<<` is a `binaryOperator` with a dependent type.
+template  void f() {
+  T t;
+  Stream stream;
+  stream << t;
+}
+} // namespace gh57297
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..fb9afc0646ac8cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation
+  for uses in type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index f2e1beb025423cf..624a643cc60e4ba 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -296,9 +296,9 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   // resolved and modelled as `binaryOperator` on a dependent type.
   // Such instances are considered a modification, because they can modify
   // in different instantiations of the template.
-  binaryOperator(hasEitherOperand(
-  allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
-isTypeDependent(,
+  binaryOperator(
+  
hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp,
+  isTypeDependent()),
   // Within class templates and member functions the member expression 
might
   // not be resolved. In that case, the `callExpr` is considered to be a
   // modification.
diff --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index c0a398394093c48..cfa3c535ce35292 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -343,6 +343,17 @@ TEST(ExprMutati

[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Julian Schmidt (5chmidti)


Changes

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297


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


5 Files Affected:

- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp 
(+11) 
- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Analysis/ExprMutationAnalyzer.cpp (+3-3) 
- (modified) clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp (+11) 


``diff
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5ce38ab48bf295f..bb75c9a3ce08125 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness
+  ` check to not warn on uses in
+  type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
+
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence, avoid
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
index 7b5ccabdd6ef611..415bb06020b9dc3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
@@ -20,3 +20,14 @@ void instantiate_template_cases() {
   type_dependent_variables();
   type_dependent_variables();
 }
+
+namespace gh57297{
+struct Stream {};
+// Explicitly not declaring a (templated) stream operator
+// so the `<<` is a `binaryOperator` with a dependent type.
+template  void f() {
+  T t;
+  Stream stream;
+  stream << t;
+}
+} // namespace gh57297
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..fb9afc0646ac8cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation
+  for uses in type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index f2e1beb025423cf..624a643cc60e4ba 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -296,9 +296,9 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   // resolved and modelled as `binaryOperator` on a dependent type.
   // Such instances are considered a modification, because they can modify
   // in different instantiations of the template.
-  binaryOperator(hasEitherOperand(
-  allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
-isTypeDependent(,
+  binaryOperator(
+  
hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp,
+  isTypeDependent()),
   // Within class templates and member functions the member expression 
might
   // not be resolved. In that case, the `callExpr` is considered to be a
   // modification.
diff --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index c0a398394093c48..cfa3c535ce35292 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -343,6 +343,17 @@ TEST(ExprMutationAnalyzerTest, UnresolvedOperator) {
   EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, DependentOperatorWithNonDependentOperand) {
+  // gh57297
+  // Explicitly not declaring a (templated) stream operator
+  // so the `<<` is a `binaryOperator` with a dependent type.
+  const auto AST = buildASTFromCode("struct Stream {}; template  "
+"void f() { T t; Stream x; x << t;}");
+  const auto Results =
+  match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+  EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x <

[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

CC @JonasToth for your work on `ExprMutationAnalyzer`

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


[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

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


@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation

PiotrZSL wrote:

I think this should be under static analyzer changes or not included at all.

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


[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/70559

>From b29eb35fe8597ceefc4c615817174181a16f3c4c Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 28 Oct 2023 18:08:51 +0200
Subject: [PATCH 1/2] [clang-tidy] fix match for binaryOperator in
 ExprMutationAnalyzer for misc-const-correctness

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checkers/misc/const-correctness-templates.cpp | 11 +++
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Analysis/ExprMutationAnalyzer.cpp   |  6 +++---
 clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp | 11 +++
 5 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5ce38ab48bf295f..bb75c9a3ce08125 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness
+  ` check to not warn on uses in
+  type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
+
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence, avoid
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
index 7b5ccabdd6ef611..415bb06020b9dc3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
@@ -20,3 +20,14 @@ void instantiate_template_cases() {
   type_dependent_variables();
   type_dependent_variables();
 }
+
+namespace gh57297{
+struct Stream {};
+// Explicitly not declaring a (templated) stream operator
+// so the `<<` is a `binaryOperator` with a dependent type.
+template  void f() {
+  T t;
+  Stream stream;
+  stream << t;
+}
+} // namespace gh57297
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..fb9afc0646ac8cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation
+  for uses in type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index f2e1beb025423cf..624a643cc60e4ba 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -296,9 +296,9 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   // resolved and modelled as `binaryOperator` on a dependent type.
   // Such instances are considered a modification, because they can modify
   // in different instantiations of the template.
-  binaryOperator(hasEitherOperand(
-  allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
-isTypeDependent(,
+  binaryOperator(
+  
hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp,
+  isTypeDependent()),
   // Within class templates and member functions the member expression 
might
   // not be resolved. In that case, the `callExpr` is considered to be a
   // modification.
diff --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index c0a398394093c48..cfa3c535ce35292 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -343,6 +343,17 @@ TEST(ExprMutationAnalyzerTest, UnresolvedOperator) {
   EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, DependentOperatorWithNonDependentOperand) {
+  // gh57297
+  // Explicitly not declaring a (templated) stream operator
+  // so the `<<` is a `binaryOperator` with a dependent type.
+  const auto AST = buildASTFromCode("struct Stream {}; template  "
+

[clang] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70551)

2023-10-28 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/70551

>From e02939572877cdc839894454a6fab36ab143d924 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:33:07 +0100
Subject: [PATCH 1/3] [clang][DebugInfo][NFC] Add createConstantValueExpression
 helper

This patch factors out the code to create a DIExpression from
an APValue into a separate helper function.

This will be useful in a follow-up patch where we re-use this
logic elsewhere.
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 44 ++-
 clang/lib/CodeGen/CGDebugInfo.h   |  5 
 2 files changed, 31 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index c430713b0d77d79..a109f140cca80c8 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5574,25 +5574,8 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue &Init) {
   auto &GV = DeclCache[VD];
   if (GV)
 return;
-  llvm::DIExpression *InitExpr = nullptr;
-  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
-// FIXME: Add a representation for integer constants wider than 64 bits.
-if (Init.isInt()) {
-  const llvm::APSInt &InitInt = Init.getInt();
-  std::optional InitIntOpt;
-  if (InitInt.isUnsigned())
-InitIntOpt = InitInt.tryZExtValue();
-  else if (auto tmp = InitInt.trySExtValue(); tmp.has_value())
-// Transform a signed optional to unsigned optional. When cpp 23 comes,
-// use std::optional::transform
-InitIntOpt = (uint64_t)tmp.value();
-  if (InitIntOpt)
-InitExpr = DBuilder.createConstantValueExpression(InitIntOpt.value());
-} else if (Init.isFloat())
-  InitExpr = DBuilder.createConstantValueExpression(
-  Init.getFloat().bitcastToAPInt().getZExtValue());
-  }
 
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
   llvm::MDTuple *TemplateParameters = nullptr;
 
   if (isa(VD))
@@ -5929,3 +5912,28 @@ llvm::DINode::DIFlags 
CGDebugInfo::getCallSiteRelatedAttrs() const {
 
   return llvm::DINode::FlagAllCallsDescribed;
 }
+
+llvm::DIExpression *
+CGDebugInfo::createConstantValueExpression(clang::ValueDecl const *VD,
+   const APValue &Val) {
+  llvm::DIExpression *ValExpr = nullptr;
+  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
+// FIXME: Add a representation for integer constants wider than 64 bits.
+if (Val.isInt()) {
+  const llvm::APSInt &ValInt = Val.getInt();
+  std::optional ValIntOpt;
+  if (ValInt.isUnsigned())
+ValIntOpt = ValInt.tryZExtValue();
+  else if (auto tmp = ValInt.trySExtValue(); tmp.has_value())
+// Transform a signed optional to unsigned optional. When cpp 23 comes,
+// use std::optional::transform
+ValIntOpt = (uint64_t)tmp.value();
+  if (ValIntOpt)
+ValExpr = DBuilder.createConstantValueExpression(ValIntOpt.value());
+} else if (Val.isFloat())
+  ValExpr = DBuilder.createConstantValueExpression(
+  Val.getFloat().bitcastToAPInt().getZExtValue());
+  }
+
+  return ValExpr;
+}
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index ae12485850ca775..7b60e94555d0608 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -800,6 +800,11 @@ class CGDebugInfo {
llvm::MDTuple *&TemplateParameters,
llvm::DIScope *&VDContext);
 
+  /// Create a DIExpression representing the constant corresponding
+  /// to the specified 'Val'. Returns nullptr on failure.
+  llvm::DIExpression *createConstantValueExpression(const clang::ValueDecl *VD,
+const APValue &Val);
+
   /// Allocate a copy of \p A using the DebugInfoNames allocator
   /// and return a reference to it. If multiple arguments are given the strings
   /// are concatenated.

>From 119276638095f48d8d2a5dd8fc7e042059e66378 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:19:47 +0100
Subject: [PATCH 2/3] [clang][DebugInfo] Emit global variable definitions for
 static data members with constant initializers
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

When an LLDB user asks for the value of a static data member, LLDB starts by
searching the Names accelerator table for the corresponding variable definition
DIE. For static data members with out-of-class definitions that works fine,
because those get represented as global variables with a location and making 
them
eligible to be added to the Names table. However, in-class definitions won’t get
indexed because we usually don't emit global variables for them. So in DWARF
we end up with a single `DW_TAG_member` that usually holds the constant 
initializer.
But we don't get a corresponding CU-level `DW_TAG_

[clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread Julian Schmidt via cfe-commits


@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation

5chmidti wrote:

Done

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


[clang] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-10-28 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

The top-level Linux and Windows tests work, but inside the `Trigger 
Build`/`clang-ci` run, the windows test step fails. I'm not sure what the 
difference is between these two Windows tests.

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


[clang] Bfi precision (PR #66285)

2023-10-28 Thread Duncan P . N . Exon Smith via cfe-commits

dexonsmith wrote:

Interesting. Probably `Value::getMetadata()` could/should call 
`DenseMap::find()` instead of `operator[]()` and assert that it's found before 
dereferencing, because `Value::hasMetadata()` (which, IIRC, consults a bit 
stored in `Value`) has already promised something will be there. Probably 
you'll find me on the git-blame for this...

Your plan SGTM!

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


[clang] [clang] Robustify openmp test (PR #69739)

2023-10-28 Thread Johannes Doerfert via cfe-commits

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

LG, thx

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-28 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov updated 
https://github.com/llvm/llvm-project/pull/68993

>From ed580b95157d7f423c5384fa2d51af00f1359a10 Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Mon, 2 Oct 2023 14:46:27 +0100
Subject: [PATCH 1/3] [CFIFixup] Allow function prologues to span more than one
 basic block

The CFIFixup pass assumes a function prologue is contained in a single
basic block. This assumption is broken with upcoming support for stack
probing (`-fstack-clash-protection`) in AArch64 - the emitted probing
sequence in a prologue may contain loops, i.e. more than one basic
block. The generated CFG is not arbitrary though:
 * CFI instructions are outside of any loops
 * for any two CFI instructions of the function prologue one dominates
   and is post-dominated by the other

Thus, for the prologue CFI instructions, if one is
executed then all are executed, there is a total order of
executions, and the last instruction in that order can be considered
the end of the prologoue for the purpose of inserting the initial
`.cfi_remember_state` directive.

That last instruction is found by finding the first block in the
post-order traversal which contains prologue CFI instructions.
---
 llvm/lib/CodeGen/CFIFixup.cpp |  62 ++--
 .../cfi-fixup-multi-block-prologue.mir| 308 ++
 2 files changed, 347 insertions(+), 23 deletions(-)
 create mode 100644 llvm/test/CodeGen/AArch64/cfi-fixup-multi-block-prologue.mir

diff --git a/llvm/lib/CodeGen/CFIFixup.cpp b/llvm/lib/CodeGen/CFIFixup.cpp
index 837dbd77d07361a..964a8d56511fa1b 100644
--- a/llvm/lib/CodeGen/CFIFixup.cpp
+++ b/llvm/lib/CodeGen/CFIFixup.cpp
@@ -10,20 +10,25 @@
 // This pass inserts the necessary  instructions to adjust for the 
inconsistency
 // of the call-frame information caused by final machine basic block layout.
 // The pass relies in constraints LLVM imposes on the placement of
-// save/restore points (cf. ShrinkWrap):
-// * there is a single basic block, containing the function prologue
+// save/restore points (cf. ShrinkWrap) and has certain preconditions about
+// placement of CFI instructions:
+// * for any two CFI instructions of the function prologue one dominates
+//   and is post-dominated by the other
 // * possibly multiple epilogue blocks, where each epilogue block is
 //   complete and self-contained, i.e. CSR restore instructions (and the
 //   corresponding CFI instructions are not split across two or more blocks.
-// * prologue and epilogue blocks are outside of any loops
-// Thus, during execution, at the beginning and at the end of each basic block
-// the function can be in one of two states:
+// * CFI instructions are not contained in any loops
+// Thus, during execution, at the beginning and at the end of each basic block,
+// following the prologue, the function can be in one of two states:
 //  - "has a call frame", if the function has executed the prologue, and
 //has not executed any epilogue
 //  - "does not have a call frame", if the function has not executed the
 //prologue, or has executed an epilogue
 // which can be computed by a single RPO traversal.
 
+// The location of the prologue is determined by finding the first block in the
+// post-order traversal which contains CFI instructions.
+
 // In order to accommodate backends which do not generate unwind info in
 // epilogues we compute an additional property "strong no call frame on entry",
 // which is set for the entry point of the function and for every block
@@ -85,10 +90,6 @@ static bool isPrologueCFIInstruction(const MachineInstr &MI) 
{
  MI.getFlag(MachineInstr::FrameSetup);
 }
 
-static bool containsPrologue(const MachineBasicBlock &MBB) {
-  return llvm::any_of(MBB.instrs(), isPrologueCFIInstruction);
-}
-
 static bool containsEpilogue(const MachineBasicBlock &MBB) {
   return llvm::any_of(llvm::reverse(MBB), [](const auto &MI) {
 return MI.getOpcode() == TargetOpcode::CFI_INSTRUCTION &&
@@ -96,6 +97,25 @@ static bool containsEpilogue(const MachineBasicBlock &MBB) {
   });
 }
 
+static MachineBasicBlock *
+findPrologueEnd(MachineFunction &MF, MachineBasicBlock::iterator &PrologueEnd) 
{
+  MachineBasicBlock *PrologueBlock = nullptr;
+  for (auto It = po_begin(&MF.front()), End = po_end(&MF.front()); It != End;
+   ++It) {
+MachineBasicBlock *MBB = *It;
+llvm::for_each(MBB->instrs(), [&](MachineInstr &MI) {
+  if (isPrologueCFIInstruction(MI)) {
+PrologueBlock = MBB;
+PrologueEnd = std::next(MI.getIterator());
+  }
+});
+if (PrologueBlock)
+  return PrologueBlock;
+  }
+
+  return nullptr;
+}
+
 bool CFIFixup::runOnMachineFunction(MachineFunction &MF) {
   const TargetFrameLowering &TFL = *MF.getSubtarget().getFrameLowering();
   if (!TFL.enableCFIFixup(MF))
@@ -105,6 +125,14 @@ bool CFIFixup::runOnMachineFunction(MachineFunction &MF) {
   if (NumBlocks < 2)
 return false;
 
+  // Find the prologue and the point where we can issue the 

[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-28 Thread Momchil Velikov via cfe-commits


@@ -85,17 +90,32 @@ static bool isPrologueCFIInstruction(const MachineInstr 
&MI) {
  MI.getFlag(MachineInstr::FrameSetup);
 }
 
-static bool containsPrologue(const MachineBasicBlock &MBB) {
-  return llvm::any_of(MBB.instrs(), isPrologueCFIInstruction);
-}
-
 static bool containsEpilogue(const MachineBasicBlock &MBB) {
   return llvm::any_of(llvm::reverse(MBB), [](const auto &MI) {
 return MI.getOpcode() == TargetOpcode::CFI_INSTRUCTION &&
MI.getFlag(MachineInstr::FrameDestroy);
   });
 }
 
+static MachineBasicBlock *
+findPrologueEnd(MachineFunction &MF, MachineBasicBlock::iterator &PrologueEnd) 
{
+  MachineBasicBlock *PrologueBlock = nullptr;
+  for (auto It = po_begin(&MF.front()), End = po_end(&MF.front()); It != End;
+   ++It) {
+MachineBasicBlock *MBB = *It;
+llvm::for_each(MBB->instrs(), [&](MachineInstr &MI) {

momchil-velikov wrote:

Done (in another PR).

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


[clang] [OpenMP] Unify the min/max thread/teams pathways (PR #70273)

2023-10-28 Thread Johannes Doerfert via cfe-commits


@@ -1,68 +1,20 @@
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s -check-prefix=CHECK1
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s 
-emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  %s 
-check-prefix=CHECK1
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s  -check-prefix=CHECK1
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple 
i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | 
FileCheck -allow-deprecated-dag-overlap  %s  -check-prefix=CHECK1
-
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s -check-prefix=CHECK2
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s 
-emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  %s 
-check-prefix=CHECK2
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s  -check-prefix=CHECK2
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple 
i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | 
FileCheck -allow-deprecated-dag-overlap  %s  -check-prefix=CHECK2
-
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s -check-prefix=CHECK3
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s 
-emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  %s 
-check-prefix=CHECK3
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s  -check-prefix=CHECK3
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple 
i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | 
FileCheck -allow-deprecated-dag-overlap  %s  -check-prefix=CHECK3
-
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s -check-prefix=CHECK4
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s 
-emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  %s 
-check-prefix=CHECK4
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s  -check-prefix=CHECK4
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ 
-std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple 
i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | 
FileCheck -allow-deprecated-dag-overlap  %s  -check-prefix=CHECK4
-
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu 
-x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck 
-allow-deprecated-dag-overlap  %s -check-prefix=CHECK5
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ 
-std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RU

[clang] [clang-format][NFC] Delete TT_LambdaArrow (PR #70519)

2023-10-28 Thread Björn Schäpers via cfe-commits

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


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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-28 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 created 
https://github.com/llvm/llvm-project/pull/70567

This PR is proposing a fix for 
https://github.com/llvm/llvm-project/issues/65971.

Previously, given a coroutine like this
```
task foo(int a) {
  co_return;
}
```
Parameter `a` is never used. However, because C++ coroutines move constructs 
the variable to a heap allocated coroutine activation frame, we considered all 
parameters referenced. When diagnosing unused parameters, we cannot distinguish 
if the variable reference was due to coroutine parameter moves. 


Compiler Explorer shows that GCC warns against this case correctly, but clang 
does not: https://godbolt.org/z/Wo7dfqeaf

This change adds a flag `LastReferenceInCoroutineParamMoves` to `Decl`s. All 
other references to the `Decl` will clear the flag, so we are still able to 
tell if the reference is from the user defined coroutine body. 

>From ba6c43cc63e9ae3c8d174406ced4df839af3e0a7 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Fri, 27 Oct 2023 16:37:40 -0700
Subject: [PATCH] [Clang] Coroutines: warn against unused parameters in C++
 coroutines with -Wunused-parameters

---
 clang/include/clang/AST/DeclBase.h| 18 +++-
 clang/lib/Sema/SemaCoroutine.cpp  |  6 
 clang/lib/Sema/SemaDecl.cpp   |  5 +++-
 .../warn-unused-parameters-coroutine.cpp  | 28 +++
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 978e4255e877ec2..dc78ee37d16bea2 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -306,6 +306,11 @@ class alignas(8) Decl {
   /// are regarded as "referenced" but not "used".
   unsigned Referenced : 1;
 
+  /// Whether the last reference to this declaration happened in Coroutine
+  /// Parameter moves. Otherwise the reference caused by such moves would
+  /// prevent a warning against unused parameters in all coroutines.
+  unsigned LastReferenceInCoroutineParamMoves : 1;
+
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
   /// definition.
@@ -609,11 +614,22 @@ class alignas(8) Decl {
   /// Whether any declaration of this entity was referenced.
   bool isReferenced() const;
 
+  bool isLastReferenceInCoroutineParamMoves() const {
+return LastReferenceInCoroutineParamMoves;
+  }
+
+  void setLastReferenceInCoroutineParamMoves(bool V = true) {
+LastReferenceInCoroutineParamMoves = true;
+  }
+
   /// Whether this declaration was referenced. This should not be relied
   /// upon for anything other than debugging.
   bool isThisDeclarationReferenced() const { return Referenced; }
 
-  void setReferenced(bool R = true) { Referenced = R; }
+  void setReferenced(bool R = true) {
+Referenced = R;
+LastReferenceInCoroutineParamMoves = false;
+  }
 
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index cfaa93fbea4dd37..2936c39941e2922 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1964,9 +1964,15 @@ bool Sema::buildCoroutineParameterMoves(SourceLocation 
Loc) {
 if (PD->getType()->isDependentType())
   continue;
 
+bool PDRefBefore = PD->isReferenced();
+
 ExprResult PDRefExpr =
 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
+
+if (!PDRefBefore)
+  PD->setLastReferenceInCoroutineParamMoves();
+
 if (PDRefExpr.isInvalid())
   return false;
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c4979b51e68f5e2..06487d3595de557 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15089,7 +15089,10 @@ void 
Sema::DiagnoseUnusedParameters(ArrayRef Parameters) {
 return;
 
   for (const ParmVarDecl *Parameter : Parameters) {
-if (!Parameter->isReferenced() && Parameter->getDeclName() &&
+if (Parameter->isReferenced() && 
!Parameter->isLastReferenceInCoroutineParamMoves())
+  continue;
+
+if (Parameter->getDeclName() &&
 !Parameter->hasAttr() &&
 !Parameter->getIdentifier()->isPlaceholder()) {
   Diag(Parameter->getLocation(), diag::warn_unused_parameter)
diff --git a/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp 
b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
new file mode 100644
index 000..0fd26ea4a21be79
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-parameter -verify -std=c++20 %s
+
+#include "Inputs/std-coroutine.h"
+
+struct 

[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-28 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff b1554fe080e8b074a30f2a4cb88666bdb7b1ce9e 
ba6c43cc63e9ae3c8d174406ced4df839af3e0a7 -- 
clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp 
clang/include/clang/AST/DeclBase.h clang/lib/Sema/SemaCoroutine.cpp 
clang/lib/Sema/SemaDecl.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 06487d359..948fdd18d 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15089,11 +15089,11 @@ void 
Sema::DiagnoseUnusedParameters(ArrayRef Parameters) {
 return;
 
   for (const ParmVarDecl *Parameter : Parameters) {
-if (Parameter->isReferenced() && 
!Parameter->isLastReferenceInCoroutineParamMoves())
+if (Parameter->isReferenced() &&
+!Parameter->isLastReferenceInCoroutineParamMoves())
   continue;
 
-if (Parameter->getDeclName() &&
-!Parameter->hasAttr() &&
+if (Parameter->getDeclName() && !Parameter->hasAttr() &&
 !Parameter->getIdentifier()->isPlaceholder()) {
   Diag(Parameter->getLocation(), diag::warn_unused_parameter)
 << Parameter->getDeclName();

``




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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-28 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 updated 
https://github.com/llvm/llvm-project/pull/70567

>From ba6c43cc63e9ae3c8d174406ced4df839af3e0a7 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Fri, 27 Oct 2023 16:37:40 -0700
Subject: [PATCH 1/2] [Clang] Coroutines: warn against unused parameters in C++
 coroutines with -Wunused-parameters

---
 clang/include/clang/AST/DeclBase.h| 18 +++-
 clang/lib/Sema/SemaCoroutine.cpp  |  6 
 clang/lib/Sema/SemaDecl.cpp   |  5 +++-
 .../warn-unused-parameters-coroutine.cpp  | 28 +++
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 978e4255e877ec2..dc78ee37d16bea2 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -306,6 +306,11 @@ class alignas(8) Decl {
   /// are regarded as "referenced" but not "used".
   unsigned Referenced : 1;
 
+  /// Whether the last reference to this declaration happened in Coroutine
+  /// Parameter moves. Otherwise the reference caused by such moves would
+  /// prevent a warning against unused parameters in all coroutines.
+  unsigned LastReferenceInCoroutineParamMoves : 1;
+
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
   /// definition.
@@ -609,11 +614,22 @@ class alignas(8) Decl {
   /// Whether any declaration of this entity was referenced.
   bool isReferenced() const;
 
+  bool isLastReferenceInCoroutineParamMoves() const {
+return LastReferenceInCoroutineParamMoves;
+  }
+
+  void setLastReferenceInCoroutineParamMoves(bool V = true) {
+LastReferenceInCoroutineParamMoves = true;
+  }
+
   /// Whether this declaration was referenced. This should not be relied
   /// upon for anything other than debugging.
   bool isThisDeclarationReferenced() const { return Referenced; }
 
-  void setReferenced(bool R = true) { Referenced = R; }
+  void setReferenced(bool R = true) {
+Referenced = R;
+LastReferenceInCoroutineParamMoves = false;
+  }
 
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index cfaa93fbea4dd37..2936c39941e2922 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1964,9 +1964,15 @@ bool Sema::buildCoroutineParameterMoves(SourceLocation 
Loc) {
 if (PD->getType()->isDependentType())
   continue;
 
+bool PDRefBefore = PD->isReferenced();
+
 ExprResult PDRefExpr =
 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
+
+if (!PDRefBefore)
+  PD->setLastReferenceInCoroutineParamMoves();
+
 if (PDRefExpr.isInvalid())
   return false;
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c4979b51e68f5e2..06487d3595de557 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15089,7 +15089,10 @@ void 
Sema::DiagnoseUnusedParameters(ArrayRef Parameters) {
 return;
 
   for (const ParmVarDecl *Parameter : Parameters) {
-if (!Parameter->isReferenced() && Parameter->getDeclName() &&
+if (Parameter->isReferenced() && 
!Parameter->isLastReferenceInCoroutineParamMoves())
+  continue;
+
+if (Parameter->getDeclName() &&
 !Parameter->hasAttr() &&
 !Parameter->getIdentifier()->isPlaceholder()) {
   Diag(Parameter->getLocation(), diag::warn_unused_parameter)
diff --git a/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp 
b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
new file mode 100644
index 000..0fd26ea4a21be79
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-parameter -verify -std=c++20 %s
+
+#include "Inputs/std-coroutine.h"
+
+struct awaitable {
+  bool await_ready() noexcept;
+  void await_resume() noexcept;
+  void await_suspend(std::coroutine_handle<>) noexcept;
+};
+
+struct task : awaitable {
+  struct promise_type {
+task get_return_object() noexcept;
+awaitable initial_suspend() noexcept;
+awaitable final_suspend() noexcept;
+void unhandled_exception() noexcept;
+void return_void() noexcept;
+  };
+};
+
+task foo(int a) { // expected-warning{{unused parameter 'a'}}
+  co_return;
+}
+
+task bar(int a, int b) { // expected-warning{{unused parameter 'b'}}
+  a = a + 1;
+  co_return;
+}

>From fe7109f18286b8ba7e3e44f1fb31fc60e1ad8422 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Sat, 28 Oct 2023 12:42:01 -0700
Subject: [PATCH 2/2] fix small bug: setLastReferenceInCoroutineParamMoves
 should respect pa

[PATCH] D150083: [clang-format] ObjCPropertyAttributeOrder to sort ObjC property attributes

2023-10-28 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D150083#4655479 , @jaredgrubb 
wrote:

> Should I open a GitHub issue for this patch?

That'd be great.


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

https://reviews.llvm.org/D150083

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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-28 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 updated 
https://github.com/llvm/llvm-project/pull/70567

>From ba6c43cc63e9ae3c8d174406ced4df839af3e0a7 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Fri, 27 Oct 2023 16:37:40 -0700
Subject: [PATCH 1/3] [Clang] Coroutines: warn against unused parameters in C++
 coroutines with -Wunused-parameters

---
 clang/include/clang/AST/DeclBase.h| 18 +++-
 clang/lib/Sema/SemaCoroutine.cpp  |  6 
 clang/lib/Sema/SemaDecl.cpp   |  5 +++-
 .../warn-unused-parameters-coroutine.cpp  | 28 +++
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 978e4255e877ec2..dc78ee37d16bea2 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -306,6 +306,11 @@ class alignas(8) Decl {
   /// are regarded as "referenced" but not "used".
   unsigned Referenced : 1;
 
+  /// Whether the last reference to this declaration happened in Coroutine
+  /// Parameter moves. Otherwise the reference caused by such moves would
+  /// prevent a warning against unused parameters in all coroutines.
+  unsigned LastReferenceInCoroutineParamMoves : 1;
+
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
   /// definition.
@@ -609,11 +614,22 @@ class alignas(8) Decl {
   /// Whether any declaration of this entity was referenced.
   bool isReferenced() const;
 
+  bool isLastReferenceInCoroutineParamMoves() const {
+return LastReferenceInCoroutineParamMoves;
+  }
+
+  void setLastReferenceInCoroutineParamMoves(bool V = true) {
+LastReferenceInCoroutineParamMoves = true;
+  }
+
   /// Whether this declaration was referenced. This should not be relied
   /// upon for anything other than debugging.
   bool isThisDeclarationReferenced() const { return Referenced; }
 
-  void setReferenced(bool R = true) { Referenced = R; }
+  void setReferenced(bool R = true) {
+Referenced = R;
+LastReferenceInCoroutineParamMoves = false;
+  }
 
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index cfaa93fbea4dd37..2936c39941e2922 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1964,9 +1964,15 @@ bool Sema::buildCoroutineParameterMoves(SourceLocation 
Loc) {
 if (PD->getType()->isDependentType())
   continue;
 
+bool PDRefBefore = PD->isReferenced();
+
 ExprResult PDRefExpr =
 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
+
+if (!PDRefBefore)
+  PD->setLastReferenceInCoroutineParamMoves();
+
 if (PDRefExpr.isInvalid())
   return false;
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c4979b51e68f5e2..06487d3595de557 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15089,7 +15089,10 @@ void 
Sema::DiagnoseUnusedParameters(ArrayRef Parameters) {
 return;
 
   for (const ParmVarDecl *Parameter : Parameters) {
-if (!Parameter->isReferenced() && Parameter->getDeclName() &&
+if (Parameter->isReferenced() && 
!Parameter->isLastReferenceInCoroutineParamMoves())
+  continue;
+
+if (Parameter->getDeclName() &&
 !Parameter->hasAttr() &&
 !Parameter->getIdentifier()->isPlaceholder()) {
   Diag(Parameter->getLocation(), diag::warn_unused_parameter)
diff --git a/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp 
b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
new file mode 100644
index 000..0fd26ea4a21be79
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-parameter -verify -std=c++20 %s
+
+#include "Inputs/std-coroutine.h"
+
+struct awaitable {
+  bool await_ready() noexcept;
+  void await_resume() noexcept;
+  void await_suspend(std::coroutine_handle<>) noexcept;
+};
+
+struct task : awaitable {
+  struct promise_type {
+task get_return_object() noexcept;
+awaitable initial_suspend() noexcept;
+awaitable final_suspend() noexcept;
+void unhandled_exception() noexcept;
+void return_void() noexcept;
+  };
+};
+
+task foo(int a) { // expected-warning{{unused parameter 'a'}}
+  co_return;
+}
+
+task bar(int a, int b) { // expected-warning{{unused parameter 'b'}}
+  a = a + 1;
+  co_return;
+}

>From fe7109f18286b8ba7e3e44f1fb31fc60e1ad8422 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Sat, 28 Oct 2023 12:42:01 -0700
Subject: [PATCH 2/3] fix small bug: setLastReferenceInCoroutineParamMoves
 should respect pa

[clang] e00d32a - [clang-format][NFC] Delete TT_LambdaArrow (#70519)

2023-10-28 Thread via cfe-commits

Author: Owen Pan
Date: 2023-10-28T12:48:00-07:00
New Revision: e00d32afb9d33a1eca48e2b041c9688436706c5b

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

LOG: [clang-format][NFC] Delete TT_LambdaArrow (#70519)

It's one type of TT_TrailingReturnArrow.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 3b28f84fd8417d3..3a829cdedb77fc7 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -813,8 +813,10 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
 CurrentState.ContainsUnwrappedBuilder = true;
   }
 
-  if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
+  if (Current.is(TT_TrailingReturnArrow) &&
+  Style.Language == FormatStyle::LK_Java) {
 CurrentState.NoLineBreak = true;
+  }
   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
   (Previous.MatchingParen &&
(Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
@@ -969,7 +971,7 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState 
&State,
   //
   // is common and should be formatted like a free-standing function. The same
   // goes for wrapping before the lambda return type arrow.
-  if (Current.isNot(TT_LambdaArrow) &&
+  if (Current.isNot(TT_TrailingReturnArrow) &&
   (!Style.isJavaScript() || Current.NestingLevel != 0 ||
!PreviousNonComment || PreviousNonComment->isNot(tok::equal) ||
!Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
@@ -1548,7 +1550,7 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
   }
   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
 CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
-  if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
+  if (Current.isOneOf(TT_LambdaLSquare, TT_TrailingReturnArrow))
 CurrentState.LastSpace = State.Column;
   if (Current.is(TT_RequiresExpression) &&
   Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index acd24f836199da1..87f6a76ec5bfd39 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -100,7 +100,6 @@ namespace format {
   TYPE(JsTypeColon)
\
   TYPE(JsTypeOperator) 
\
   TYPE(JsTypeOptionalQuestion) 
\
-  TYPE(LambdaArrow)
\
   TYPE(LambdaLBrace)   
\
   TYPE(LambdaLSquare)  
\
   TYPE(LeadingJavaAnnotation)  
\
@@ -690,7 +689,7 @@ struct FormatToken {
   bool isMemberAccess() const {
 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
!isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
-TT_LambdaArrow, TT_LeadingJavaAnnotation);
+TT_LeadingJavaAnnotation);
   }
 
   bool isUnaryOperator() const {

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e0ea8bcdb07a32b..9ec8b93e39fd23a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -766,7 +766,8 @@ class AnnotatingParser {
 }
 // An arrow after an ObjC method expression is not a lambda arrow.
 if (CurrentToken->getType() == TT_ObjCMethodExpr &&
-CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) {
+CurrentToken->Next &&
+CurrentToken->Next->is(TT_TrailingReturnArrow)) {
   CurrentToken->Next->overwriteFixedType(TT_Unknown);
 }
 Left->MatchingParen = CurrentToken;
@@ -1409,10 +1410,8 @@ class AnnotatingParser {
   }
   break;
 case tok::arrow:
-  if (Tok->isNot(TT_LambdaArrow) && Tok->Previous &&
-  Tok->Previous->is(tok::kw_noexcept)) {
+  if (Tok->Previous && Tok->Previous->is(tok::kw_noexcept))
 Tok->setType(TT_TrailingReturnArrow);
-  }
   break;
 default:
   break;
@@ -1689,11 +1688,11 @@ class AnnotatingParser {
 TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
 TT_ForEach

[clang] [clang-format][NFC] Delete TT_LambdaArrow (PR #70519)

2023-10-28 Thread Owen Pan via cfe-commits

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits

https://github.com/serge-sans-paille updated 
https://github.com/llvm/llvm-project/pull/70543

>From 7bbcabd82edc1736cc22243e109dc0858036c6ac Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Fri, 27 Oct 2023 22:48:08 +0200
Subject: [PATCH] [clang] Change GetCharAndSizeSlow interface to by-value style

Instead of passing the Size by reference, assuming it is initialized,
return it alongside the expected char result as a POD.

This makes the interface less error prone: previous interface expected
the Size reference to be initialized, and it was often forgotten,
leading to uninitialized variable usage. This patch fixes the issue.

This also generates faster code, as the returned POD (a char and an
unsigned) fits in 64 bits. The speedup according to compile time tracker
reach -O.7%, with a good number of -0.4%. Details are available on


https://llvm-compile-time-tracker.com/compare.php?from=3fe63f81fcb999681daa11b2890c82fda3aaeef5&to=fc76a9202f737472ecad4d6e0b0bf87a013866f3&stat=instructions:u

And icing on the cake, on my setup it also shaves 2kB out of
libclang-cpp :-)
---
 clang/include/clang/Lex/Lexer.h   | 35 
 clang/lib/Lex/DependencyDirectivesScanner.cpp |  7 +-
 clang/lib/Lex/Lexer.cpp   | 79 +++
 3 files changed, 65 insertions(+), 56 deletions(-)

diff --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h
index ac0ef14c591bdd7..899e665e7454652 100644
--- a/clang/include/clang/Lex/Lexer.h
+++ b/clang/include/clang/Lex/Lexer.h
@@ -575,19 +575,23 @@ class Lexer : public PreprocessorLexer {
   /// sequence.
   static bool isNewLineEscaped(const char *BufferStart, const char *Str);
 
+  /// Represents a char and the number of bytes parsed to produce it.
+  struct SizedChar {
+char Char;
+unsigned Size;
+  };
+
   /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
   /// emit a warning.
-  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
-  const LangOptions &LangOpts) {
+  static inline SizedChar getCharAndSizeNoWarn(const char *Ptr,
+   const LangOptions &LangOpts) {
 // If this is not a trigraph and not a UCN or escaped newline, return
 // quickly.
 if (isObviouslySimpleCharacter(Ptr[0])) {
-  Size = 1;
-  return *Ptr;
+  return {*Ptr, 1u};
 }
 
-Size = 0;
-return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
+return getCharAndSizeSlowNoWarn(Ptr, LangOpts);
   }
 
   /// Returns the leading whitespace for line that corresponds to the given
@@ -665,8 +669,7 @@ class Lexer : public PreprocessorLexer {
 // quickly.
 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
 
-unsigned Size = 0;
-char C = getCharAndSizeSlow(Ptr, Size, &Tok);
+auto [C, Size] = getCharAndSizeSlow(Ptr, &Tok);
 Ptr += Size;
 return C;
   }
@@ -682,9 +685,7 @@ class Lexer : public PreprocessorLexer {
 
 // Otherwise, re-lex the character with a current token, allowing
 // diagnostics to be emitted and flags to be set.
-Size = 0;
-getCharAndSizeSlow(Ptr, Size, &Tok);
-return Ptr+Size;
+return Ptr + getCharAndSizeSlow(Ptr, &Tok).Size;
   }
 
   /// getCharAndSize - Peek a single 'character' from the specified buffer,
@@ -699,14 +700,14 @@ class Lexer : public PreprocessorLexer {
   return *Ptr;
 }
 
-Size = 0;
-return getCharAndSizeSlow(Ptr, Size);
+auto CharAndSize = getCharAndSizeSlow(Ptr);
+Size = CharAndSize.Size;
+return CharAndSize.Char;
   }
 
   /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
   /// method.
-  char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
-  Token *Tok = nullptr);
+  SizedChar getCharAndSizeSlow(const char *Ptr, Token *Tok = nullptr);
 
   /// getEscapedNewLineSize - Return the size of the specified escaped newline,
   /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
@@ -720,8 +721,8 @@ class Lexer : public PreprocessorLexer {
 
   /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
   /// diagnostic.
-  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
-   const LangOptions &LangOpts);
+  static SizedChar getCharAndSizeSlowNoWarn(const char *Ptr,
+const LangOptions &LangOpts);
 
   
//======//
   // Other lexer functions.
diff --git a/clang/lib/Lex/DependencyDirectivesScanner.cpp 
b/clang/lib/Lex/DependencyDirectivesScanner.cpp
index 2bd2c5f8388c0dd..42b89f98a24f3e1 100644
--- a/clang/lib/Lex/DependencyDirectivesScanner.cpp
+++ b/clang/lib/Lex/DependencyDirectivesScanner.cpp
@@ -565,10 +565,9 @@ Scanner::cleanStringIfNeeded(const 
dependency_directives_scan::Token &Tok) {
   cons

[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits

serge-sans-paille wrote:

@cor3ntin yep, looks better with a small struct, updated pushed

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


[clang] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70551)

2023-10-28 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/70551

>From e02939572877cdc839894454a6fab36ab143d924 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:33:07 +0100
Subject: [PATCH 1/4] [clang][DebugInfo][NFC] Add createConstantValueExpression
 helper

This patch factors out the code to create a DIExpression from
an APValue into a separate helper function.

This will be useful in a follow-up patch where we re-use this
logic elsewhere.
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 44 ++-
 clang/lib/CodeGen/CGDebugInfo.h   |  5 
 2 files changed, 31 insertions(+), 18 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index c430713b0d77d79..a109f140cca80c8 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5574,25 +5574,8 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue &Init) {
   auto &GV = DeclCache[VD];
   if (GV)
 return;
-  llvm::DIExpression *InitExpr = nullptr;
-  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
-// FIXME: Add a representation for integer constants wider than 64 bits.
-if (Init.isInt()) {
-  const llvm::APSInt &InitInt = Init.getInt();
-  std::optional InitIntOpt;
-  if (InitInt.isUnsigned())
-InitIntOpt = InitInt.tryZExtValue();
-  else if (auto tmp = InitInt.trySExtValue(); tmp.has_value())
-// Transform a signed optional to unsigned optional. When cpp 23 comes,
-// use std::optional::transform
-InitIntOpt = (uint64_t)tmp.value();
-  if (InitIntOpt)
-InitExpr = DBuilder.createConstantValueExpression(InitIntOpt.value());
-} else if (Init.isFloat())
-  InitExpr = DBuilder.createConstantValueExpression(
-  Init.getFloat().bitcastToAPInt().getZExtValue());
-  }
 
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
   llvm::MDTuple *TemplateParameters = nullptr;
 
   if (isa(VD))
@@ -5929,3 +5912,28 @@ llvm::DINode::DIFlags 
CGDebugInfo::getCallSiteRelatedAttrs() const {
 
   return llvm::DINode::FlagAllCallsDescribed;
 }
+
+llvm::DIExpression *
+CGDebugInfo::createConstantValueExpression(clang::ValueDecl const *VD,
+   const APValue &Val) {
+  llvm::DIExpression *ValExpr = nullptr;
+  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
+// FIXME: Add a representation for integer constants wider than 64 bits.
+if (Val.isInt()) {
+  const llvm::APSInt &ValInt = Val.getInt();
+  std::optional ValIntOpt;
+  if (ValInt.isUnsigned())
+ValIntOpt = ValInt.tryZExtValue();
+  else if (auto tmp = ValInt.trySExtValue(); tmp.has_value())
+// Transform a signed optional to unsigned optional. When cpp 23 comes,
+// use std::optional::transform
+ValIntOpt = (uint64_t)tmp.value();
+  if (ValIntOpt)
+ValExpr = DBuilder.createConstantValueExpression(ValIntOpt.value());
+} else if (Val.isFloat())
+  ValExpr = DBuilder.createConstantValueExpression(
+  Val.getFloat().bitcastToAPInt().getZExtValue());
+  }
+
+  return ValExpr;
+}
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index ae12485850ca775..7b60e94555d0608 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -800,6 +800,11 @@ class CGDebugInfo {
llvm::MDTuple *&TemplateParameters,
llvm::DIScope *&VDContext);
 
+  /// Create a DIExpression representing the constant corresponding
+  /// to the specified 'Val'. Returns nullptr on failure.
+  llvm::DIExpression *createConstantValueExpression(const clang::ValueDecl *VD,
+const APValue &Val);
+
   /// Allocate a copy of \p A using the DebugInfoNames allocator
   /// and return a reference to it. If multiple arguments are given the strings
   /// are concatenated.

>From 119276638095f48d8d2a5dd8fc7e042059e66378 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:19:47 +0100
Subject: [PATCH 2/4] [clang][DebugInfo] Emit global variable definitions for
 static data members with constant initializers
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

When an LLDB user asks for the value of a static data member, LLDB starts by
searching the Names accelerator table for the corresponding variable definition
DIE. For static data members with out-of-class definitions that works fine,
because those get represented as global variables with a location and making 
them
eligible to be added to the Names table. However, in-class definitions won’t get
indexed because we usually don't emit global variables for them. So in DWARF
we end up with a single `DW_TAG_member` that usually holds the constant 
initializer.
But we don't get a corresponding CU-level `DW_TAG_

[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits


@@ -1964,11 +1969,14 @@ bool Lexer::LexIdentifierContinue(Token &Result, const 
char *CurPtr) {
 /// isHexaLiteral - Return true if Start points to a hex constant.
 /// in microsoft mode (where this is supposed to be several different tokens).
 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
-  unsigned Size;
-  char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
+  auto CharAndSize1 = Lexer::getCharAndSizeNoWarn(Start, LangOpts);
+  char C1 = CharAndSize1.Char;
   if (C1 != '0')
 return false;
-  char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
+
+  auto CharAndSize2 =

cor3ntin wrote:

You can reuse `CharAndSize` here

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits


@@ -2012,15 +2020,15 @@ bool Lexer::LexNumericConstant(Token &Result, const 
char *CurPtr) {
 
   // If we have a digit separator, continue.
   if (C == '\'' && (LangOpts.CPlusPlus14 || LangOpts.C23)) {
-unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, LangOpts);
+auto NextCharAndSize = getCharAndSizeNoWarn(CurPtr + Size, LangOpts);

cor3ntin wrote:

Structured binding here?

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits


@@ -2085,8 +2093,9 @@ const char *Lexer::LexUDSuffix(Token &Result, const char 
*CurPtr,
   unsigned Consumed = Size;
   unsigned Chars = 1;
   while (true) {
-unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, 
LangOpts);
+auto NextCharAndSize =

cor3ntin wrote:

Structured binding here?

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


[clang] Perf/lexer faster slow get char and size (PR #70543)

2023-10-28 Thread via cfe-commits


@@ -565,10 +565,9 @@ Scanner::cleanStringIfNeeded(const 
dependency_directives_scan::Token &Tok) {
   const char *BufPtr = Input.begin() + Tok.Offset;
   const char *AfterIdent = Input.begin() + Tok.getEnd();
   while (BufPtr < AfterIdent) {
-unsigned Size;
-Spelling[SpellingLength++] =
-Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
-BufPtr += Size;
+auto CharAndSize = Lexer::getCharAndSizeNoWarn(BufPtr, LangOpts);

cor3ntin wrote:

Structured binding here?

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


[clang] [OpenMP] Unify the min/max thread/teams pathways (PR #70273)

2023-10-28 Thread Shilei Tian via cfe-commits

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

LG

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


[clang-tools-extra] [MLIR] Update convert-gpu-to-spirv pass to prepare using GPU compilat… (PR #69941)

2023-10-28 Thread Lei Zhang via cfe-commits

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

Nice. Just one final request.

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


[clang-tools-extra] [MLIR] Update convert-gpu-to-spirv pass to prepare using GPU compilat… (PR #69941)

2023-10-28 Thread Lei Zhang via cfe-commits

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


[clang] [MLIR] Update convert-gpu-to-spirv pass to prepare using GPU compilat… (PR #69941)

2023-10-28 Thread Lei Zhang via cfe-commits

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

Nice. Just one final request.

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


[clang] [MLIR] Update convert-gpu-to-spirv pass to prepare using GPU compilat… (PR #69941)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -54,22 +55,52 @@ void GPUToSPIRVPass::runOnOperation() {
 
   SmallVector gpuModules;
   OpBuilder builder(context);
+
+  auto targetEnvSupportsKernelCapability = [](gpu::GPUModuleOp moduleOp) {
+Operation *gpuModule = moduleOp.getOperation();
+auto targetAttr = spirv::lookupTargetEnvOrDefault(gpuModule);
+spirv::TargetEnv targetEnv(targetAttr);
+return targetEnv.allows(spirv::Capability::Kernel);
+  };
+
   module.walk([&](gpu::GPUModuleOp moduleOp) {
 // Clone each GPU kernel module for conversion, given that the GPU
 // launch op still needs the original GPU kernel module.
-builder.setInsertionPoint(moduleOp.getOperation());
+// For Vulkan Shader capabilities, we insert the newly converted SPIR-V
+// module right after the original GPU module, as that's the expectation of
+// the in-tree Vulkan runner.
+// For OpenCL Kernel capabilities, we insert the newly converted SPIR-V
+// module inside the original GPU module, as that's the expectaion of the
+// normal GPU compilation pipeline.
+if (targetEnvSupportsKernelCapability(moduleOp)) {
+  builder.setInsertionPoint(moduleOp.getBody(),
+moduleOp.getBody()->begin());
+} else {
+  builder.setInsertionPoint(moduleOp.getOperation());
+}
 gpuModules.push_back(builder.clone(*moduleOp.getOperation()));
   });
 
   // Run conversion for each module independently as they can have different
   // TargetEnv attributes.
   for (Operation *gpuModule : gpuModules) {
+spirv::TargetEnvAttr targetAttr =
+spirv::lookupTargetEnvOrDefault(gpuModule);
+
 // Map MemRef memory space to SPIR-V storage class first if requested.
 if (mapMemorySpace) {
+  spirv::TargetEnv targetEnv(targetAttr);
+  FailureOr memoryModel =
+  spirv::getMemoryModel(targetEnv);
+  if (failed(memoryModel))
+return signalPassFailure();
+
   std::unique_ptr target =
   spirv::getMemorySpaceToStorageClassTarget(*context);
   spirv::MemorySpaceToStorageClassMap memorySpaceMap =
-  spirv::mapMemorySpaceToVulkanStorageClass;
+  (memoryModel == spirv::MemoryModel::OpenCL)

antiagainst wrote:

Here we can also use the above `targetEnvSupportsKernelCapability` no? 
Something like:

```c++
spirv::MemorySpaceToStorageClassMap memorySpaceMap =
  targetEnvSupportsKernelCapability(gpuModule) ? ...
```

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


[clang-tools-extra] Bfi precision (PR #66285)

2023-10-28 Thread David Li via cfe-commits

david-xl wrote:

> And digging even deeper:
> 
> * FWIW I noticed that I only used `clang -c` as benchmark previously, should 
> have used `clang -c -O3` resulting in this:
> 
> ```
> Old-BFI:  insn: 37,821,687,947  (baseline)
> New-BFI:  insn: 38,133,312,923  +0.82%
> Old-BFI, no-cold: insn: 37,423,365,184  -1.05%
> New-BFI, no-cold: insn: 37,438,736,713  -1.01%
> ```
> 
> * The problematic part of the code that is inlined/not-inlined is actually 
> marked as `LLVM_UNLIKELY` here: 
> https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/DenseMap.h#L607
>   and intuitively one would think that it is probably best to not inline 
> `grow`  (as will happen with the new BFI version)
> * In practice not-inlining `grow` mostly ends up being worse because of 
> knock-on effects as far as I can tell. These are the inlining decisions I 
> noticed for the most prominent situation:
> 
> ```
> - `grow` inlined (Old-BFI):
>  - Instruction::getMetadataImpl
>  -> Value::getMetadata   not inlined
>  -> DenseMap::operator[] inlined
>  -> DenseMap::FindAndConstruct   inlined
>  -> DenseMap::InsertIntoBucket   not inlined, size
>likely too big with `grow` inlined here
>  -> DenseMap::grow   inlined
> - `grow` inlined (New-BFI):
>  - Instruction::getMadataImpl
>  -> Value::getMetadata  inlined
>  -> DenseMap::operator[]inlined
>  -> DenseMap::FindAndConstruct  not inlined, size
>  -> DenseMap::InsertIntoBucket  inlined
>  -> DenseMap::grow  not inlined
> ```
> 
> Though if you look into this then I would state that the code got better for 
> the wrong reasons! Not inlining `grow` is a sensible decision in this context 
> and the `LLVM_UNLIKELY` annotation makes sense (I actually added some 
> counters and see the unlikely branch taken somewhere between 1% and 10% of 
> the cases depending on inputs, so seems sensible).
> 
> Unfortunately the particular code here `getMetadataImpl` never inserts new 
> things into the map, but unfortunately `operator[]` gives you that behavior 
> by default so nobody noticed. So not inlining `InsertIntoBucket` happened to 
> be a great decision previously that the compiler did by accident without 
> having good data to support this. Now with better but still insufficient data 
> (as this is PGO) we happen to end up inlining `InsertIntoBucket` wasting code 
> size leading to worse inlining decisions further up the stack...
> 
> Long story short: This ended up another of the many stories where the 
> compiler cannot make the right inlining decisions without having actual 
> runtime data. It tends to make a better decision based on the data that ends 
> up being wrong anyway here. I'm gonna leave things as is and rather put up 
> some improvements to LLVM code instead!

Good analysis.

Your plan sounds good but lowering the cold threshold is probably a good thing 
to do with the new BFI. The FindAndConstruct method in DenseMap can probably be 
annotated with buitin_expect to indicate the insertion is a unlikely path.

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


[clang] Bfi precision (PR #66285)

2023-10-28 Thread David Li via cfe-commits

david-xl wrote:

> And digging even deeper:
> 
> * FWIW I noticed that I only used `clang -c` as benchmark previously, should 
> have used `clang -c -O3` resulting in this:
> 
> ```
> Old-BFI:  insn: 37,821,687,947  (baseline)
> New-BFI:  insn: 38,133,312,923  +0.82%
> Old-BFI, no-cold: insn: 37,423,365,184  -1.05%
> New-BFI, no-cold: insn: 37,438,736,713  -1.01%
> ```
> 
> * The problematic part of the code that is inlined/not-inlined is actually 
> marked as `LLVM_UNLIKELY` here: 
> https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/DenseMap.h#L607
>   and intuitively one would think that it is probably best to not inline 
> `grow`  (as will happen with the new BFI version)
> * In practice not-inlining `grow` mostly ends up being worse because of 
> knock-on effects as far as I can tell. These are the inlining decisions I 
> noticed for the most prominent situation:
> 
> ```
> - `grow` inlined (Old-BFI):
>  - Instruction::getMetadataImpl
>  -> Value::getMetadata   not inlined
>  -> DenseMap::operator[] inlined
>  -> DenseMap::FindAndConstruct   inlined
>  -> DenseMap::InsertIntoBucket   not inlined, size
>likely too big with `grow` inlined here
>  -> DenseMap::grow   inlined
> - `grow` inlined (New-BFI):
>  - Instruction::getMadataImpl
>  -> Value::getMetadata  inlined
>  -> DenseMap::operator[]inlined
>  -> DenseMap::FindAndConstruct  not inlined, size
>  -> DenseMap::InsertIntoBucket  inlined
>  -> DenseMap::grow  not inlined
> ```
> 
> Though if you look into this then I would state that the code got better for 
> the wrong reasons! Not inlining `grow` is a sensible decision in this context 
> and the `LLVM_UNLIKELY` annotation makes sense (I actually added some 
> counters and see the unlikely branch taken somewhere between 1% and 10% of 
> the cases depending on inputs, so seems sensible).
> 
> Unfortunately the particular code here `getMetadataImpl` never inserts new 
> things into the map, but unfortunately `operator[]` gives you that behavior 
> by default so nobody noticed. So not inlining `InsertIntoBucket` happened to 
> be a great decision previously that the compiler did by accident without 
> having good data to support this. Now with better but still insufficient data 
> (as this is PGO) we happen to end up inlining `InsertIntoBucket` wasting code 
> size leading to worse inlining decisions further up the stack...
> 
> Long story short: This ended up another of the many stories where the 
> compiler cannot make the right inlining decisions without having actual 
> runtime data. It tends to make a better decision based on the data that ends 
> up being wrong anyway here. I'm gonna leave things as is and rather put up 
> some improvements to LLVM code instead!

Good analysis.

Your plan sounds good but lowering the cold threshold is probably a good thing 
to do with the new BFI. The FindAndConstruct method in DenseMap can probably be 
annotated with buitin_expect to indicate the insertion is a unlikely path.

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.
+class SPIRVTargetAttrImpl
+: public gpu::TargetAttrInterface::FallbackModel {
+public:
+  std::optional>
+  serializeToObject(Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const;
+
+  Attribute createObject(Attribute attribute,
+ const SmallVector &object,
+ const gpu::TargetOptions &options) const;
+};
+} // namespace
+
+// Register the SPIRV dialect, the SPIRV translation & the target interface.
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+DialectRegistry ®istry) {
+  registry.addExtension(+[](MLIRContext *ctx, spirv::SPIRVDialect *dialect) {
+spirv::SPIRVTargetAttr::attachInterface(*ctx);
+  });
+}
+
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+MLIRContext &context) {
+  DialectRegistry registry;
+  registerSPIRVTargetInterfaceExternalModels(registry);
+  context.appendDialectRegistry(registry);
+}
+
+// Reuse from existing serializer
+std::optional> SPIRVTargetAttrImpl::serializeToObject(
+Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const {
+  assert(module && "The module must be non null.");
+  if (!module)
+return std::nullopt;
+  if (!mlir::isa(module)) {
+module->emitError("Module must be a GPU module.");
+return std::nullopt;
+  }
+  auto gpuMod = dyn_cast(module);
+  auto spvMods = gpuMod.getOps();
+  // Empty spirv::ModuleOp

antiagainst wrote:

The comment here does not provide additional value; we should remove it or 
expand it to be more clear.

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -166,4 +166,35 @@ def SPIRV_ResourceLimitsAttr : 
SPIRV_Attr<"ResourceLimits", "resource_limits"> {
   let assemblyFormat = "`<` struct(params) `>`";
 }
 
+//===--===//
+// SPIRV target attribute.
+//===--===//
+
+def SPIRV_TargetAttr : SPIRV_Attr<"SPIRVTarget", "target"> {

antiagainst wrote:

This attribute is pretty much a duplication of `spirv::TargetEnvAttr` defined 
in `SPIRVAttributes.h`? We should avoid introducing such duplications and 
causing confusion. Any reaons we cannot use `spirv::TargetEnvAttr` directly? 

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//

antiagainst wrote:

Nit: again, please use SPIR-V in docs and comments. Please make sure everywhere 
follows the convention. :)

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,7 @@
+// RUN: mlir-opt %s --spirv-attach-target='module=spirv.* ver=v1.0 
caps=Kernel' | FileCheck %s
+
+module attributes {gpu.container_module} {
+// CHECK: @spirv_module_1 [#spirv.target, 
resource_limits = <>>]
+gpu.module @spirv_module_1 {

antiagainst wrote:

Can we add tests to show like

1) multiple GPU modules in the same container module?
2) different match regex with hits and misses?

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.

antiagainst wrote:

SPIR-V implementation of the `gpu:TargetAttrInterface`.

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -188,4 +188,46 @@ def GpuROCDLAttachTarget: Pass<"rocdl-attach-target", ""> {
   ];
 }
 
+def GpuSPIRVAttachTarget: Pass<"spirv-attach-target", ""> {
+  let summary = "Attaches an SPIRV target attribute to a GPU Module.";
+  let description = [{
+This pass searches for all GPU Modules in the immediate regions and 
attaches
+an SPIRV target if the module matches the name specified by the `module` 
argument.
+
+Example:
+```
+// File: in1.mlir:
+gpu.module @nvvm_module_1 {...}
+gpu.module @spirv_module_1 {...}
+// mlir-opt --spirv-attach-target="module=spirv.* ver=v1.0 caps=Kernel" 
in1.mlir
+gpu.module @nvvm_module_1 {...}
+gpu.module @spirv_module_1 [#spirv.target, resource_limits = <>>] {...}
+```
+  }];
+  let options = [
+Option<"moduleMatcher", "module", "std::string",
+   /*default=*/ [{""}],
+   "Regex used to identify the modules to attach the target to.">,
+Option<"spirvVersion", "ver", "std::string",
+   /*default=*/ "\"v1.0\"",
+   "SPIRV Addressing Model.">,
+ListOption<"spirvCapabilities", "caps", "std::string",
+   "List of required SPIRV Capabilities">,

antiagainst wrote:

s/required/supported/

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.
+class SPIRVTargetAttrImpl
+: public gpu::TargetAttrInterface::FallbackModel {
+public:
+  std::optional>
+  serializeToObject(Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const;
+
+  Attribute createObject(Attribute attribute,
+ const SmallVector &object,
+ const gpu::TargetOptions &options) const;
+};
+} // namespace
+
+// Register the SPIRV dialect, the SPIRV translation & the target interface.
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+DialectRegistry ®istry) {
+  registry.addExtension(+[](MLIRContext *ctx, spirv::SPIRVDialect *dialect) {
+spirv::SPIRVTargetAttr::attachInterface(*ctx);
+  });
+}
+
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+MLIRContext &context) {
+  DialectRegistry registry;
+  registerSPIRVTargetInterfaceExternalModels(registry);
+  context.appendDialectRegistry(registry);
+}
+
+// Reuse from existing serializer
+std::optional> SPIRVTargetAttrImpl::serializeToObject(
+Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const {
+  assert(module && "The module must be non null.");
+  if (!module)
+return std::nullopt;
+  if (!mlir::isa(module)) {
+module->emitError("Module must be a GPU module.");
+return std::nullopt;
+  }
+  auto gpuMod = dyn_cast(module);
+  auto spvMods = gpuMod.getOps();
+  // Empty spirv::ModuleOp
+  if (spvMods.empty()) {
+return std::nullopt;
+  }
+  auto spvMod = *spvMods.begin();
+  llvm::SmallVector spvBinary;
+
+  spvBinary.clear();
+  // serialize the spv module to spv binary
+  if (mlir::failed(spirv::serialize(spvMod, spvBinary))) {
+spvMod.emitError() << "Failed to serialize SPIR-V module";

antiagainst wrote:

Nit: "failed to .."

no capitalization to compose better with previous / following messages. 

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.
+class SPIRVTargetAttrImpl
+: public gpu::TargetAttrInterface::FallbackModel {
+public:
+  std::optional>
+  serializeToObject(Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const;
+
+  Attribute createObject(Attribute attribute,
+ const SmallVector &object,
+ const gpu::TargetOptions &options) const;
+};
+} // namespace
+
+// Register the SPIRV dialect, the SPIRV translation & the target interface.
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+DialectRegistry ®istry) {
+  registry.addExtension(+[](MLIRContext *ctx, spirv::SPIRVDialect *dialect) {
+spirv::SPIRVTargetAttr::attachInterface(*ctx);
+  });
+}
+
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+MLIRContext &context) {
+  DialectRegistry registry;
+  registerSPIRVTargetInterfaceExternalModels(registry);
+  context.appendDialectRegistry(registry);
+}
+
+// Reuse from existing serializer
+std::optional> SPIRVTargetAttrImpl::serializeToObject(
+Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const {
+  assert(module && "The module must be non null.");

antiagainst wrote:

We don't need this assert here?

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,94 @@
+//===- SPIRVAttachTarget.cpp - Attach an SPIRV target 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements the `GpuSPIRVAttachTarget` pass, attaching
+// `#spirv.target` attributes to GPU modules.
+//
+//===--===//
+
+#include "mlir/Dialect/GPU/Transforms/Passes.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/TargetAndABI.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/Pass/Pass.h"
+#include "mlir/Target/SPIRV/Target.h"
+#include "llvm/Support/Regex.h"
+
+namespace mlir {
+#define GEN_PASS_DEF_GPUSPIRVATTACHTARGET
+#include "mlir/Dialect/GPU/Transforms/Passes.h.inc"
+} // namespace mlir
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+struct SPIRVAttachTarget
+: public impl::GpuSPIRVAttachTargetBase {
+  using Base::Base;
+
+  void runOnOperation() override;
+
+  void getDependentDialects(DialectRegistry ®istry) const override {
+registry.insert();
+  }
+};
+} // namespace
+
+void SPIRVAttachTarget::runOnOperation() {
+  OpBuilder builder(&getContext());
+  if (!symbolizeVersion(spirvVersion))
+return signalPassFailure();
+  if (!symbolizeClientAPI(clientApi))
+return signalPassFailure();
+  if (!symbolizeVendor(deviceVendor))
+return signalPassFailure();
+  if (!symbolizeDeviceType(deviceType))
+return signalPassFailure();
+
+  Version version = symbolizeVersion(spirvVersion).value();

antiagainst wrote:

We should avoid calling `symbolizeVersion` twice. We can save the result in a 
local variable in the above call and use it here.

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -166,4 +166,35 @@ def SPIRV_ResourceLimitsAttr : 
SPIRV_Attr<"ResourceLimits", "resource_limits"> {
   let assemblyFormat = "`<` struct(params) `>`";
 }
 
+//===--===//
+// SPIRV target attribute.

antiagainst wrote:

Nit: SPIR-V

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,94 @@
+//===- SPIRVAttachTarget.cpp - Attach an SPIRV target 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements the `GpuSPIRVAttachTarget` pass, attaching

antiagainst wrote:

Nit: GPUSPIRVAttachTarget

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -188,4 +188,46 @@ def GpuROCDLAttachTarget: Pass<"rocdl-attach-target", ""> {
   ];
 }
 
+def GpuSPIRVAttachTarget: Pass<"spirv-attach-target", ""> {
+  let summary = "Attaches an SPIRV target attribute to a GPU Module.";
+  let description = [{
+This pass searches for all GPU Modules in the immediate regions and 
attaches
+an SPIRV target if the module matches the name specified by the `module` 
argument.
+
+Example:
+```
+// File: in1.mlir:
+gpu.module @nvvm_module_1 {...}
+gpu.module @spirv_module_1 {...}
+// mlir-opt --spirv-attach-target="module=spirv.* ver=v1.0 caps=Kernel" 
in1.mlir
+gpu.module @nvvm_module_1 {...}
+gpu.module @spirv_module_1 [#spirv.target, resource_limits = <>>] {...}
+```
+  }];
+  let options = [
+Option<"moduleMatcher", "module", "std::string",
+   /*default=*/ [{""}],
+   "Regex used to identify the modules to attach the target to.">,
+Option<"spirvVersion", "ver", "std::string",
+   /*default=*/ "\"v1.0\"",
+   "SPIRV Addressing Model.">,
+ListOption<"spirvCapabilities", "caps", "std::string",
+   "List of required SPIRV Capabilities">,

antiagainst wrote:

s/required/supported/

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.
+class SPIRVTargetAttrImpl
+: public gpu::TargetAttrInterface::FallbackModel {
+public:
+  std::optional>
+  serializeToObject(Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const;
+
+  Attribute createObject(Attribute attribute,
+ const SmallVector &object,
+ const gpu::TargetOptions &options) const;
+};
+} // namespace
+
+// Register the SPIRV dialect, the SPIRV translation & the target interface.
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+DialectRegistry ®istry) {
+  registry.addExtension(+[](MLIRContext *ctx, spirv::SPIRVDialect *dialect) {
+spirv::SPIRVTargetAttr::attachInterface(*ctx);
+  });
+}
+
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+MLIRContext &context) {
+  DialectRegistry registry;
+  registerSPIRVTargetInterfaceExternalModels(registry);
+  context.appendDialectRegistry(registry);
+}
+
+// Reuse from existing serializer
+std::optional> SPIRVTargetAttrImpl::serializeToObject(
+Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const {
+  assert(module && "The module must be non null.");
+  if (!module)
+return std::nullopt;
+  if (!mlir::isa(module)) {
+module->emitError("Module must be a GPU module.");
+return std::nullopt;
+  }
+  auto gpuMod = dyn_cast(module);
+  auto spvMods = gpuMod.getOps();
+  // Empty spirv::ModuleOp
+  if (spvMods.empty()) {
+return std::nullopt;
+  }
+  auto spvMod = *spvMods.begin();
+  llvm::SmallVector spvBinary;
+
+  spvBinary.clear();
+  // serialize the spv module to spv binary
+  if (mlir::failed(spirv::serialize(spvMod, spvBinary))) {
+spvMod.emitError() << "Failed to serialize SPIR-V module";

antiagainst wrote:

Nit: "failed to .."

no capitalization to compose better with previous / following messages. 

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -188,4 +188,46 @@ def GpuROCDLAttachTarget: Pass<"rocdl-attach-target", ""> {
   ];
 }
 
+def GpuSPIRVAttachTarget: Pass<"spirv-attach-target", ""> {
+  let summary = "Attaches an SPIRV target attribute to a GPU Module.";

antiagainst wrote:

Nit: s/SPIRV/SPIR-V/.

SPIR-V is the formal spelling. We should use that when in docs and comments.

Also for all the following docs and comments.

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -166,4 +166,35 @@ def SPIRV_ResourceLimitsAttr : 
SPIRV_Attr<"ResourceLimits", "resource_limits"> {
   let assemblyFormat = "`<` struct(params) `>`";
 }
 
+//===--===//
+// SPIRV target attribute.
+//===--===//
+
+def SPIRV_TargetAttr : SPIRV_Attr<"SPIRVTarget", "target"> {

antiagainst wrote:

This attribute is pretty much a duplication of `spirv::TargetEnvAttr` defined 
in `SPIRVAttributes.h`? We should avoid introducing such duplications and 
causing confusion. Any reaons we cannot use `spirv::TargetEnvAttr` directly? 

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,30 @@
+//===- Target.h - MLIR SPIRV target registration *- C++ 
-*-===//

antiagainst wrote:

Nit: again, please use SPIR-V in docs and comments.

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits

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

Thanks again for the contribution! A couple of comments inlined. My main 
concern is the duplication of `spirv.target` attribute. We should avoid the 
duplication and confusion there.

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,117 @@
+//===- Target.cpp - MLIR SPIRV target compilation ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This files defines SPIRV target related functions including registration
+// calls for the `#spirv.target` compilation attribute.
+//
+//===--===//
+
+#include "mlir/Target/SPIRV/Target.h"
+
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
+#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
+#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Target/SPIRV/Serialization.h"
+
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Program.h"
+#include "llvm/Support/TargetSelect.h"
+
+#include 
+#include 
+
+using namespace mlir;
+using namespace mlir::spirv;
+
+namespace {
+// Implementation of the `TargetAttrInterface` model.
+class SPIRVTargetAttrImpl
+: public gpu::TargetAttrInterface::FallbackModel {
+public:
+  std::optional>
+  serializeToObject(Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const;
+
+  Attribute createObject(Attribute attribute,
+ const SmallVector &object,
+ const gpu::TargetOptions &options) const;
+};
+} // namespace
+
+// Register the SPIRV dialect, the SPIRV translation & the target interface.
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+DialectRegistry ®istry) {
+  registry.addExtension(+[](MLIRContext *ctx, spirv::SPIRVDialect *dialect) {
+spirv::SPIRVTargetAttr::attachInterface(*ctx);
+  });
+}
+
+void mlir::spirv::registerSPIRVTargetInterfaceExternalModels(
+MLIRContext &context) {
+  DialectRegistry registry;
+  registerSPIRVTargetInterfaceExternalModels(registry);
+  context.appendDialectRegistry(registry);
+}
+
+// Reuse from existing serializer
+std::optional> SPIRVTargetAttrImpl::serializeToObject(
+Attribute attribute, Operation *module,
+const gpu::TargetOptions &options) const {
+  assert(module && "The module must be non null.");
+  if (!module)
+return std::nullopt;
+  if (!mlir::isa(module)) {
+module->emitError("Module must be a GPU module.");
+return std::nullopt;
+  }
+  auto gpuMod = dyn_cast(module);
+  auto spvMods = gpuMod.getOps();
+  // Empty spirv::ModuleOp
+  if (spvMods.empty()) {

antiagainst wrote:

Nit: drop `{..}` for trivial if statements per LLVM coding sytle.

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


[clang-tools-extra] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -188,4 +188,46 @@ def GpuROCDLAttachTarget: Pass<"rocdl-attach-target", ""> {
   ];
 }
 
+def GpuSPIRVAttachTarget: Pass<"spirv-attach-target", ""> {
+  let summary = "Attaches an SPIRV target attribute to a GPU Module.";
+  let description = [{
+This pass searches for all GPU Modules in the immediate regions and 
attaches
+an SPIRV target if the module matches the name specified by the `module` 
argument.
+
+Example:
+```
+// File: in1.mlir:
+gpu.module @nvvm_module_1 {...}
+gpu.module @spirv_module_1 {...}
+// mlir-opt --spirv-attach-target="module=spirv.* ver=v1.0 caps=Kernel" 
in1.mlir

antiagainst wrote:

Given the following file

```
Please don't call the symbolize* functions twice everywhere--those functions 
are expensive. We can save the result in a locla variable and use it later.
```
With `mlir-opt ...`, it will generate:

```
gpu.module @nvvm_module_1 {...}
gpu.module @spirv_module_1 [#spirv.target, resource_limits = <>>] {...}
```

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -188,4 +188,46 @@ def GpuROCDLAttachTarget: Pass<"rocdl-attach-target", ""> {
   ];
 }
 
+def GpuSPIRVAttachTarget: Pass<"spirv-attach-target", ""> {
+  let summary = "Attaches an SPIRV target attribute to a GPU Module.";

antiagainst wrote:

Nit: s/SPIRV/SPIR-V/.

SPIR-V is the formal spelling. We should use that when in docs and comments.

Also for all the following docs and comments.

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


[clang] [MLIR] SPIRV Target Attribute (PR #69949)

2023-10-28 Thread Lei Zhang via cfe-commits


@@ -0,0 +1,30 @@
+//===- Target.h - MLIR SPIRV target registration *- C++ 
-*-===//

antiagainst wrote:

Nit: again, please use SPIR-V in docs and comments.

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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-28 Thread Yuxuan Chen via cfe-commits

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


[clang] [clang][Interp] Implement dynamic memory allocation handling (PR #70306)

2023-10-28 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/70306

>From f1bb89bf7cfe8940726a1c51edaaf73d5bd74c4e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 25 Oct 2023 08:33:30 +0200
Subject: [PATCH 1/5] [clang][Interp] Implement dynamic memory allocation
 handling

---
 clang/lib/AST/CMakeLists.txt  |   1 +
 clang/lib/AST/Interp/ByteCodeExprGen.cpp  |  76 +++
 clang/lib/AST/Interp/ByteCodeExprGen.h|   2 +
 clang/lib/AST/Interp/Context.cpp  |   2 +-
 clang/lib/AST/Interp/DynamicAllocator.cpp |  91 
 clang/lib/AST/Interp/DynamicAllocator.h   |  90 
 clang/lib/AST/Interp/EvalEmitter.cpp  |   4 +-
 clang/lib/AST/Interp/Interp.cpp   |  37 
 clang/lib/AST/Interp/Interp.h |  94 
 clang/lib/AST/Interp/InterpState.cpp  |  15 ++
 clang/lib/AST/Interp/InterpState.h|  10 +
 clang/lib/AST/Interp/Opcodes.td   |  24 +++
 clang/test/AST/Interp/new-delete.cpp  | 247 ++
 13 files changed, 690 insertions(+), 3 deletions(-)
 create mode 100644 clang/lib/AST/Interp/DynamicAllocator.cpp
 create mode 100644 clang/lib/AST/Interp/DynamicAllocator.h
 create mode 100644 clang/test/AST/Interp/new-delete.cpp

diff --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index fe3f8c485ec1c56..1423623fb038cab 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -75,6 +75,7 @@ add_clang_library(clangAST
   Interp/Function.cpp
   Interp/InterpBuiltin.cpp
   Interp/Floating.cpp
+  Interp/DynamicAllocator.cpp
   Interp/Interp.cpp
   Interp/InterpBlock.cpp
   Interp/InterpFrame.cpp
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 195af664c13dafc..380ec8fc2dda661 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1629,6 +1629,82 @@ bool 
ByteCodeExprGen::VisitCXXScalarValueInitExpr(
   return this->visitZeroInitializer(classifyPrim(Ty), Ty, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXNewExpr(const CXXNewExpr *E) {
+  assert(classifyPrim(E->getType()) == PT_Ptr);
+  const Expr *Init = E->getInitializer();
+  QualType ElementType = E->getAllocatedType();
+  std::optional ElemT = classify(ElementType);
+
+  const Descriptor *Desc;
+  if (ElemT) {
+if (E->isArray())
+  Desc = nullptr; // We're not going to use it in this case.
+else
+  Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
+/*IsConst=*/false, /*IsTemporary=*/false,
+/*IsMutable=*/false);
+  } else {
+Desc = P.createDescriptor(
+E, ElementType.getTypePtr(),
+E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
+/*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
+  }
+
+  if (E->isArray()) {
+assert(E->getArraySize());
+PrimType SizeT = classifyPrim((*E->getArraySize())->getType());
+
+if (!this->visit(*E->getArraySize()))
+  return false;
+
+if (ElemT) {
+  // N primitive elements.
+  if (!this->emitAllocN(SizeT, *ElemT, E, E))
+return false;
+} else {
+  // N Composite elements.
+  if (!this->emitAllocCN(SizeT, Desc, E))
+return false;
+}
+
+  } else {
+// Allocate just one element.
+if (!this->emitAlloc(Desc, E))
+  return false;
+
+if (Init) {
+  if (ElemT) {
+if (!this->visit(Init))
+  return false;
+
+if (!this->emitInit(*ElemT, E))
+  return false;
+  } else {
+// Composite.
+if (!this->visitInitializer(Init))
+  return false;
+  }
+}
+  }
+
+  if (DiscardResult)
+return this->emitPopPtr(E);
+
+  return true;
+}
+
+template 
+bool ByteCodeExprGen::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
+  const Expr *Arg = E->getArgument();
+
+  // Arg must be an lvalue.
+  if (!this->visit(Arg))
+return false;
+
+  return this->emitFree(E->isArrayForm(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 83986d3dd579ed6..f65dc9494db36ef 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -107,6 +107,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
+  bool VisitCXXNewExpr(const CXXNewExpr *E);
+  bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/lib/AST/Interp/Context.cpp b/clang/lib/AS

[clang] [clang][Interp] IndirectMember initializers (PR #69900)

2023-10-28 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/69900

>From af4c29cfef620476c0d922d6ee9628f95cefc2b5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 22 Oct 2023 19:47:33 +0200
Subject: [PATCH] [clang][Interp] IndirectMember initializers

---
 clang/lib/AST/Interp/ByteCodeStmtGen.cpp | 67 
 clang/lib/AST/Interp/Interp.h|  7 ++-
 clang/lib/AST/Interp/Opcodes.td  |  6 ++-
 clang/test/AST/Interp/records.cpp| 60 +
 4 files changed, 114 insertions(+), 26 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 509abe3ae867f93..c22bbd8623e5326 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -142,6 +142,27 @@ bool ByteCodeStmtGen::visitFunc(const 
FunctionDecl *F) {
   // Classify the return type.
   ReturnType = this->classify(F->getReturnType());
 
+  auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
+  const Expr *InitExpr) -> bool {
+if (std::optional T = this->classify(InitExpr)) {
+  if (!this->visit(InitExpr))
+return false;
+
+  if (F->isBitField())
+return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
+  return this->emitInitThisField(*T, FieldOffset, InitExpr);
+}
+// Non-primitive case. Get a pointer to the field-to-initialize
+// on the stack and call visitInitialzer() for it.
+if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
+  return false;
+
+if (!this->visitInitializer(InitExpr))
+  return false;
+
+return this->emitPopPtr(InitExpr);
+  };
+
   // Emit custom code if this is a lambda static invoker.
   if (const auto *MD = dyn_cast(F);
   MD && MD->isLambdaStaticInvoker())
@@ -162,29 +183,8 @@ bool ByteCodeStmtGen::visitFunc(const 
FunctionDecl *F) {
   if (const FieldDecl *Member = Init->getMember()) {
 const Record::Field *F = R->getField(Member);
 
-if (std::optional T = this->classify(InitExpr)) {
-  if (!this->visit(InitExpr))
-return false;
-
-  if (F->isBitField()) {
-if (!this->emitInitThisBitField(*T, F, InitExpr))
-  return false;
-  } else {
-if (!this->emitInitThisField(*T, F->Offset, InitExpr))
-  return false;
-  }
-} else {
-  // Non-primitive case. Get a pointer to the field-to-initialize
-  // on the stack and call visitInitialzer() for it.
-  if (!this->emitGetPtrThisField(F->Offset, InitExpr))
-return false;
-
-  if (!this->visitInitializer(InitExpr))
-return false;
-
-  if (!this->emitPopPtr(InitExpr))
-return false;
-}
+if (!emitFieldInitializer(F, F->Offset, InitExpr))
+  return false;
   } else if (const Type *Base = Init->getBaseClass()) {
 // Base class initializer.
 // Get This Base and call initializer on it.
@@ -198,6 +198,27 @@ bool ByteCodeStmtGen::visitFunc(const 
FunctionDecl *F) {
   return false;
 if (!this->emitInitPtrPop(InitExpr))
   return false;
+  } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
+assert(IFD->getChainingSize() >= 2);
+
+unsigned NestedFieldOffset = 0;
+const Record::Field *NestedField = nullptr;
+for (const NamedDecl *ND : IFD->chain()) {
+  // FIXME: Can this *not* be a FieldDecl?
+  const FieldDecl *FD = cast(ND);
+  const Record *FieldRecord =
+  this->P.getOrCreateRecord(FD->getParent());
+  assert(FieldRecord);
+
+  NestedField = FieldRecord->getField(FD);
+  assert(NestedField);
+
+  NestedFieldOffset += NestedField->Offset;
+}
+assert(NestedField);
+
+if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr))
+  return false;
   } else {
 assert(Init->isDelegatingInitializer());
 if (!this->emitThis(InitExpr))
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 7dd415d6e460536..3e24a1782b4af14 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1065,15 +1065,18 @@ bool InitThisField(InterpState &S, CodePtr OpPC, 
uint32_t I) {
   return true;
 }
 
+// FIXME: The Field pointer here is too much IMO and we could instead just
+// pass an Offset + BitWidth pair.
 template ::T>
-bool InitThisBitField(InterpState &S, CodePtr OpPC, const Record::Field *F) {
+bool InitThisBitField(InterpState &S, CodePtr OpPC, const Record::Field *F,
+  uint32_t FieldOffset) {
   assert(F->isBitField());
   if (S.checkingPotentialConstantExpression())
 return false;
   const Pointer &This = S.Current->getThis();
   if (!CheckThis(S, OpPC, This))
 

[PATCH] D86993: Document Clang's expectations of the C standard library.

2023-10-28 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D86993#4655474 , @RalfJung wrote:

> With everything moving to github PRs, what are the next steps for this patch?

I'm unlikely to have cycles to work on this in the near future. If someone else 
wants to take over here, you would have my blessing :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86993

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


[clang] [clang-format][NFC] Reduce indent (PR #70583)

2023-10-28 Thread Björn Schäpers via cfe-commits

https://github.com/HazardyKnusperkeks created 
https://github.com/llvm/llvm-project/pull/70583

By using if init statement.

From b1af9c060cc5dca1f3bbc551d6a77e73451ffa06 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Sun, 29 Oct 2023 07:18:06 +0100
Subject: [PATCH] [clang-format][NFC] Reduce indent

By using if init statement.
---
 clang/lib/Format/TokenAnnotator.cpp | 22 ++
 1 file changed, 10 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9ec8b93e39fd23a..eda312689f3ce4a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2093,18 +2093,16 @@ class AnnotatingParser {
   !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
  tok::comma, tok::period, tok::arrow,
  tok::coloncolon, tok::kw_noexcept)) {
-if (FormatToken *AfterParen = Current.MatchingParen->Next) {
-  // Make sure this isn't the return type of an Obj-C block declaration
-  if (AfterParen->isNot(tok::caret)) {
-if (FormatToken *BeforeParen = Current.MatchingParen->Previous) {
-  if (BeforeParen->is(tok::identifier) &&
-  BeforeParen->isNot(TT_TypenameMacro) &&
-  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
-  (!BeforeParen->Previous ||
-   BeforeParen->Previous->ClosesTemplateDeclaration)) {
-Current.setType(TT_FunctionAnnotationRParen);
-  }
-}
+if (FormatToken *AfterParen = Current.MatchingParen->Next;
+AfterParen->isNot(tok::caret)) {
+  // Make sure this isn't the return type of an Obj-C block 
declaration.
+  if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
+  BeforeParen->is(tok::identifier) &&
+  BeforeParen->isNot(TT_TypenameMacro) &&
+  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
+  (!BeforeParen->Previous ||
+   BeforeParen->Previous->ClosesTemplateDeclaration)) {
+Current.setType(TT_FunctionAnnotationRParen);
   }
 }
   }

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


[clang] [clang-format][NFC] Reduce indent (PR #70583)

2023-10-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Björn Schäpers (HazardyKnusperkeks)


Changes

By using if init statement.

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


1 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+10-12) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9ec8b93e39fd23a..eda312689f3ce4a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2093,18 +2093,16 @@ class AnnotatingParser {
   !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
  tok::comma, tok::period, tok::arrow,
  tok::coloncolon, tok::kw_noexcept)) {
-if (FormatToken *AfterParen = Current.MatchingParen->Next) {
-  // Make sure this isn't the return type of an Obj-C block declaration
-  if (AfterParen->isNot(tok::caret)) {
-if (FormatToken *BeforeParen = Current.MatchingParen->Previous) {
-  if (BeforeParen->is(tok::identifier) &&
-  BeforeParen->isNot(TT_TypenameMacro) &&
-  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
-  (!BeforeParen->Previous ||
-   BeforeParen->Previous->ClosesTemplateDeclaration)) {
-Current.setType(TT_FunctionAnnotationRParen);
-  }
-}
+if (FormatToken *AfterParen = Current.MatchingParen->Next;
+AfterParen->isNot(tok::caret)) {
+  // Make sure this isn't the return type of an Obj-C block 
declaration.
+  if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
+  BeforeParen->is(tok::identifier) &&
+  BeforeParen->isNot(TT_TypenameMacro) &&
+  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
+  (!BeforeParen->Previous ||
+   BeforeParen->Previous->ClosesTemplateDeclaration)) {
+Current.setType(TT_FunctionAnnotationRParen);
   }
 }
   }

``




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


  1   2   >