[clang] [libclang/python] Derive library function types from annotations (PR #142120)
github-actions[bot] wrote: :warning: Python code formatter, darker found issues in your code. :warning: You can test this locally with the following command: ``bash darker --check --diff -r HEAD~1...HEAD clang/bindings/python/clang/cindex.py `` View the diff from darker here. ``diff --- cindex.py 2025-05-30 10:54:15.00 + +++ cindex.py 2025-05-30 10:59:10.491593 + @@ -4021,556 +4021,727 @@ return annotation_types # Functions strictly alphabetical order. class ClangLib(Protocol): - def clang_annotateTokens( self, arg1: TranslationUnit, arg2: _Pointer[Token], arg3: c_uint, arg4: _Pointer[Cursor], -) -> None: ... - -def clang_CompilationDatabase_dispose(self, arg1: _Pointer[c_void_p]) -> None: ... +) -> None: +... + +def clang_CompilationDatabase_dispose(self, arg1: _Pointer[c_void_p]) -> None: +... def clang_CompilationDatabase_fromDirectory( self, arg1: c_interop_string, arg2: _Pointer[c_uint] -) -> _Pointer[c_void_p]: ... +) -> _Pointer[c_void_p]: +... def clang_CompilationDatabase_getAllCompileCommands( self, arg1: _Pointer[c_void_p] -) -> _Pointer[c_void_p]: ... +) -> _Pointer[c_void_p]: +... def clang_CompilationDatabase_getCompileCommands( self, arg1: _Pointer[c_void_p], arg2: c_interop_string -) -> _Pointer[c_void_p]: ... - -def clang_CompileCommands_dispose(self, arg1: _Pointer[c_void_p]) -> None: ... +) -> _Pointer[c_void_p]: +... + +def clang_CompileCommands_dispose(self, arg1: _Pointer[c_void_p]) -> None: +... def clang_CompileCommands_getCommand( self, arg1: _Pointer[c_void_p], arg2: c_uint -) -> _Pointer[c_void_p]: ... - -def clang_CompileCommands_getSize(self, arg1: _Pointer[c_void_p]) -> c_uint: ... +) -> _Pointer[c_void_p]: +... + +def clang_CompileCommands_getSize(self, arg1: _Pointer[c_void_p]) -> c_uint: +... def clang_CompileCommand_getArg( self, arg1: _Pointer[c_void_p], arg2: c_uint -) -> _CXString: ... - -def clang_CompileCommand_getDirectory( -self, arg1: _Pointer[c_void_p] -) -> _CXString: ... - -def clang_CompileCommand_getFilename( -self, arg1: _Pointer[c_void_p] -) -> _CXString: ... - -def clang_CompileCommand_getNumArgs(self, arg1: _Pointer[c_void_p]) -> c_uint: ... +) -> _CXString: +... + +def clang_CompileCommand_getDirectory(self, arg1: _Pointer[c_void_p]) -> _CXString: +... + +def clang_CompileCommand_getFilename(self, arg1: _Pointer[c_void_p]) -> _CXString: +... + +def clang_CompileCommand_getNumArgs(self, arg1: _Pointer[c_void_p]) -> c_uint: +... def clang_codeCompleteAt( self, arg1: TranslationUnit, arg2: c_interop_string, arg3: c_int, arg4: c_int, arg5: c_void_p, arg6: c_int, arg7: c_int, -) -> _Pointer[CCRStructure]: ... +) -> _Pointer[CCRStructure]: +... def clang_codeCompleteGetDiagnostic( self, arg1: CodeCompletionResults, arg2: c_int -) -> Diagnostic: ... - -def clang_codeCompleteGetNumDiagnostics( -self, arg1: CodeCompletionResults -) -> c_int: ... - -def clang_createIndex(self, arg1: c_int, arg2: c_int) -> _Pointer[c_void_p]: ... +) -> Diagnostic: +... + +def clang_codeCompleteGetNumDiagnostics(self, arg1: CodeCompletionResults) -> c_int: +... + +def clang_createIndex(self, arg1: c_int, arg2: c_int) -> _Pointer[c_void_p]: +... def clang_createTranslationUnit( self, arg1: Index, arg2: c_interop_string -) -> _Pointer[c_void_p]: ... - -def clang_CXRewriter_create(self, arg1: TranslationUnit) -> _Pointer[c_void_p]: ... - -def clang_CXRewriter_dispose(self, arg1: Rewriter) -> None: ... +) -> _Pointer[c_void_p]: +... + +def clang_CXRewriter_create(self, arg1: TranslationUnit) -> _Pointer[c_void_p]: +... + +def clang_CXRewriter_dispose(self, arg1: Rewriter) -> None: +... def clang_CXRewriter_insertTextBefore( self, arg1: Rewriter, arg2: SourceLocation, arg3: c_interop_string -) -> None: ... - -def clang_CXRewriter_overwriteChangedFiles(self, arg1: Rewriter) -> c_int: ... - -def clang_CXRewriter_removeText( -self, arg1: Rewriter, arg2: SourceRange -) -> None: ... +) -> None: +... + +def clang_CXRewriter_overwriteChangedFiles(self, arg1: Rewriter) -> c_int: +... + +def clang_CXRewriter_removeText(self, arg1: Rewriter, arg2: SourceRange) -> None: +... def clang_CXRewriter_replaceText( self, arg1: Rewriter, arg2: SourceRange, arg3: c_interop_string -) -> None: ... - -def clang_CXRewriter_writeMainFileToStdOut(self, arg1: Rewri
[clang] [clang][SPIRV] Fix build issue after c474f8f (PR #141954)
Keenuts wrote: thanks! https://github.com/llvm/llvm-project/pull/141954 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][SPIRV] Fix build issue after c474f8f (PR #141954)
https://github.com/Keenuts closed https://github.com/llvm/llvm-project/pull/141954 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Separate implicit int conversion on negation sign to new diagnostic group (PR #139429)
https://github.com/AaronBallman commented: LGTM aside from a request for another test https://github.com/llvm/llvm-project/pull/139429 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Separate implicit int conversion on negation sign to new diagnostic group (PR #139429)
@@ -0,0 +1,46 @@ +// RUN: %clang_cc1 %s -verify=expected -Wimplicit-int-conversion +// RUN: %clang_cc1 %s -verify=none -Wimplicit-int-conversion -Wno-implicit-int-conversion-on-negation + +// none-no-diagnostics + +char test_char(char x) { + return -x; // expected-warning {{implicit conversion loses integer precision: 'int' to 'char' on negation}} +} + +unsigned char test_unsigned_char(unsigned char x) { + return -x; // expected-warning {{implicit conversion loses integer precision: 'int' to 'unsigned char' on negation}} +} + +short test_short(short x) { + return -x; // expected-warning {{implicit conversion loses integer precision: 'int' to 'short' on negation}} +} + +unsigned short test_unsigned_short(unsigned short x) { + return -x; // expected-warning {{implicit conversion loses integer precision: 'int' to 'unsigned short' on negation}} +} AaronBallman wrote: One last test and I think we're good: ``` unsigned _BitInt(16) test_unsigned_bit_int(unsigned _BitInt(16) x) { return -x; } ``` this should not diagnose because `_BitInt` does not undergo promotion. https://github.com/llvm/llvm-project/pull/139429 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] Refactor error handling to use ExitOnError (PR #141699)
@@ -0,0 +1,29 @@ +/// Invalid output path (%t is a file, not a directory). +// RUN: rm -rf %t && touch %t +// RUN: not clang-doc %s -output=%t/subdir 2>&1 | FileCheck %s +// CHECK: clang-doc error: +// CHECK: {{(Not a directory|no such file or directory)}} + +/// Invalid format option. +// RUN: not clang-doc %s --output=%t.dir -format=badformat 2>&1 | FileCheck %s --check-prefix=BAD-FORMAT +// BAD-FORMAT: clang-doc: for the --format option: Cannot find option named 'badformat'! + +/// Missing HTML asset directory (warning only). +// RUN: clang-doc %s -format=html -asset=%t/nonexistent-assets 2>&1 | FileCheck %s --check-prefix=ASSET-WARN +// ASSET-WARN: Asset path supply is not a directory +// ASSET-WARN: falling back to default + +/// Mapping failure (with --ignore-map-errors=false). +// RUN: not clang-doc %t/nonexistent.cpp -ignore-map-errors=false 2>&1 | FileCheck %s --check-prefix=MAP-FAIL +// MAP-FAIL: clang-doc error: Failed to run action + +/// Mapping failure (with --ignore-map-errors=true). +// RUN: clang-doc %t/nonexistent.cpp 2>&1 | FileCheck %s --check-prefix=MAP-WARN +// MAP-WARN: Error mapping decls in files. Clang-doc will ignore these files and continue + +///Invalid executor type +// RUN: not clang-doc --executor=invalid %s 2>&1 | FileCheck %s --check-prefix=EXECUTOR-FAIL +// EXECUTOR-FAIL: clang-doc error: +// EXECUTOR-FAIL: Executor "invalid" is not registered snarang181 wrote: I ran `clang-doc --extra-arg=-nonexistentflag %s` and I get a diagnostic error saying `error: unknown argument: '-nonexistentflag'` but this does not seem to be blocking, and the test does return. Hence, the `ExitOnErr` handler does not get invoked. https://github.com/llvm/llvm-project/pull/141699 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] Refactor error handling to use ExitOnError (PR #141699)
https://github.com/snarang181 updated https://github.com/llvm/llvm-project/pull/141699 >From f0b3184f2d4342eb0aacf3a77671556ac2e57650 Mon Sep 17 00:00:00 2001 From: Samarth Narang Date: Tue, 27 May 2025 21:32:41 -0400 Subject: [PATCH 01/14] [clang-doc] Refactor error handling to use ExitOnError This patch replaces manual error checks and exit() calls in clang-doc with llvm::ExitOnError for consistency and maintainability. No functional changes to outputs or APIs. --- .../clang-doc/tool/ClangDocMain.cpp | 32 ++- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp index 41fbe87a713d9..54c5d41e3a6cd 100644 --- a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp +++ b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp @@ -43,6 +43,7 @@ using namespace clang::ast_matchers; using namespace clang::tooling; using namespace clang; +static llvm::ExitOnError ExitOnErr; static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static llvm::cl::OptionCategory ClangDocCategory("clang-doc options"); @@ -249,6 +250,8 @@ int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); std::error_code OK; + ExitOnErr.setBanner("clang-doc error: "); + const char *Overview = R"(Generates documentation from source code and comments. @@ -272,11 +275,7 @@ Example usage for a project using a compile commands database: // Fail early if an invalid format was provided. std::string Format = getFormatString(); llvm::outs() << "Emiting docs in " << Format << " format.\n"; - auto G = doc::findGeneratorByName(Format); - if (!G) { -llvm::errs() << toString(G.takeError()) << "\n"; -return 1; - } + auto G = ExitOnErr(doc::findGeneratorByName(Format)); ArgumentsAdjuster ArgAdjuster; if (!DoxygenOnly) @@ -297,10 +296,7 @@ Example usage for a project using a compile commands database: {UserStylesheets.begin(), UserStylesheets.end()}}; if (Format == "html") { -if (auto Err = getHtmlAssetFiles(argv[0], CDCtx)) { - llvm::errs() << toString(std::move(Err)) << "\n"; - return 1; -} +ExitOnErr(getHtmlAssetFiles(argv[0], CDCtx)); } if (Format == "mustache") { @@ -320,7 +316,7 @@ Example usage for a project using a compile commands database: "these files and continue:\n" << toString(std::move(Err)) << "\n"; else { - llvm::errs() << toString(std::move(Err)) << "\n"; + ExitOnErr(std::move(Err)); return 1; } } @@ -391,22 +387,14 @@ Example usage for a project using a compile commands database: sortUsrToInfo(USRToInfo); // Ensure the root output directory exists. - if (std::error_code Err = llvm::sys::fs::create_directories(OutDirectory); - Err != std::error_code()) { -llvm::errs() << "Failed to create directory '" << OutDirectory << "'\n"; -return 1; - } + ExitOnErr( + llvm::errorCodeToError(llvm::sys::fs::create_directories(OutDirectory))); // Run the generator. llvm::outs() << "Generating docs...\n"; - if (auto Err = - G->get()->generateDocs(OutDirectory, std::move(USRToInfo), CDCtx)) { -llvm::errs() << toString(std::move(Err)) << "\n"; -return 1; - } - + ExitOnErr(G->generateDocs(OutDirectory, std::move(USRToInfo), CDCtx)); llvm::outs() << "Generating assets for docs...\n"; - Err = G->get()->createResources(CDCtx); + Err = G->createResources(CDCtx); if (Err) { llvm::outs() << "warning: " << toString(std::move(Err)) << "\n"; } >From daab868b8bc145286af02867b24175b6cb9edd0e Mon Sep 17 00:00:00 2001 From: Samarth Narang Date: Wed, 28 May 2025 18:47:17 -0400 Subject: [PATCH 02/14] Addressing PR feedback --- clang-tools-extra/clang-doc/tool/ClangDocMain.cpp| 12 +--- .../test/clang-doc/invalid-file-error.test | 4 2 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 clang-tools-extra/test/clang-doc/invalid-file-error.test diff --git a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp index 54c5d41e3a6cd..932a9654b563a 100644 --- a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp +++ b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp @@ -43,7 +43,6 @@ using namespace clang::ast_matchers; using namespace clang::tooling; using namespace clang; -static llvm::ExitOnError ExitOnErr; static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static llvm::cl::OptionCategory ClangDocCategory("clang-doc options"); @@ -119,6 +118,8 @@ static llvm::cl::opt FormatEnum( "Documentation in mustache HTML format")), llvm::cl::init(OutputFormatTy::yaml), llvm::cl::cat(ClangDocCategory)); +static llvm::ExitOnError ExitOnErr; + static std::string getFormatString() { switch (FormatEn
[clang] [clang-format] Handle bit-field colon of non-numeric-constant size (PR #142110)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/142110 Fix #142050 >From 9cf70104e03372be9122d44a87694cd04b9b34c9 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Fri, 30 May 2025 01:52:31 -0700 Subject: [PATCH] [clang-format] Handle bit-field colon of non-numeric-constant size Fix #142050 --- clang/lib/Format/TokenAnnotator.cpp | 4 +++- clang/unittests/Format/TokenAnnotatorTest.cpp | 8 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 51ececc0c0e81..f8272811bbe6c 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1411,7 +1411,9 @@ class AnnotatingParser { assert(Prev); if (Prev->isPointerOrReference()) Prev->setFinalizedType(TT_PointerOrReference); - } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { + } else if ((CurrentToken && CurrentToken->is(tok::numeric_constant)) || + (Prev && Prev->is(TT_StartOfName) && !Scopes.empty() && + Scopes.back() == ST_Class)) { Tok->setType(TT_BitFieldColon); } else if (Contexts.size() == 1 && !Line.getFirstNonComment()->isOneOf(tok::kw_enum, tok::kw_case, diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index f39468424a393..1a5ed4b9040c2 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -4076,6 +4076,14 @@ TEST_F(TokenAnnotatorTest, EnumColonInTypedef) { EXPECT_TOKEN(Tokens[2], tok::colon, TT_Unknown); // Not TT_InheritanceColon. } +TEST_F(TokenAnnotatorTest, BitFieldColon) { + auto Tokens = annotate("class C {\n" + " int f : SIZE;\n" + "};"); + ASSERT_EQ(Tokens.size(), 11u) << Tokens; + EXPECT_TOKEN(Tokens[5], tok::colon, TT_BitFieldColon); +} + } // namespace } // namespace format } // namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Derive library function types from annotations (PR #142120)
DeinAlptraum wrote: @Endilll this is an attempt at implementing what we've discussed previously: defining the library function signatures only in a single place in a way that serves both as type annotations for the library functions and registering the correct library function types on the lib object. This PR seems to work as is (at least all unit tests pass, except for a single one that I was too lazy to adapt for the PoC) but it has several issues, namely 1. the biggest one: it seems that, once a function has been registered (=argument and return types defined on the lib object) they are automatically converted as far as possible. To quote from https://docs.python.org/3/library/ctypes.html > Specifying a format protects against incompatible argument types (just as a > prototype for a C function), and tries to convert the arguments to valid types > When a foreign function is called, each actual argument is passed to the > [from_param()](https://docs.python.org/3/library/ctypes.html#ctypes._CData.from_param) > class method of the items in the > [argtypes](https://docs.python.org/3/library/ctypes.html#ctypes._CFuncPtr.argtypes) > tuple, this method allows adapting the actual argument to an object that the > foreign function accepts. For example, **a > [c_char_p](https://docs.python.org/3/library/ctypes.html#ctypes.c_char_p) > item in the > [argtypes](https://docs.python.org/3/library/ctypes.html#ctypes._CFuncPtr.argtypes) > tuple will convert a string passed as argument into a bytes object using > ctypes conversion rules**. > Fundamental data types, when returned as foreign function call results, [...] > are transparently converted to native Python types. In other words, **if a > foreign function has a > [restype](https://docs.python.org/3/library/ctypes.html#ctypes._CFuncPtr.restype) > of > [c_char_p](https://docs.python.org/3/library/ctypes.html#ctypes.c_char_p), > you will always receive a Python bytes object, not a > [c_char_p](https://docs.python.org/3/library/ctypes.html#ctypes.c_char_p) > instance**. That explains why we don't have to do any conversion between C types and Python types at the boundary between the lib object and the Python interface. Unfortunately, it also means that, while we need to annotate the library functions with C Types such as `c_int` so that these can be read out and properly registered on the library object, after these are registered at runtime these types become wrong so the type checker complains at almost every function call that we don't actually pass in or return e.g. a `c_int` but a normal Python `int`. 2. `ctypes` uses function calls to generate certain types used when registering functions at runtime. E.g. pointer types are generated by calling `POINTER(sometype)`. The type checker doesn't call functions so it cannot use these for annotations. These specific function calls just wrap the type in the `_Pointer` generic, which makes for a valid type annotation as `_Pointer[sometype]` - the ugly thing is, I need to convert between these via string manipulation to convert `_Pointer` type annotations to a `POINTER()` call when registering the function. The way this makes the types used for function registration less transparent makes me uncomfortable. 3. Adding on to 2., there is also the `CFUNCTYPE()` used for generating the types for the callback functions, similar to `POINTER()`, but it goes beyond simple wrapping so there is no way to annotate these correctly. I had to annotate these as *the actual generated function objects* so the functions can be registered properly, but the type checker complains correctly that these are not valid types. Sorry, I hope this was comprehensible, the issues are a bit involved... Would love to hear your opinion on this, but imo this seems like it adds too many workarounds and intransparencies, and there's so many unsolvable issues that we end up with almost no benefit. https://github.com/llvm/llvm-project/pull/142120 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-reorder-fields] Use expanded location for macros (PR #142147)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/142147 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [PowerPC] frontend get target feature from backend with cpu name (PR #137670)
https://github.com/diggerlin updated https://github.com/llvm/llvm-project/pull/137670 >From 97f10e6a0fb4c158359e79e24650f8fdf4d23ef2 Mon Sep 17 00:00:00 2001 From: zhijian Date: Fri, 25 Apr 2025 13:09:47 + Subject: [PATCH 1/7] implement getting target features from backend for clang frontend --- clang/lib/Basic/Targets/PPC.cpp | 150 +- .../cxx11-thread-local-reference.cpp | 2 +- .../Driver/aix-shared-lib-tls-model-opt.c | 7 +- .../Driver/aix-small-local-exec-dynamic-tls.c | 15 +- clang/test/Driver/ppc-crbits.cpp | 4 - clang/test/Driver/ppc-isa-features.cpp| 22 +-- llvm/include/llvm/MC/MCSubtargetInfo.h| 32 +++- .../llvm/TargetParser/PPCTargetParser.h | 5 + llvm/lib/MC/MCSubtargetInfo.cpp | 32 +++- llvm/lib/Target/PowerPC/PPC.td| 4 +- llvm/lib/TargetParser/CMakeLists.txt | 8 + llvm/lib/TargetParser/PPCTargetParser.cpp | 26 +++ llvm/utils/TableGen/SubtargetEmitter.cpp | 52 -- 13 files changed, 159 insertions(+), 200 deletions(-) diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp index 425ad68bb9098..2a1024be1d537 100644 --- a/clang/lib/Basic/Targets/PPC.cpp +++ b/clang/lib/Basic/Targets/PPC.cpp @@ -15,6 +15,7 @@ #include "clang/Basic/MacroBuilder.h" #include "clang/Basic/TargetBuiltins.h" #include "llvm/TargetParser/PPCTargetParser.h" +#include using namespace clang; using namespace clang::targets; @@ -516,130 +517,15 @@ static bool ppcUserFeaturesCheck(DiagnosticsEngine &Diags, bool PPCTargetInfo::initFeatureMap( llvm::StringMap &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector &FeaturesVec) const { - Features["altivec"] = llvm::StringSwitch(CPU) -.Case("7400", true) -.Case("g4", true) -.Case("7450", true) -.Case("g4+", true) -.Case("970", true) -.Case("g5", true) -.Case("pwr6", true) -.Case("pwr7", true) -.Case("pwr8", true) -.Case("pwr9", true) -.Case("ppc64", true) -.Case("ppc64le", true) -.Default(false); - - Features["power9-vector"] = (CPU == "pwr9"); - Features["crypto"] = llvm::StringSwitch(CPU) - .Case("ppc64le", true) - .Case("pwr9", true) - .Case("pwr8", true) - .Default(false); - Features["power8-vector"] = llvm::StringSwitch(CPU) - .Case("ppc64le", true) - .Case("pwr9", true) - .Case("pwr8", true) - .Default(false); - Features["bpermd"] = llvm::StringSwitch(CPU) - .Case("ppc64le", true) - .Case("pwr9", true) - .Case("pwr8", true) - .Case("pwr7", true) - .Default(false); - Features["extdiv"] = llvm::StringSwitch(CPU) - .Case("ppc64le", true) - .Case("pwr9", true) - .Case("pwr8", true) - .Case("pwr7", true) - .Default(false); - Features["direct-move"] = llvm::StringSwitch(CPU) -.Case("ppc64le", true) -.Case("pwr9", true) -.Case("pwr8", true) -.Default(false); - Features["crbits"] = llvm::StringSwitch(CPU) -.Case("ppc64le", true) -.Case("pwr9", true) -.Case("pwr8", true) -.Default(false); - Features["vsx"] = llvm::StringSwitch(CPU) -.Case("ppc64le", true) -.Case("pwr9", true) -.Case("pwr8", true) -.Case("pwr7", true) -.Default(false); - Features["htm"] = llvm::StringSwitch(CPU) -.Case("ppc64le", true) -.Case("pwr9", true) -.Case("pwr8", true) -.Default(false); - - // ROP Protect is off by default. - Features["rop-protect"] = false; - // Privileged instructions are off by default. - Features["privileged"] = false; - if (getTriple().isOSAIX()) { -// The code generated by the -maix-small-local-[exec|dynamic]-tls option is -// turned off by default. -Features["aix-small-local-exec-tls"] = false; -Features["aix-small-local-dyna
[clang-tools-extra] [clang-reorder-fields] Use expanded location for macros (PR #142147)
https://github.com/vvuksanovic created https://github.com/llvm/llvm-project/pull/142147 Fixes macros being replaced instead of their expansion. Closes #52632 >From 82f35e120d075eb0f55d02ff2a4d750e6e352475 Mon Sep 17 00:00:00 2001 From: Vladimir Vuksanovic Date: Fri, 30 May 2025 05:41:09 -0700 Subject: [PATCH] [clang-reorder-fields] Use expanded location for macros Fixes macros being replaced instead of their expansion. Closes #52632 --- .../ReorderFieldsAction.cpp | 4 .../MacroExpansionField.cpp | 24 +++ 2 files changed, 28 insertions(+) create mode 100644 clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index ea0207619fb2b..3b1cd18d80346 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -86,6 +86,10 @@ getNewFieldsOrder(const RecordDecl *Definition, static void addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, std::map &Replacements) { + if (Old.getBegin().isMacroID()) +Old = Context.getSourceManager().getExpansionRange(Old).getAsRange(); + if (New.getBegin().isMacroID()) +New = Context.getSourceManager().getExpansionRange(New).getAsRange(); StringRef NewText = Lexer::getSourceText(CharSourceRange::getTokenRange(New), Context.getSourceManager(), Context.getLangOpts()); diff --git a/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp b/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp new file mode 100644 index 0..a4c3cbc1e12f4 --- /dev/null +++ b/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp @@ -0,0 +1,24 @@ +// RUN: clang-reorder-fields -record-name ::bar::Foo -fields-order z,y,x %s -- | FileCheck %s + +namespace bar { + +#define INT_DECL(NAME) int NAME // CHECK: {{^#define INT_DECL\(NAME\) int NAME}} +#define MACRO_DECL int x; // CHECK-NEXT: {{^#define MACRO_DECL int x;}} + +struct Foo { + MACRO_DECL // CHECK: {{^ INT_DECL\(z\);}} + int y; // CHECK-NEXT: {{^ int y;}} + INT_DECL(z); // CHECK-NEXT: {{^ MACRO_DECL}} +}; + +#define FOO 0 // CHECK: {{^#define FOO 0}} +#define BAR 1 // CHECK-NEXT: {{^#define BAR 1}} +#define BAZ 2 // CHECK-NEXT: {{^#define BAZ 2}} + +struct Foo foo = { + FOO, // CHECK: {{^ BAZ,}} + BAR, // CHECK-NEXT: {{^ BAR,}} + BAZ, // CHECK-NEXT: {{^ FOO,}} +}; + +} // end namespace bar ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [mlir] [flang] Add support for -mprefer-vector-width= (PR #142073)
mcinally wrote: Thanks, @tarunprabhu! https://github.com/llvm/llvm-project/pull/142073 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][NFC] Move Diags.isIgnored check later in checkForRedundantLoop (PR #141470)
https://github.com/shafik approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/141470 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 4d650ef - [Sema] Fix type mismatch error when arguments to elementwise math builtin have different qualifiers, which should be well-formed (#141485)
Author: Acthink Yang Date: 2025-05-30T07:09:20-07:00 New Revision: 4d650ef4b3d7a0f21f8681e73586d0319fc3953b URL: https://github.com/llvm/llvm-project/commit/4d650ef4b3d7a0f21f8681e73586d0319fc3953b DIFF: https://github.com/llvm/llvm-project/commit/4d650ef4b3d7a0f21f8681e73586d0319fc3953b.diff LOG: [Sema] Fix type mismatch error when arguments to elementwise math builtin have different qualifiers, which should be well-formed (#141485) Fixes #141397 Element-wise math builtins (e.g. __builtin_elementwise_max/__builtin_elementwise_pow etc.) fail when their arguments have different qualifications, but should be well-formed. The fix is to use hasSameUnqualifiedType to check if the arguments match. Added: Modified: clang/docs/ReleaseNotes.rst clang/lib/Sema/SemaChecking.cpp clang/test/Sema/builtins-elementwise-math.c Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 32266fce4d3cb..dc97883de05d0 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -669,6 +669,7 @@ Bug Fixes in This Version base classes. (GH139452) - Fixed an assertion failure in serialization of constexpr structs containing unions. (#GH140130) - Fixed duplicate entries in TableGen that caused the wrong attribute to be selected. (GH#140701) +- Fixed type mismatch error when 'builtin-elementwise-math' arguments have diff erent qualifiers, this should be well-formed. (#GH141397) Bug Fixes to Compiler Builtins ^^ diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index ba2630e960e6f..373ca549cb23b 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -15572,7 +15572,7 @@ Sema::BuiltinVectorMath(CallExpr *TheCall, if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1)) return std::nullopt; - if (TyA.getCanonicalType() != TyB.getCanonicalType()) { + if (!Context.hasSameUnqualifiedType(TyA, TyB)) { Diag(LocA, diag::err_typecheck_call_ diff erent_arg_types) << TyA << TyB; return std::nullopt; } diff --git a/clang/test/Sema/builtins-elementwise-math.c b/clang/test/Sema/builtins-elementwise-math.c index b5648a5e5c6e8..01057b3f8d083 100644 --- a/clang/test/Sema/builtins-elementwise-math.c +++ b/clang/test/Sema/builtins-elementwise-math.c @@ -3,6 +3,7 @@ typedef double double2 __attribute__((ext_vector_type(2))); typedef double double4 __attribute__((ext_vector_type(4))); typedef float float2 __attribute__((ext_vector_type(2))); +typedef float float3 __attribute__((ext_vector_type(3))); typedef float float4 __attribute__((ext_vector_type(4))); typedef int int2 __attribute__((ext_vector_type(2))); @@ -1202,3 +1203,13 @@ void test_builtin_elementwise_fma(int i32, int2 v2i32, short i16, c3 = __builtin_elementwise_fma(f32, f32, c3); // expected-error@-1 {{3rd argument must be a scalar or vector of floating-point types (was '_Complex float')}} } + +typedef struct { + float3 b; +} struct_float3; +// This example uncovered a bug #141397 : +// Type mismatch error when 'builtin-elementwise-math' arguments have diff erent qualifiers, this should be well-formed +float3 foo(float3 a,const struct_float3* hi) { + float3 b = __builtin_elementwise_max((float3)(0.0f), a); + return __builtin_elementwise_pow(b, hi->b.yyy); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Fix type mismatch error when arguments to elementwise math builtin have different qualifiers, which should be well-formed (PR #141485)
https://github.com/shafik closed https://github.com/llvm/llvm-project/pull/141485 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Declare builtins used in #pragma intrinsic (PR #138205)
sarnex wrote: Sure, I was hoping I could find an easy fix really quickly but just reproing took me a while, I'll revert immediately in the future, thanks. https://github.com/llvm/llvm-project/pull/138205 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,209 @@ +#include "clang/AST/RecordLayout.h" +#include "clang/AST/Type.h" +#include "clang/Analysis/Analyses/ThreadSafetyTIL.h" +#include "clang/Basic/LLVM.h" +#include "clang/Basic/TargetInfo.h" +#include "llvm/ABI/Types.h" +#include "llvm/Support/Alignment.h" +#include "llvm/Support/Casting.h" +#include + +namespace clang { +namespace mapper { + +const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) { + QT = QT.getCanonicalType().getUnqualifiedType(); + + auto It = TypeCache.find(QT); + if (It != TypeCache.end()) +return It->second; + + const llvm::abi::Type *Result = nullptr; + if (const auto *BT = dyn_cast(QT.getTypePtr())) { +Result = convertBuiltinType(BT); + } else if (const auto *PT = dyn_cast(QT.getTypePtr())) { +Result = convertPointerType(PT); + } else if (const auto *AT = dyn_cast(QT.getTypePtr())) { +Result = convertArrayType(AT); + } else if (const auto *VT = dyn_cast(QT.getTypePtr())) { +Result = convertVectorType(VT); + } else if (const auto *RT = dyn_cast(QT.getTypePtr())) { +Result = convertRecordType(RT); + } else if (const auto *ET = dyn_cast(QT.getTypePtr())) { +Result = convertEnumType(ET); + } else { +// TODO: Write Fallback logic for unsupported types. + } + TypeCache[QT] = Result; + return Result; +} + +const llvm::abi::Type * +QualTypeMapper::convertBuiltinType(const BuiltinType *BT) { + switch (BT->getKind()) { + case BuiltinType::Void: +return Builder.getVoidType(); + + case BuiltinType::Bool: + case BuiltinType::UChar: + case BuiltinType::Char_U: + case BuiltinType::UShort: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char_S: + case BuiltinType::SChar: + case BuiltinType::Short: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), true); + + case BuiltinType::WChar_U: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::WChar_S: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), true); + + case BuiltinType::Char8: +return Builder.getIntegerType(8, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char16: +return Builder.getIntegerType(16, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char32: +return Builder.getIntegerType(32, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Int: + case BuiltinType::UInt: +return Builder.getIntegerType(ASTCtx.getIntWidth(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Int); + + case BuiltinType::Long: + case BuiltinType::ULong: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Long); + + case BuiltinType::LongLong: + case BuiltinType::ULongLong: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::LongLong); + + case BuiltinType::Int128: + case BuiltinType::UInt128: +return Builder.getIntegerType(128, getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Int128); + + case BuiltinType::Half: + case BuiltinType::Float16: +return Builder.getFloatType(llvm::APFloat::IEEEhalf(), +getTypeAlign(QualType(BT, 0))); + + case BuiltinType::Float: +return Builder.getFloatType(llvm::APFloat::IEEEsingle(), +getTypeAlign(QualType(BT, 0))); + + case BuiltinType::Double: +return Builder.getFloatType(llvm::APFloat::IEEEdouble(), +getTypeAlign(QualType(BT, 0))); + + case BuiltinType::LongDouble: +return Builder.getFloatType(ASTCtx.getFloatTypeSemantics(QualType(BT, 0)), +getTypeAlign(QualType(BT, 0))); + + case BuiltinType::BFloat16: +return Builder.getFloatType(llvm::APFloat::BFloat(), +getTypeAlign(QualType(BT, 0))); + + case BuiltinType::Float128: +return Builder.getFloatType(llvm::APFloat::IEEEquad(), +getTypeAlign(QualType(BT, 0))); nikic wrote: You can use `getFloatTypeSemantics()` instead for the FP types, it will correctly determine what these mean per target. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/c
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
nikic wrote: We should include the license file header in the newly created files: https://llvm.org/docs/CodingStandards.html#file-headers https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/kiranchandramohan edited https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
@@ -111,6 +111,13 @@ int main(int argc, const char **argv) { } } + llvm::StringSet<> SavedStrings; + // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the + // scenes. + if (const char *OverrideStr = ::getenv("FCC_OVERRIDE_OPTIONS")) kiranchandramohan wrote: ```suggestion if (const char *overrideStr = ::getenv("FCC_OVERRIDE_OPTIONS")) ``` https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
@@ -111,6 +111,13 @@ int main(int argc, const char **argv) { } } + llvm::StringSet<> SavedStrings; kiranchandramohan wrote: ```suggestion llvm::StringSet<> savedStrings; ``` https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/kiranchandramohan approved this pull request. LGTM. Thanks. https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,209 @@ +#include "clang/AST/RecordLayout.h" +#include "clang/AST/Type.h" +#include "clang/Analysis/Analyses/ThreadSafetyTIL.h" +#include "clang/Basic/LLVM.h" +#include "clang/Basic/TargetInfo.h" +#include "llvm/ABI/Types.h" +#include "llvm/Support/Alignment.h" +#include "llvm/Support/Casting.h" +#include + +namespace clang { +namespace mapper { + +const llvm::abi::Type *QualTypeMapper::convertType(QualType QT) { + QT = QT.getCanonicalType().getUnqualifiedType(); + + auto It = TypeCache.find(QT); + if (It != TypeCache.end()) +return It->second; + + const llvm::abi::Type *Result = nullptr; + if (const auto *BT = dyn_cast(QT.getTypePtr())) { +Result = convertBuiltinType(BT); + } else if (const auto *PT = dyn_cast(QT.getTypePtr())) { +Result = convertPointerType(PT); + } else if (const auto *AT = dyn_cast(QT.getTypePtr())) { +Result = convertArrayType(AT); + } else if (const auto *VT = dyn_cast(QT.getTypePtr())) { +Result = convertVectorType(VT); + } else if (const auto *RT = dyn_cast(QT.getTypePtr())) { +Result = convertRecordType(RT); + } else if (const auto *ET = dyn_cast(QT.getTypePtr())) { +Result = convertEnumType(ET); + } else { +// TODO: Write Fallback logic for unsupported types. + } + TypeCache[QT] = Result; + return Result; +} + +const llvm::abi::Type * +QualTypeMapper::convertBuiltinType(const BuiltinType *BT) { + switch (BT->getKind()) { + case BuiltinType::Void: +return Builder.getVoidType(); + + case BuiltinType::Bool: + case BuiltinType::UChar: + case BuiltinType::Char_U: + case BuiltinType::UShort: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char_S: + case BuiltinType::SChar: + case BuiltinType::Short: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), true); + + case BuiltinType::WChar_U: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::WChar_S: +return Builder.getIntegerType(ASTCtx.getCharWidth(), + getTypeAlign(QualType(BT, 0)), true); + + case BuiltinType::Char8: +return Builder.getIntegerType(8, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char16: +return Builder.getIntegerType(16, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Char32: +return Builder.getIntegerType(32, getTypeAlign(QualType(BT, 0)), false); + + case BuiltinType::Int: + case BuiltinType::UInt: +return Builder.getIntegerType(ASTCtx.getIntWidth(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Int); + + case BuiltinType::Long: + case BuiltinType::ULong: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Long); + + case BuiltinType::LongLong: + case BuiltinType::ULongLong: +return Builder.getIntegerType(ASTCtx.getTypeSize(QualType(BT, 0)), + getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::LongLong); + + case BuiltinType::Int128: + case BuiltinType::UInt128: +return Builder.getIntegerType(128, getTypeAlign(QualType(BT, 0)), + BT->getKind() == BuiltinType::Int128); nikic wrote: Can we cover all of these in one implementation (using just getTypeSize and something like isSignedInteger)? https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,260 @@ +#ifndef LLVM_ABI_TYPES_H +#define LLVM_ABI_TYPES_H + +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/Support/Alignment.h" +#include "llvm/Support/Allocator.h" +#include "llvm/Support/TypeSize.h" +#include +#include + +namespace llvm { +namespace abi { + +enum class TypeKind { + Void, + Integer, + Float, + Pointer, + Array, + Vector, + Struct, + Union, +}; + +class Type { +protected: + TypeKind Kind; + TypeSize SizeInBits; + Align AlignInBits; nikic wrote: Are you sure this one is InBits? That would be pretty unusual, because memory can't be bit-addressed anyway. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,78 @@ +#ifndef LLVM_ABI_QUALTYPE_MAPPER_H +#define LLVM_ABI_QUALTYPE_MAPPER_H nikic wrote: Outdated header guard. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,78 @@ +#ifndef LLVM_ABI_QUALTYPE_MAPPER_H +#define LLVM_ABI_QUALTYPE_MAPPER_H + +#include "llvm/IR/DerivedTypes.h" +#include "llvm/Support/Allocator.h" +#include +#include +#include +#include +#include + +// Specialization for QualType +template <> struct llvm::DenseMapInfo { nikic wrote: This already exists in clang/include/clang/AST/TypeOrdering.h. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,260 @@ +#ifndef LLVM_ABI_TYPES_H +#define LLVM_ABI_TYPES_H + +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/Support/Alignment.h" +#include "llvm/Support/Allocator.h" +#include "llvm/Support/TypeSize.h" +#include +#include nikic wrote: ```suggestion #include "llvm/IR/CallingConv.h" ``` https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
@@ -0,0 +1,78 @@ +#ifndef LLVM_ABI_QUALTYPE_MAPPER_H +#define LLVM_ABI_QUALTYPE_MAPPER_H + +#include "llvm/IR/DerivedTypes.h" +#include "llvm/Support/Allocator.h" +#include +#include +#include +#include +#include nikic wrote: Should always use `""` for non-system headers. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [WIP] ABI Lowering Library (PR #140112)
nikic wrote: I think this should be part of the clang/CodeGen library, not a new one. https://github.com/llvm/llvm-project/pull/140112 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
@@ -614,3 +614,30 @@ nvfortran defines `-fast` as - `-Mcache_align`: there is no equivalent flag in Flang or Clang. - `-Mflushz`: flush-to-zero mode - when `-ffast-math` is specified, Flang will link to `crtfastmath.o` to ensure denormal numbers are flushed to zero. + + +## FCC_OVERRIDE_OPTIONS + +The environment variable `FCC_OVERRIDE_OPTIONS` can be used to apply a list of +edits to the input argument lists. The value of this environment variable is +a space separated list of edits to perform. These edits are applied in order to +the input argument lists. Edits should be one of the following forms: abidh wrote: Thanks. This looks better than what I had originally. I have updated the docs. https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Log the paths of loaded config files without --log=verbose (PR #142063)
https://github.com/hokein approved this pull request. https://github.com/llvm/llvm-project/pull/142063 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Revert "[clangd] [Modules] Fixes to correctly handle module dependencies" (PR #142162)
llvmbot wrote: @llvm/pr-subscribers-clangd @llvm/pr-subscribers-clang-tools-extra Author: None (fleeting-xx) Changes Reverts llvm/llvm-project#142090 due to build failures on [arm64 windows](https://lab.llvm.org/buildbot/#/builders/161). I'll need someone with commit permission to apply this revert. --- Full diff: https://github.com/llvm/llvm-project/pull/142162.diff 3 Files Affected: - (modified) clang-tools-extra/clangd/ModulesBuilder.cpp (+13-14) - (removed) clang-tools-extra/clangd/test/module_dependencies.test (-92) - (modified) clang-tools-extra/clangd/test/modules.test (+5-5) ``diff diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp index 786fb88dbe318..bf77f43bd28bb 100644 --- a/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -84,7 +84,8 @@ class FailedPrerequisiteModules : public PrerequisiteModules { // We shouldn't adjust the compilation commands based on // FailedPrerequisiteModules. - void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {} + void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override { + } // FailedPrerequisiteModules can never be reused. bool @@ -429,21 +430,21 @@ class CachingProjectModules : public ProjectModules { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, - CachingProjectModules &MDB, - StringRef ModuleName) { - llvm::SmallVector ModuleNames; +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + CachingProjectModules &MDB, + StringRef ModuleName) { + llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { ModuleNamesSet.insert(ModuleName); -for (const std::string &RequiredModuleName : MDB.getRequiredModules( +for (StringRef RequiredModuleName : MDB.getRequiredModules( MDB.getSourceForModuleName(ModuleName, RequiredSource))) if (ModuleNamesSet.insert(RequiredModuleName).second) Visitor(RequiredModuleName, Visitor); -ModuleNames.push_back(ModuleName.str()); +ModuleNames.push_back(ModuleName); }; VisitDeps(ModuleName, VisitDeps); @@ -493,13 +494,13 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( // Get Required modules in topological order. auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName); for (llvm::StringRef ReqModuleName : ReqModuleNames) { -if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName)) +if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName)) continue; if (auto Cached = Cache.getModule(ReqModuleName)) { if (IsModuleFileUpToDate(Cached->getModuleFilePath(), BuiltModuleFiles, TFS.view(std::nullopt))) { -log("Reusing module {0} from {1}", ReqModuleName, +log("Reusing module {0} from {1}", ModuleName, Cached->getModuleFilePath()); BuiltModuleFiles.addModuleFile(std::move(Cached)); continue; @@ -507,16 +508,14 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( Cache.remove(ReqModuleName); } -std::string ReqFileName = -MDB.getSourceForModuleName(ReqModuleName, RequiredSource); llvm::Expected MF = buildModuleFile( -ReqModuleName, ReqFileName, getCDB(), TFS, BuiltModuleFiles); +ModuleName, ModuleUnitFileName, getCDB(), TFS, BuiltModuleFiles); if (llvm::Error Err = MF.takeError()) return Err; -log("Built module {0} to {1}", ReqModuleName, MF->getModuleFilePath()); +log("Built module {0} to {1}", ModuleName, MF->getModuleFilePath()); auto BuiltModuleFile = std::make_shared(std::move(*MF)); -Cache.add(ReqModuleName, BuiltModuleFile); +Cache.add(ModuleName, BuiltModuleFile); BuiltModuleFiles.addModuleFile(std::move(BuiltModuleFile)); } diff --git a/clang-tools-extra/clangd/test/module_dependencies.test b/clang-tools-extra/clangd/test/module_dependencies.test deleted file mode 100644 index ee1df7f8a35cc..0 --- a/clang-tools-extra/clangd/test/module_dependencies.test +++ /dev/null @@ -1,92 +0,0 @@ -# A smoke test to check that a simple dependency chain for modules can work. -# -# RUN: rm -fr %t -# RUN: mkdir -p %t -# RUN: split-file %s %t -# -# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp -# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json -#
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
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 HEAD~1 HEAD --extensions cpp,c -- clang/lib/Serialization/ASTReader.cpp clang/test/Modules/module-file-modified.c `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 565f01221..521d8f88d 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2877,7 +2877,7 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { << *Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) Diag(diag::note_ast_file_required_by) -<< ImportStack[I-1]->FileName << ImportStack[I]->FileName; + << ImportStack[I - 1]->FileName << ImportStack[I]->FileName; } Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName; `` https://github.com/llvm/llvm-project/pull/142161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] add tags to Mustache namespace template (PR #142045)
@@ -0,0 +1,13 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/MyNamespace/index.html + +namespace MyNamespace { + class Foo; +} + +// CHECK: +// CHECK-NEXT: +// CHECK-NEXT:class Foo +// CHECK-NEXT: +// CHECK-NEXT: evelez7 wrote: Yes, a separate namespace generates a new folder and index.html. Any records declared inside of that namespace get put in the same folder as a separate HTML file. So this test also generates an empty `GlobalNamespace/index.html` since nested namespaces aren't rendered. https://github.com/llvm/llvm-project/pull/142045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [Modules] Fixes to correctly handle module dependencies (PR #142090)
@@ -430,21 +429,21 @@ class CachingProjectModules : public ProjectModules { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, - CachingProjectModules &MDB, - StringRef ModuleName) { - llvm::SmallVector ModuleNames; +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + CachingProjectModules &MDB, + StringRef ModuleName) { + llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { ModuleNamesSet.insert(ModuleName); -for (StringRef RequiredModuleName : MDB.getRequiredModules( +for (const std::string &RequiredModuleName : MDB.getRequiredModules( fleeting-xx wrote: I'll change this back to a `StringRef` when I resubmit this after the arm64 build issues are resolved. https://github.com/llvm/llvm-project/pull/142090 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream (PR #142163)
https://github.com/Michael137 created https://github.com/llvm/llvm-project/pull/142163 We're planning on using the ASTPrinter in LLDB for AST dumping. But it currently takes the output stream via `unique_ptr`. In LLDB we don't have the output stream available in this form and instead it would be convenient if we could just pass a reference to the stream. This patch adds that overload. >From 9bd15ee7ed44adc836bcd07ff7e856d7a32ba6a9 Mon Sep 17 00:00:00 2001 From: Michael Buch Date: Fri, 30 May 2025 15:44:09 +0100 Subject: [PATCH] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream We're planning on using the ASTPrinter in LLDB for AST dumping. But it currently takes the output stream via `unique_ptr`. In LLDB we don't have the output stream available in this form and instead it would be convenient if we could just pass a reference to the stream. This patch adds that overload. --- clang/include/clang/Frontend/ASTConsumers.h | 5 + clang/lib/Frontend/ASTConsumers.cpp | 20 2 files changed, 25 insertions(+) diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index 0e068bf5cccb5..890701b6ff188 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -35,6 +35,11 @@ CreateASTDumper(std::unique_ptr OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format); +std::unique_ptr +CreateASTDumper(raw_ostream &OS, StringRef FilterString, bool DumpDecls, +bool Deserialize, bool DumpLookups, bool DumpDeclTypes, +ASTDumpOutputFormat Format); + // AST Decl node lister: prints qualified names of all filterable AST Decl // nodes. std::unique_ptr CreateASTDeclNodeLister(); diff --git a/clang/lib/Frontend/ASTConsumers.cpp b/clang/lib/Frontend/ASTConsumers.cpp index a6e35452b4fbe..a5ff4d44592d4 100644 --- a/clang/lib/Frontend/ASTConsumers.cpp +++ b/clang/lib/Frontend/ASTConsumers.cpp @@ -41,6 +41,13 @@ namespace { OutputKind(K), OutputFormat(Format), FilterString(FilterString), DumpLookups(DumpLookups), DumpDeclTypes(DumpDeclTypes) {} +ASTPrinter(raw_ostream &Out, Kind K, ASTDumpOutputFormat Format, + StringRef FilterString, bool DumpLookups = false, + bool DumpDeclTypes = false) +: Out(Out), OwnedOut(nullptr), OutputKind(K), OutputFormat(Format), + FilterString(FilterString), DumpLookups(DumpLookups), + DumpDeclTypes(DumpDeclTypes) {} + void HandleTranslationUnit(ASTContext &Context) override { TranslationUnitDecl *D = Context.getTranslationUnitDecl(); @@ -176,6 +183,19 @@ clang::CreateASTDumper(std::unique_ptr Out, StringRef FilterString, Format, FilterString, DumpLookups, DumpDeclTypes); } +std::unique_ptr +clang::CreateASTDumper(raw_ostream &Out, StringRef FilterString, bool DumpDecls, + bool Deserialize, bool DumpLookups, bool DumpDeclTypes, + ASTDumpOutputFormat Format) { + assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump"); + return std::make_unique(Out, + Deserialize ? ASTPrinter::DumpFull + : DumpDecls ? ASTPrinter::Dump + : ASTPrinter::None, + Format, FilterString, DumpLookups, + DumpDeclTypes); +} + std::unique_ptr clang::CreateASTDeclNodeLister() { return std::make_unique(nullptr); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream (PR #142163)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Michael Buch (Michael137) Changes We're planning on using the ASTPrinter in LLDB for AST dumping. But it currently takes the output stream via `unique_ptr`. In LLDB we don't have the output stream available in this form and instead it would be convenient if we could just pass a reference to the stream. This patch adds that overload. --- Full diff: https://github.com/llvm/llvm-project/pull/142163.diff 2 Files Affected: - (modified) clang/include/clang/Frontend/ASTConsumers.h (+5) - (modified) clang/lib/Frontend/ASTConsumers.cpp (+20) ``diff diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index 0e068bf5cccb5..890701b6ff188 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -35,6 +35,11 @@ CreateASTDumper(std::unique_ptr OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format); +std::unique_ptr +CreateASTDumper(raw_ostream &OS, StringRef FilterString, bool DumpDecls, +bool Deserialize, bool DumpLookups, bool DumpDeclTypes, +ASTDumpOutputFormat Format); + // AST Decl node lister: prints qualified names of all filterable AST Decl // nodes. std::unique_ptr CreateASTDeclNodeLister(); diff --git a/clang/lib/Frontend/ASTConsumers.cpp b/clang/lib/Frontend/ASTConsumers.cpp index a6e35452b4fbe..a5ff4d44592d4 100644 --- a/clang/lib/Frontend/ASTConsumers.cpp +++ b/clang/lib/Frontend/ASTConsumers.cpp @@ -41,6 +41,13 @@ namespace { OutputKind(K), OutputFormat(Format), FilterString(FilterString), DumpLookups(DumpLookups), DumpDeclTypes(DumpDeclTypes) {} +ASTPrinter(raw_ostream &Out, Kind K, ASTDumpOutputFormat Format, + StringRef FilterString, bool DumpLookups = false, + bool DumpDeclTypes = false) +: Out(Out), OwnedOut(nullptr), OutputKind(K), OutputFormat(Format), + FilterString(FilterString), DumpLookups(DumpLookups), + DumpDeclTypes(DumpDeclTypes) {} + void HandleTranslationUnit(ASTContext &Context) override { TranslationUnitDecl *D = Context.getTranslationUnitDecl(); @@ -176,6 +183,19 @@ clang::CreateASTDumper(std::unique_ptr Out, StringRef FilterString, Format, FilterString, DumpLookups, DumpDeclTypes); } +std::unique_ptr +clang::CreateASTDumper(raw_ostream &Out, StringRef FilterString, bool DumpDecls, + bool Deserialize, bool DumpLookups, bool DumpDeclTypes, + ASTDumpOutputFormat Format) { + assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump"); + return std::make_unique(Out, + Deserialize ? ASTPrinter::DumpFull + : DumpDecls ? ASTPrinter::Dump + : ASTPrinter::None, + Format, FilterString, DumpLookups, + DumpDeclTypes); +} + std::unique_ptr clang::CreateASTDeclNodeLister() { return std::make_unique(nullptr); } `` https://github.com/llvm/llvm-project/pull/142163 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Revert "[clangd] [Modules] Fixes to correctly handle module dependencies" (PR #142162)
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 HEAD~1 HEAD --extensions cpp -- clang-tools-extra/clangd/ModulesBuilder.cpp `` View the diff from clang-format here. ``diff diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp index bf77f43bd..8a54b70a2 100644 --- a/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -84,8 +84,7 @@ public: // We shouldn't adjust the compilation commands based on // FailedPrerequisiteModules. - void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override { - } + void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {} // FailedPrerequisiteModules can never be reused. bool `` https://github.com/llvm/llvm-project/pull/142162 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [DebugInfo] Place local ODR-uniqued types in decl DISubprograms (PR #142166)
https://github.com/dzhidzhoev created https://github.com/llvm/llvm-project/pull/142166 This commit was split from https://github.com/llvm/llvm-project/pull/119001 commit chain after the discussion with @jmorse. It can be merged before the fixed version of https://github.com/llvm/llvm-project/pull/75385, which will help to track down issues if they pop up after the merge. The original commit message follows: There are two flavours of DISubprogram: declarations, which are unique'd and abstractly describe the function in question. There are also definition DISubprograms which correspond to real instances, some of which are inlined, duplicated across translation units in LTO, or otherwise can have multiple instances. Given that LLVM sometimes force-uniques types by their ODR-name, see the enableDebugTypeODRUniquing feature, we shouldn't place types that might be unique'd into duplicated contexts like definition DISubprograms. Instead, place them into the declaration. This slightly bends the existing approach where only functions that have a separate declaratrion to their definition get a declaration-DISubprogram. A single function in a translation unit might now get a declaration where it didn't before, if it contains an ODR-unique'd type declaration. This seems reasonable given that the LLVM idea of a declaration doesn't have to exactly match source-language ideas. The added cpp test checks that such ORD-unique'd types are detected and placed in the declaration DISubprogram, creating one if necessary. The IR test ensures that nothing changes after a round-trip with enableDebugTypeODRUniquing turned on. >From a9dce227053e7e58293e10020ed2dfe300aa55f1 Mon Sep 17 00:00:00 2001 From: Jeremy Morse Date: Thu, 5 Dec 2024 10:30:17 + Subject: [PATCH] [DebugInfo] Place local ODR-uniqued types in decl DISubprograms There are two flavours of DISubprogram: declarations, which are unique'd and abstractly describe the function in question. There are also definition DISubprograms which correspond to real instances, some of which are inlined, duplicated across translation units in LTO, or otherwise can have multiple instances. Given that LLVM sometimes force-uniques types by their ODR-name, see the enableDebugTypeODRUniquing feature, we shouldn't place types that might be unique'd into duplicated contexts like definition DISubprograms. Instead, place them into the declaration. This slightly bends the existing approach where only functions that have a separate declaratrion to their definition get a declaration-DISubprogram. A single function in a translation unit might now get a declaration where it didn't before, if it contains an ODR-unique'd type declaration. This seems reasonable given that the LLVM idea of a declaration doesn't have to exactly match source-language ideas. The added cpp test checks that such ORD-unique'd types are detected and placed in the declaration DISubprogram, creating one if necessary. The IR test ensures that nothing changes after a round-trip with enableDebugTypeODRUniquing turned on. --- clang/lib/CodeGen/CGDebugInfo.cpp | 56 +++- clang/lib/CodeGen/CGDebugInfo.h | 6 + .../CodeGenCXX/debug-info-local-types.cpp | 79 +++ .../DebugInfo/local-odr-types-hierarchy.ll| 124 ++ 4 files changed, 264 insertions(+), 1 deletion(-) create mode 100644 clang/test/CodeGenCXX/debug-info-local-types.cpp create mode 100644 llvm/test/DebugInfo/local-odr-types-hierarchy.ll diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 5772c07154144..5d82717de2910 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1353,6 +1353,7 @@ CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, // Don't include a linkage name in line tables only. if (CGM.getCodeGenOpts().hasReducedDebugInfo()) Identifier = getTypeIdentifier(Ty, CGM, TheCU); + Ctx = PickCompositeTypeScope(Ctx, Identifier); llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags, Identifier); @@ -3718,6 +3719,7 @@ llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { // FwdDecl with the second and then replace the second with // complete type. llvm::DIScope *EDContext = getDeclContextDescriptor(ED); +EDContext = PickCompositeTypeScope(EDContext, Identifier); llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0)); @@ -3765,7 +3767,7 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); unsigned Line = getLineNumber(ED->getLocation()); - llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); + llvm
[clang] [flang] [llvm] Add IR Profile-Guided Optimization (IR PGO) support to the Flang compiler (PR #136098)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `amdgpu-offload-ubuntu-22-cmake-build-only` running on `rocm-docker-ubu-22` while building `clang,flang,llvm` at step 4 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/203/builds/12089 Here is the relevant piece of the build log for the reference ``` Step 4 (annotate) failure: '../llvm-zorg/zorg/buildbot/builders/annotated/amdgpu-offload-cmake.py --jobs=32' (failure) ... [4788/7836] Linking CXX shared library lib/libMLIRNVGPUDialect.so.21.0git [4789/7836] Linking CXX shared library lib/libMLIRShardingInterface.so.21.0git [4790/7836] Linking CXX shared library lib/libMLIRArithToEmitC.so.21.0git [4791/7836] Linking CXX shared library lib/libLLVMIRPrinter.so.21.0git [4792/7836] Linking CXX shared library lib/libMLIRBufferizationDialect.so.21.0git [4793/7836] Linking CXX shared library lib/libLLVMFrontendAtomic.so.21.0git [4794/7836] Creating library symlink lib/libMLIRArithToEmitC.so [4795/7836] Creating library symlink lib/libLLVMIRPrinter.so [4796/7836] Creating library symlink lib/libLLVMFrontendAtomic.so [4797/7836] Linking CXX shared library lib/libLLVMFrontendDriver.so.21.0git FAILED: lib/libLLVMFrontendDriver.so.21.0git : && /usr/bin/c++ -fPIC -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -O3 -DNDEBUG -Wl,-z,defs -Wl,-z,nodelete -Wl,-rpath-link,/home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/build/./lib -Wl,--gc-sections -shared -Wl,-soname,libLLVMFrontendDriver.so.21.0git -o lib/libLLVMFrontendDriver.so.21.0git lib/Frontend/Driver/CMakeFiles/LLVMFrontendDriver.dir/CodeGenOptions.cpp.o -Wl,-rpath,"\$ORIGIN/../lib:/home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/build/lib:" lib/libLLVMAnalysis.so.21.0git lib/libLLVMCore.so.21.0git lib/libLLVMSupport.so.21.0git -Wl,-rpath-link,/home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/build/lib && : /usr/bin/ld: lib/Frontend/Driver/CMakeFiles/LLVMFrontendDriver.dir/CodeGenOptions.cpp.o: in function `llvm::driver::getDefaultProfileGenName[abi:cxx11]()': CodeGenOptions.cpp:(.text._ZN4llvm6driver24getDefaultProfileGenNameB5cxx11Ev+0x7): undefined reference to `llvm::DebugInfoCorrelate' /usr/bin/ld: CodeGenOptions.cpp:(.text._ZN4llvm6driver24getDefaultProfileGenNameB5cxx11Ev+0x25): undefined reference to `llvm::ProfileCorrelate' collect2: error: ld returned 1 exit status [4798/7836] Creating library symlink lib/libMLIRTensorUtils.so [4799/7836] Creating library symlink lib/libMLIRBufferizationDialect.so [4800/7836] Creating library symlink lib/libMLIRShardingInterface.so [4801/7836] Linking CXX shared library lib/libLLVMBitWriter.so.21.0git [4802/7836] Linking CXX shared library lib/libMLIRSCFDialect.so.21.0git [4803/7836] Linking CXX shared library lib/libLLVMTarget.so.21.0git [4804/7836] Building CXX object tools/mlir/test/lib/Dialect/TestIRDLToCpp/CMakeFiles/MLIRTestIRDLToCppDialect.dir/TestIRDLToCppDialect.cpp.o In file included from /usr/include/c++/11/cassert:44, from /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/llvm-project/llvm/include/llvm/IR/ProfileSummary.h:17, from /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/llvm-project/llvm/include/llvm/IR/Module.h:30, from /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/llvm-project/mlir/include/mlir/Dialect/LLVMIR/LLVMDialect.h:38, from /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/llvm-project/mlir/include/mlir/Target/LLVMIR/LLVMTranslationInterface.h:16, from /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/llvm-project/mlir/test/lib/Dialect/TestIRDLToCpp/TestIRDLToCppDialect.cpp:22: /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/build/tools/mlir/test/lib/Dialect/TestIRDLToCpp/test_irdl_to_cpp.irdl.mlir.cpp.inc: In static member function ‘static llvm::StringRef mlir::test_irdl_to_cpp::BarOp::getOperandName(unsigned int)’: /home/botworker/bbot/amdgpu-offload-ubuntu-22-cmake-build-only/build/tools/mlir/test/lib/Dialect/TestIRDLToCpp/test_irdl_to_cpp.irdl.mlir.cpp.inc:223:18: warning: comparison of unsigned expression in ‘< 0’ is always false [-Wtype-limits] 223 | assert(index < 0 && "invalid attribute index"); |~~^~~ [4805/7836] Linking CXX shared library lib/libMLIRShapeDialect.so.21.0git [4806/7836] Linking CXX shared library lib/libLLVMSandboxIR.so.21.0git [4807
[clang] [llvm] [DebugInfo] Place local ODR-uniqued types in decl DISubprograms (PR #142166)
llvmbot wrote: @llvm/pr-subscribers-debuginfo Author: Vladislav Dzhidzhoev (dzhidzhoev) Changes This commit was split from https://github.com/llvm/llvm-project/pull/119001 commit chain after the discussion with @jmorse. It can be merged before the fixed version of https://github.com/llvm/llvm-project/pull/75385, which will help to track down issues if they pop up after the merge. The original commit message follows: There are two flavours of DISubprogram: declarations, which are unique'd and abstractly describe the function in question. There are also definition DISubprograms which correspond to real instances, some of which are inlined, duplicated across translation units in LTO, or otherwise can have multiple instances. Given that LLVM sometimes force-uniques types by their ODR-name, see the enableDebugTypeODRUniquing feature, we shouldn't place types that might be unique'd into duplicated contexts like definition DISubprograms. Instead, place them into the declaration. This slightly bends the existing approach where only functions that have a separate declaratrion to their definition get a declaration-DISubprogram. A single function in a translation unit might now get a declaration where it didn't before, if it contains an ODR-unique'd type declaration. This seems reasonable given that the LLVM idea of a declaration doesn't have to exactly match source-language ideas. The added cpp test checks that such ORD-unique'd types are detected and placed in the declaration DISubprogram, creating one if necessary. The IR test ensures that nothing changes after a round-trip with enableDebugTypeODRUniquing turned on. --- Full diff: https://github.com/llvm/llvm-project/pull/142166.diff 4 Files Affected: - (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+55-1) - (modified) clang/lib/CodeGen/CGDebugInfo.h (+6) - (added) clang/test/CodeGenCXX/debug-info-local-types.cpp (+79) - (added) llvm/test/DebugInfo/local-odr-types-hierarchy.ll (+124) ``diff diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 5772c07154144..5d82717de2910 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -1353,6 +1353,7 @@ CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, // Don't include a linkage name in line tables only. if (CGM.getCodeGenOpts().hasReducedDebugInfo()) Identifier = getTypeIdentifier(Ty, CGM, TheCU); + Ctx = PickCompositeTypeScope(Ctx, Identifier); llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags, Identifier); @@ -3718,6 +3719,7 @@ llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { // FwdDecl with the second and then replace the second with // complete type. llvm::DIScope *EDContext = getDeclContextDescriptor(ED); +EDContext = PickCompositeTypeScope(EDContext, Identifier); llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0)); @@ -3765,7 +3767,7 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); unsigned Line = getLineNumber(ED->getLocation()); - llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); + llvm::DIScope *EnumContext = PickCompositeTypeScope(getDeclContextDescriptor(ED), Identifier); llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit); return DBuilder.createEnumerationType( EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy, @@ -4097,6 +4099,57 @@ CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) { return Res; } +llvm::DIScope *CGDebugInfo::PickCompositeTypeScope(llvm::DIScope *S, + StringRef Identifier) { + using llvm::DISubprogram; + + // Only adjust the scope for composite types placed into functions. + if (!isa(S)) +return S; + + // We must adjust the scope if the ODR-name of the type is set. + if (Identifier.empty()) +return S; + + // This type has an ODR-name, and might be de-duplicated during LTO. It needs + // to be placed in the unique declaration of the function, not a (potentially + // duplicated) definition. + DISubprogram *SP = cast(S); + if (DISubprogram *Decl = SP->getDeclaration()) +return Decl; + + // There is no declaration -- we must produce one and retrofit it to the + // existing definition. Assume that we can just harvest the existing + // information, clear the definition flag and set as decl. + DISubprogram::DISPFlags SPFlags = SP->getSPFlags(); + SPFlags &= ~DISubprogram::SPFlagDefinition; + + llvm::DINode::DIFlags Flags = SP->getFlags(); + Flags &= ~llvm::DINode::FlagAllCallsDescribed; + +#ifdef EXPENSIVE_CHE
[clang] [Clang] Improve infrastructure for libstdc++ workarounds (PR #141977)
@@ -979,3 +979,50 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro, return EvaluateDirectiveExpression(IfNDefMacro, Tok, EvaluatedDefined, CheckForEoD); } + +static std::optional +getCXXStandardLibraryVersion(Preprocessor &PP, StringRef MacroName, + CXXStandardLibraryVersionInfo::Library Lib) { + MacroInfo *Macro = PP.getMacroInfo(PP.getIdentifierInfo(MacroName)); + + if (!Macro || Macro->getNumTokens() != 1) erichkeane wrote: Should we also check `isObjectLike` here too? https://github.com/llvm/llvm-project/pull/141977 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-reorder-fields] Support designated initializers (PR #142150)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Vladimir Vuksanovic (vvuksanovic) Changes Initializer lists with designators, missing elements or omitted braces can now be rewritten. Any missing designators are added and they get sorted according to the new order. ``` struct Foo { int a; int b; int c; }; struct Foo foo = { .a = 1, 2, 3 } ``` when reordering elements to "b,a,c" becomes: ``` struct Foo { int b; int a; int c; }; struct Foo foo = { .b = 2, .a = 1, .c = 3 } ``` --- Patch is 34.11 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/142150.diff 5 Files Affected: - (modified) clang-tools-extra/clang-reorder-fields/CMakeLists.txt (+1) - (modified) clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp (+253-48) - (added) clang-tools-extra/clang-reorder-fields/utils/Designator.cpp (+256) - (added) clang-tools-extra/clang-reorder-fields/utils/Designator.h (+118) - (added) clang-tools-extra/test/clang-reorder-fields/DesignatedInitializerList.c (+31) ``diff diff --git a/clang-tools-extra/clang-reorder-fields/CMakeLists.txt b/clang-tools-extra/clang-reorder-fields/CMakeLists.txt index 2fdeb65d89767..dfb28234fd548 100644 --- a/clang-tools-extra/clang-reorder-fields/CMakeLists.txt +++ b/clang-tools-extra/clang-reorder-fields/CMakeLists.txt @@ -4,6 +4,7 @@ set(LLVM_LINK_COMPONENTS ) add_clang_library(clangReorderFields STATIC + utils/Designator.cpp ReorderFieldsAction.cpp DEPENDS diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index ea0207619fb2b..f5961a7dab0c9 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -13,6 +13,7 @@ //===--===// #include "ReorderFieldsAction.h" +#include "utils/Designator.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" @@ -23,6 +24,7 @@ #include "clang/Tooling/Refactoring.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" +#include "llvm/Support/ErrorHandling.h" #include namespace clang { @@ -81,7 +83,44 @@ getNewFieldsOrder(const RecordDecl *Definition, return NewFieldsOrder; } +struct ReorderedStruct { +public: + ReorderedStruct(const RecordDecl *Decl, ArrayRef NewFieldsOrder) + : Definition(Decl), NewFieldsOrder(NewFieldsOrder), +NewFieldsPositions(NewFieldsOrder.size()) { +for (unsigned I = 0; I < NewFieldsPositions.size(); ++I) + NewFieldsPositions[NewFieldsOrder[I]] = I; + } + + const RecordDecl *Definition; + ArrayRef NewFieldsOrder; + SmallVector NewFieldsPositions; +}; + // FIXME: error-handling +/// Replaces a range of source code by the specified text. +static void +addReplacement(SourceRange Old, StringRef New, const ASTContext &Context, + std::map &Replacements) { + tooling::Replacement R(Context.getSourceManager(), + CharSourceRange::getTokenRange(Old), New, + Context.getLangOpts()); + consumeError(Replacements[std::string(R.getFilePath())].add(R)); +} + +/// Replaces one range of source code by another and adds a prefix. +static void +addReplacement(SourceRange Old, SourceRange New, StringRef Prefix, + const ASTContext &Context, + std::map &Replacements) { + std::string NewText = + (Prefix + Lexer::getSourceText(CharSourceRange::getTokenRange(New), + Context.getSourceManager(), + Context.getLangOpts())) + .str(); + addReplacement(Old, NewText, Context, Replacements); +} + /// Replaces one range of source code by another. static void addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, @@ -89,10 +128,7 @@ addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, StringRef NewText = Lexer::getSourceText(CharSourceRange::getTokenRange(New), Context.getSourceManager(), Context.getLangOpts()); - tooling::Replacement R(Context.getSourceManager(), - CharSourceRange::getTokenRange(Old), NewText, - Context.getLangOpts()); - consumeError(Replacements[std::string(R.getFilePath())].add(R)); + addReplacement(Old, NewText.str(), Context, Replacements); } /// Find all member fields used in the given init-list initializer expr @@ -194,33 +230,33 @@ static SourceRange getFullFieldSourceRange(const FieldDecl &Field, /// different accesses (public/protected/private) is not supported. /// \returns true on success. static bool reorderFieldsInDefinition( -const RecordDecl *Definition, ArrayRef NewFieldsOrder, -const ASTContext &Context, +const ReorderedStruct &RS, cons
[clang-tools-extra] [clang-reorder-fields] Prevent rewriting unsupported cases (PR #142149)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Vladimir Vuksanovic (vvuksanovic) Changes Add checks to prevent rewriting when doing so might result in incorrect code. The following cases are checked: - There are multiple field declarations in one statement like `int a, b` - Multiple fields are created from a single macro expansion - Preprocessor directives are present in the struct --- Full diff: https://github.com/llvm/llvm-project/pull/142149.diff 4 Files Affected: - (modified) clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp (+51) - (added) clang-tools-extra/test/clang-reorder-fields/MacroExpandsToMultipleFields.cpp (+13) - (added) clang-tools-extra/test/clang-reorder-fields/MultipleFieldDeclsInStatement.cpp (+11) - (added) clang-tools-extra/test/clang-reorder-fields/PreprocessorDirectiveInDefinition.cpp (+16) ``diff diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index ea0207619fb2b..245da5e3433c5 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -50,6 +50,55 @@ static const RecordDecl *findDefinition(StringRef RecordName, return selectFirst("recordDecl", Results); } +static bool isSafeToRewrite(const RecordDecl *Decl, const ASTContext &Context) { + // Don't attempt to rewrite if there is a declaration like 'int a, b;'. + SourceLocation LastTypeLoc; + for (const auto &Field : Decl->fields()) { +SourceLocation TypeLoc = +Field->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); +if (LastTypeLoc.isValid() && TypeLoc == LastTypeLoc) + return false; +LastTypeLoc = TypeLoc; + } + + // Don't attempt to rewrite if a single macro expansion creates multiple + // fields. + SourceLocation LastMacroLoc; + for (const auto &Field : Decl->fields()) { +if (!Field->getLocation().isMacroID()) + continue; +SourceLocation MacroLoc = +Context.getSourceManager().getExpansionLoc(Field->getLocation()); +if (LastMacroLoc.isValid() && MacroLoc == LastMacroLoc) + return false; +LastMacroLoc = MacroLoc; + } + + // Skip if there are preprocessor directives present. + const SourceManager &SM = Context.getSourceManager(); + std::pair FileAndOffset = + SM.getDecomposedLoc(Decl->getSourceRange().getBegin()); + unsigned EndOffset = SM.getFileOffset(Decl->getSourceRange().getEnd()); + StringRef SrcBuffer = SM.getBufferData(FileAndOffset.first); + Lexer L(SM.getLocForStartOfFile(FileAndOffset.first), Context.getLangOpts(), + SrcBuffer.data(), SrcBuffer.data() + FileAndOffset.second, + SrcBuffer.data() + SrcBuffer.size()); + IdentifierTable Identifiers(Context.getLangOpts()); + clang::Token T; + while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < EndOffset) { +if (T.getKind() == tok::hash) { + L.LexFromRawLexer(T); + if (T.getKind() == tok::raw_identifier) { +clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier()); +if (II.getPPKeywordID() != clang::tok::pp_not_keyword) + return false; + } +} + } + + return true; +} + /// Calculates the new order of fields. /// /// \returns empty vector if the list of fields doesn't match the definition. @@ -341,6 +390,8 @@ class ReorderingConsumer : public ASTConsumer { const RecordDecl *RD = findDefinition(RecordName, Context); if (!RD) return; +if (!isSafeToRewrite(RD, Context)) + return; SmallVector NewFieldsOrder = getNewFieldsOrder(RD, DesiredFieldsOrder); if (NewFieldsOrder.empty()) diff --git a/clang-tools-extra/test/clang-reorder-fields/MacroExpandsToMultipleFields.cpp b/clang-tools-extra/test/clang-reorder-fields/MacroExpandsToMultipleFields.cpp new file mode 100644 index 0..5bafcd19ea829 --- /dev/null +++ b/clang-tools-extra/test/clang-reorder-fields/MacroExpandsToMultipleFields.cpp @@ -0,0 +1,13 @@ +// RUN: clang-reorder-fields -record-name ::bar::Foo -fields-order z,y,x %s -- | FileCheck %s + +namespace bar { + +#define FIELDS_DECL int x; int y; // CHECK: {{^#define FIELDS_DECL int x; int y;}} + +// The order of fields should not change. +struct Foo { + FIELDS_DECL // CHECK: {{^ FIELDS_DECL}} + int z; // CHECK-NEXT: {{^ int z;}} +}; + +} // end namespace bar diff --git a/clang-tools-extra/test/clang-reorder-fields/MultipleFieldDeclsInStatement.cpp b/clang-tools-extra/test/clang-reorder-fields/MultipleFieldDeclsInStatement.cpp new file mode 100644 index 0..437e7b91e27a3 --- /dev/null +++ b/clang-tools-extra/test/clang-reorder-fields/MultipleFieldDeclsInStatement.cpp @@ -0,0 +1,11 @@ +// RUN: clang-reorder-fields -record-name ::bar::Foo -fields-order z,y,x %s -- | FileCheck %s + +namespace bar { + +// The order of fields should not change. +struct Foo { + int x, y; // CHECK: {{^
[clang] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream (PR #142163)
https://github.com/AaronBallman approved this pull request. LGTM! https://github.com/llvm/llvm-project/pull/142163 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [DebugInfo] Place local ODR-uniqued types in decl DISubprograms (PR #142166)
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 HEAD~1 HEAD --extensions cpp,h -- clang/test/CodeGenCXX/debug-info-local-types.cpp clang/lib/CodeGen/CGDebugInfo.cpp clang/lib/CodeGen/CGDebugInfo.h `` View the diff from clang-format here. ``diff diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 5d82717de..5d435ff1e 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -3767,7 +3767,8 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation()); unsigned Line = getLineNumber(ED->getLocation()); - llvm::DIScope *EnumContext = PickCompositeTypeScope(getDeclContextDescriptor(ED), Identifier); + llvm::DIScope *EnumContext = + PickCompositeTypeScope(getDeclContextDescriptor(ED), Identifier); llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit); return DBuilder.createEnumerationType( EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy, `` https://github.com/llvm/llvm-project/pull/142166 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [Modules] Fixes to correctly handle module dependencies (PR #142090)
fleeting-xx wrote: Thank you @ChuanqiXu9 for the review. Looks like this is causing failures on [arm64 windows builds](https://lab.llvm.org/buildbot/#/builders/161). Not quite sure why. Relevant log contains: ``` # | I[14:07:36.383] Built preamble of size 842464 for file C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\build\tools\clang\tools\extra\clangd\test\Output\modules.test.tmp\Use.cpp version 1 in 0.02 seconds # | E[14:07:36.414] Failed to build module A; due to Don't get the module unit for module A ``` Going to revert this. I'll see if I can load up a Microsoft Surface I have access to with development tools and investigate. Until I can do so I'll go ahead and revert the change. https://github.com/llvm/llvm-project/pull/142090 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Revert "[clangd] [Modules] Fixes to correctly handle module dependencies" (PR #142162)
https://github.com/fleeting-xx created https://github.com/llvm/llvm-project/pull/142162 Reverts llvm/llvm-project#142090 due to build failures on [arm64 windows](https://lab.llvm.org/buildbot/#/builders/161). I'll need someone with commit permission to apply this revert. >From 39fe26a200155bad4992bcc6f430ffa5b4cace77 Mon Sep 17 00:00:00 2001 From: fleeting-xx Date: Fri, 30 May 2025 09:42:33 -0500 Subject: [PATCH] =?UTF-8?q?Revert=20"[clangd]=20[Modules]=20Fixes=20to=20c?= =?UTF-8?q?orrectly=20handle=20module=20dependencies=20(#14=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit d490526a81586c7b2fe674ce520276570c9881e2. --- clang-tools-extra/clangd/ModulesBuilder.cpp | 27 +++--- .../clangd/test/module_dependencies.test | 92 --- clang-tools-extra/clangd/test/modules.test| 10 +- 3 files changed, 18 insertions(+), 111 deletions(-) delete mode 100644 clang-tools-extra/clangd/test/module_dependencies.test diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp index 786fb88dbe318..bf77f43bd28bb 100644 --- a/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -84,7 +84,8 @@ class FailedPrerequisiteModules : public PrerequisiteModules { // We shouldn't adjust the compilation commands based on // FailedPrerequisiteModules. - void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {} + void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override { + } // FailedPrerequisiteModules can never be reused. bool @@ -429,21 +430,21 @@ class CachingProjectModules : public ProjectModules { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, - CachingProjectModules &MDB, - StringRef ModuleName) { - llvm::SmallVector ModuleNames; +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + CachingProjectModules &MDB, + StringRef ModuleName) { + llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { ModuleNamesSet.insert(ModuleName); -for (const std::string &RequiredModuleName : MDB.getRequiredModules( +for (StringRef RequiredModuleName : MDB.getRequiredModules( MDB.getSourceForModuleName(ModuleName, RequiredSource))) if (ModuleNamesSet.insert(RequiredModuleName).second) Visitor(RequiredModuleName, Visitor); -ModuleNames.push_back(ModuleName.str()); +ModuleNames.push_back(ModuleName); }; VisitDeps(ModuleName, VisitDeps); @@ -493,13 +494,13 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( // Get Required modules in topological order. auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName); for (llvm::StringRef ReqModuleName : ReqModuleNames) { -if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName)) +if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName)) continue; if (auto Cached = Cache.getModule(ReqModuleName)) { if (IsModuleFileUpToDate(Cached->getModuleFilePath(), BuiltModuleFiles, TFS.view(std::nullopt))) { -log("Reusing module {0} from {1}", ReqModuleName, +log("Reusing module {0} from {1}", ModuleName, Cached->getModuleFilePath()); BuiltModuleFiles.addModuleFile(std::move(Cached)); continue; @@ -507,16 +508,14 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( Cache.remove(ReqModuleName); } -std::string ReqFileName = -MDB.getSourceForModuleName(ReqModuleName, RequiredSource); llvm::Expected MF = buildModuleFile( -ReqModuleName, ReqFileName, getCDB(), TFS, BuiltModuleFiles); +ModuleName, ModuleUnitFileName, getCDB(), TFS, BuiltModuleFiles); if (llvm::Error Err = MF.takeError()) return Err; -log("Built module {0} to {1}", ReqModuleName, MF->getModuleFilePath()); +log("Built module {0} to {1}", ModuleName, MF->getModuleFilePath()); auto BuiltModuleFile = std::make_shared(std::move(*MF)); -Cache.add(ReqModuleName, BuiltModuleFile); +Cache.add(ModuleName, BuiltModuleFile); BuiltModuleFiles.addModuleFile(std::move(BuiltModuleFile)); } diff --git a/clang-tools-extra/clangd/test/module_dependencies.test b/clang-tools-extra/clangd/test/module_dependencies.test deleted file mode 100644 index ee1df7f8a35cc..0 --- a/clang-tools-extra
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Cyndy Ishida (cyndyishida) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/142161.diff 6 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSerializationKinds.td (+2-2) - (modified) clang/lib/Serialization/ASTReader.cpp (+6-6) - (modified) clang/test/Modules/module-file-modified.c (+1) - (modified) clang/test/Modules/validate-file-content.m (+1-1) - (modified) clang/test/PCH/modified-module-dependency.m (+1-1) - (modified) clang/test/PCH/validate-file-content.m (+1-1) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td b/clang/include/clang/Basic/DiagnosticSerializationKinds.td index 7965da593f218..a6cc87bc863c2 100644 --- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td +++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td @@ -24,8 +24,8 @@ def err_fe_ast_file_modified : Error< DefaultFatal; def err_fe_pch_file_overridden : Error< "file '%0' from the precompiled header has been overridden">; -def note_pch_required_by : Note<"'%0' required by '%1'">; -def note_pch_rebuild_required : Note<"please rebuild precompiled header '%0'">; +def note_ast_file_required_by : Note<"'%0' required by '%1'">; +def note_ast_file_rebuild_required : Note<"please rebuild precompiled file '%0'">; def note_module_cache_path : Note< "after modifying system headers, please delete the module cache at '%0'">; diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 8d2f105b2dec3..565f01221bb06 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2862,25 +2862,25 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { while (!ImportStack.back()->ImportedBy.empty()) ImportStack.push_back(ImportStack.back()->ImportedBy[0]); - // The top-level PCH is stale. - StringRef TopLevelPCHName(ImportStack.back()->FileName); + // The top-level AST file is stale. + StringRef TopLevelASTFileName(ImportStack.back()->FileName); Diag(diag::err_fe_ast_file_modified) << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) - << TopLevelPCHName << FileChange.Kind + << TopLevelASTFileName << FileChange.Kind << (FileChange.Old && FileChange.New) << llvm::itostr(FileChange.Old.value_or(0)) << llvm::itostr(FileChange.New.value_or(0)); // Print the import stack. if (ImportStack.size() > 1) { -Diag(diag::note_pch_required_by) +Diag(diag::note_ast_file_required_by) << *Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) - Diag(diag::note_pch_required_by) + Diag(diag::note_ast_file_required_by) << ImportStack[I-1]->FileName << ImportStack[I]->FileName; } - Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; + Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName; } IsOutOfDate = true; diff --git a/clang/test/Modules/module-file-modified.c b/clang/test/Modules/module-file-modified.c index 85018b521e288..57160f34a46cf 100644 --- a/clang/test/Modules/module-file-modified.c +++ b/clang/test/Modules/module-file-modified.c @@ -8,4 +8,5 @@ #include "a.h" int foo = 0; // redefinition of 'foo' // CHECK: fatal error: file {{.*}} has been modified since the module file {{.*}} was built +// CHECK: note: please rebuild precompiled file // REQUIRES: shell diff --git a/clang/test/Modules/validate-file-content.m b/clang/test/Modules/validate-file-content.m index 327a68a9b641e..9977aa4665f04 100644 --- a/clang/test/Modules/validate-file-content.m +++ b/clang/test/Modules/validate-file-content.m @@ -29,5 +29,5 @@ // CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed // CHECK: '[[M_H]]' required by '[[M_PCM:.*[/\\]m.*\.pcm]]' // CHECK: '[[M_PCM]]' required by '[[A_PCH]]' -// CHECK: please rebuild precompiled header '[[A_PCH]]' +// CHECK: please rebuild precompiled file '[[A_PCH]]' // expected-no-diagnostics diff --git a/clang/test/PCH/modified-module-dependency.m b/clang/test/PCH/modified-module-dependency.m index 44c14b3a0231c..a4710dea51169 100644 --- a/clang/test/PCH/modified-module-dependency.m +++ b/clang/test/PCH/modified-module-dependency.m @@ -17,4 +17,4 @@ // CHECK: file '[[TEST_H:.*[/\\]test\.h]]' has been modified since the precompiled header '[[PREFIX_PCH:.*/prefix\.pch]]' was built // CHECK: '[[TEST_H]]' required by '[[TEST_PCM:.*[/\\]test\.pcm]]' // CHECK: '[[TEST_PCM]]' required by '[[PREFIX_PCH]]' -// CHECK: please rebuild precompiled header '[[PREFIX_PCH]]' +// CHECK: please rebuild precompiled file '[[PREFIX_PCH]]' diff --git a/clang/test/PCH/validate-file-content.m b/clang/test/PCH/validate-file-con
[clang-tools-extra] [clang-doc] add tags to Mustache namespace template (PR #142045)
@@ -0,0 +1,74 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.html + +enum Color { + RED, + BLUE, + GREEN +}; + +class Foo; + +// CHECK: +// CHECK-NEXT: Enums +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: enum Color +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: Inner Classes +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: Foo +// CHECK-NEXT: +// CHECK-NEXT: + evelez7 wrote: I meant to separate the sidebar checks from the rest of the body. That's why I didn't leave a whitespace after the last check on line 21, since it's still the sidebar. I used that check to skip a bunch of closing div tags. https://github.com/llvm/llvm-project/pull/142045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
https://github.com/Michael137 edited https://github.com/llvm/llvm-project/pull/142164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
https://github.com/Michael137 edited https://github.com/llvm/llvm-project/pull/142164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
https://github.com/Michael137 created https://github.com/llvm/llvm-project/pull/142164 Depends on https://github.com/llvm/llvm-project/pull/142163 This patch makes the `-ast-dump-filter` Clang option available to the `target modules dump ast` command. This allows us to selectively dump parts of the AST by name. The AST can quickly grow way too large to skim on the console. This will aid in debugging AST related issues. Example: ``` (lldb) target modules dump ast --filter func Dumping clang ast for 48 modules. Dumping func: FunctionDecl 0xc4b785008 <> func 'void (int)' extern |-ParmVarDecl 0xc4b7853d8 <> x 'int' `-AsmLabelAttr 0xc4b785358 <> Implicit "_Z4funcIiEvT_" Dumping func: FunctionDecl 0xc4b7850b8 <> func 'void (int)' implicit_instantiation extern |-TemplateArgument type 'int' | `-BuiltinType 0xc4b85b110 'int' `-ParmVarDecl 0xc4b7853d8 <> x 'int' ``` >From 662e07aa9bb6560f37c079ba6f13be17e7885b48 Mon Sep 17 00:00:00 2001 From: Michael Buch Date: Fri, 30 May 2025 15:44:09 +0100 Subject: [PATCH 1/2] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream We're planning on using the ASTPrinter in LLDB for AST dumping. But it currently takes the output stream via `unique_ptr`. In LLDB we don't have the output stream available in this form and instead it would be convenient if we could just pass a reference to the stream. This patch adds that overload. (cherry picked from commit 9bd15ee7ed44adc836bcd07ff7e856d7a32ba6a9) --- clang/include/clang/Frontend/ASTConsumers.h | 5 + clang/lib/Frontend/ASTConsumers.cpp | 20 2 files changed, 25 insertions(+) diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index 0e068bf5cccb5..890701b6ff188 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -35,6 +35,11 @@ CreateASTDumper(std::unique_ptr OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format); +std::unique_ptr +CreateASTDumper(raw_ostream &OS, StringRef FilterString, bool DumpDecls, +bool Deserialize, bool DumpLookups, bool DumpDeclTypes, +ASTDumpOutputFormat Format); + // AST Decl node lister: prints qualified names of all filterable AST Decl // nodes. std::unique_ptr CreateASTDeclNodeLister(); diff --git a/clang/lib/Frontend/ASTConsumers.cpp b/clang/lib/Frontend/ASTConsumers.cpp index a6e35452b4fbe..a5ff4d44592d4 100644 --- a/clang/lib/Frontend/ASTConsumers.cpp +++ b/clang/lib/Frontend/ASTConsumers.cpp @@ -41,6 +41,13 @@ namespace { OutputKind(K), OutputFormat(Format), FilterString(FilterString), DumpLookups(DumpLookups), DumpDeclTypes(DumpDeclTypes) {} +ASTPrinter(raw_ostream &Out, Kind K, ASTDumpOutputFormat Format, + StringRef FilterString, bool DumpLookups = false, + bool DumpDeclTypes = false) +: Out(Out), OwnedOut(nullptr), OutputKind(K), OutputFormat(Format), + FilterString(FilterString), DumpLookups(DumpLookups), + DumpDeclTypes(DumpDeclTypes) {} + void HandleTranslationUnit(ASTContext &Context) override { TranslationUnitDecl *D = Context.getTranslationUnitDecl(); @@ -176,6 +183,19 @@ clang::CreateASTDumper(std::unique_ptr Out, StringRef FilterString, Format, FilterString, DumpLookups, DumpDeclTypes); } +std::unique_ptr +clang::CreateASTDumper(raw_ostream &Out, StringRef FilterString, bool DumpDecls, + bool Deserialize, bool DumpLookups, bool DumpDeclTypes, + ASTDumpOutputFormat Format) { + assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump"); + return std::make_unique(Out, + Deserialize ? ASTPrinter::DumpFull + : DumpDecls ? ASTPrinter::Dump + : ASTPrinter::None, + Format, FilterString, DumpLookups, + DumpDeclTypes); +} + std::unique_ptr clang::CreateASTDeclNodeLister() { return std::make_unique(nullptr); } >From 0ba5a4f09caeb54008594adfb3b8efa2a740e5e6 Mon Sep 17 00:00:00 2001 From: Michael Buch Date: Fri, 30 May 2025 15:46:27 +0100 Subject: [PATCH 2/2] [lldb] Add filter option to AST dump command This patch makes the `-ast-dump-filter` Clang option available to the `target modules dump ast` command. This allows us to selectively dump parts of the AST by name. The AST can quickly grow way too large to skim on the console. This will aid in debugging AST related issues. Example: ``` (lldb) target modules dump ast --filter func Dumping clang ast for 48 modules. Dumping func: FunctionDecl 0xc4b785008 <> func 'void (int)' extern |-ParmVarDecl 0xc4b7853d8 <> x 'int' `-AsmLabelAttr 0xc4b785358 <> Implicit "_
[clang] [flang] [mlir] [flang] Add support for -mprefer-vector-width= (PR #142073)
tarunprabhu wrote: @mcinally, It looks like the buildbot failure is because a test is written expecting a single attribute, but two are present, although the attribute being checked for is present. https://github.com/llvm/llvm-project/pull/142073 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Michael Buch (Michael137) Changes Depends on https://github.com/llvm/llvm-project/pull/142163 This patch makes the `-ast-dump-filter` Clang option available to the `target modules dump ast` command. This allows us to selectively dump parts of the AST by name. The AST can quickly grow way too large to skim on the console. This will aid in debugging AST related issues. Example: ``` (lldb) target modules dump ast --filter func Dumping clang ast for 48 modules. Dumping func: FunctionDecl 0xc4b785008 <> func 'void (int)' extern |-ParmVarDecl 0xc4b7853d8 < > x 'int' `-AsmLabelAttr 0xc4b785358 < > Implicit "_Z4funcIiEvT_" Dumping func : FunctionDecl 0xc4b7850b8 < > func 'void (int)' implicit_instantiation extern |-TemplateArgument type 'int' | `-BuiltinType 0xc4b85b110 'int' `-ParmVarDecl 0xc4b7853d8 < > x 'int' ``` --- Full diff: https://github.com/llvm/llvm-project/pull/142164.diff 19 Files Affected: - (modified) clang/include/clang/Frontend/ASTConsumers.h (+5) - (modified) clang/lib/Frontend/ASTConsumers.cpp (+20) - (modified) lldb/include/lldb/Symbol/SymbolFile.h (+1-1) - (modified) lldb/include/lldb/Symbol/SymbolFileOnDemand.h (+1-1) - (modified) lldb/include/lldb/Symbol/TypeSystem.h (+2-1) - (modified) lldb/source/Commands/CommandObjectTarget.cpp (+18-5) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp (+3-3) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h (+1-1) - (modified) lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp (+15-5) - (modified) lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h (+2-2) - (modified) lldb/source/Symbol/SymbolFileOnDemand.cpp (+3-2) ``diff diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index 0e068bf5cccb5..890701b6ff188 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -35,6 +35,11 @@ CreateASTDumper(std::unique_ptr OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format); +std::unique_ptr +CreateASTDumper(raw_ostream &OS, StringRef FilterString, bool DumpDecls, +bool Deserialize, bool DumpLookups, bool DumpDeclTypes, +ASTDumpOutputFormat Format); + // AST Decl node lister: prints qualified names of all filterable AST Decl // nodes. std::unique_ptr CreateASTDeclNodeLister(); diff --git a/clang/lib/Frontend/ASTConsumers.cpp b/clang/lib/Frontend/ASTConsumers.cpp index a6e35452b4fbe..a5ff4d44592d4 100644 --- a/clang/lib/Frontend/ASTConsumers.cpp +++ b/clang/lib/Frontend/ASTConsumers.cpp @@ -41,6 +41,13 @@ namespace { OutputKind(K), OutputFormat(Format), FilterString(FilterString), DumpLookups(DumpLookups), DumpDeclTypes(DumpDeclTypes) {} +ASTPrinter(raw_ostream &Out, Kind K, ASTDumpOutputFormat Format, + StringRef FilterString, bool DumpLookups = false, + bool DumpDeclTypes = false) +: Out(Out), OwnedOut(nullptr), OutputKind(K), OutputFormat(Format), + FilterString(FilterString), DumpLookups(DumpLookups), + DumpDeclTypes(DumpDeclTypes) {} + void HandleTranslationUnit(ASTContext &Context) override { TranslationUnitDecl *D = Context.getTranslationUnitDecl(); @@ -176,6 +183,19 @@ clang::CreateASTDumper(std::unique_ptr Out, StringRef FilterString, Format, FilterString, DumpLookups, DumpDeclTypes); } +std::unique_ptr +clang::CreateASTDumper(raw_ostream &Out, StringRef FilterString, bool DumpDecls, + bool Deserialize, bool DumpLookups, bool DumpDeclTypes, + ASTDumpOutputFormat Format) { + assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump"); + return std::make_unique(Out, + Deserialize ? ASTPrinter::DumpFull + : DumpDecls ? ASTPrinter::Dump + : ASTPrinter::None, + Format, FilterString, DumpLooku
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
llvmbot wrote: @llvm/pr-subscribers-lldb Author: Michael Buch (Michael137) Changes Depends on https://github.com/llvm/llvm-project/pull/142163 This patch makes the `-ast-dump-filter` Clang option available to the `target modules dump ast` command. This allows us to selectively dump parts of the AST by name. The AST can quickly grow way too large to skim on the console. This will aid in debugging AST related issues. Example: ``` (lldb) target modules dump ast --filter func Dumping clang ast for 48 modules. Dumping func: FunctionDecl 0xc4b785008 <> func 'void (int)' extern |-ParmVarDecl 0xc4b7853d8 < > x 'int' `-AsmLabelAttr 0xc4b785358 < > Implicit "_Z4funcIiEvT_" Dumping func : FunctionDecl 0xc4b7850b8 < > func 'void (int)' implicit_instantiation extern |-TemplateArgument type 'int' | `-BuiltinType 0xc4b85b110 'int' `-ParmVarDecl 0xc4b7853d8 < > x 'int' ``` --- Full diff: https://github.com/llvm/llvm-project/pull/142164.diff 19 Files Affected: - (modified) clang/include/clang/Frontend/ASTConsumers.h (+5) - (modified) clang/lib/Frontend/ASTConsumers.cpp (+20) - (modified) lldb/include/lldb/Symbol/SymbolFile.h (+1-1) - (modified) lldb/include/lldb/Symbol/SymbolFileOnDemand.h (+1-1) - (modified) lldb/include/lldb/Symbol/TypeSystem.h (+2-1) - (modified) lldb/source/Commands/CommandObjectTarget.cpp (+18-5) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp (+3-3) - (modified) lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h (+1-1) - (modified) lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp (+2-2) - (modified) lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.h (+1-1) - (modified) lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp (+15-5) - (modified) lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h (+2-2) - (modified) lldb/source/Symbol/SymbolFileOnDemand.cpp (+3-2) ``diff diff --git a/clang/include/clang/Frontend/ASTConsumers.h b/clang/include/clang/Frontend/ASTConsumers.h index 0e068bf5cccb5..890701b6ff188 100644 --- a/clang/include/clang/Frontend/ASTConsumers.h +++ b/clang/include/clang/Frontend/ASTConsumers.h @@ -35,6 +35,11 @@ CreateASTDumper(std::unique_ptr OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format); +std::unique_ptr +CreateASTDumper(raw_ostream &OS, StringRef FilterString, bool DumpDecls, +bool Deserialize, bool DumpLookups, bool DumpDeclTypes, +ASTDumpOutputFormat Format); + // AST Decl node lister: prints qualified names of all filterable AST Decl // nodes. std::unique_ptr CreateASTDeclNodeLister(); diff --git a/clang/lib/Frontend/ASTConsumers.cpp b/clang/lib/Frontend/ASTConsumers.cpp index a6e35452b4fbe..a5ff4d44592d4 100644 --- a/clang/lib/Frontend/ASTConsumers.cpp +++ b/clang/lib/Frontend/ASTConsumers.cpp @@ -41,6 +41,13 @@ namespace { OutputKind(K), OutputFormat(Format), FilterString(FilterString), DumpLookups(DumpLookups), DumpDeclTypes(DumpDeclTypes) {} +ASTPrinter(raw_ostream &Out, Kind K, ASTDumpOutputFormat Format, + StringRef FilterString, bool DumpLookups = false, + bool DumpDeclTypes = false) +: Out(Out), OwnedOut(nullptr), OutputKind(K), OutputFormat(Format), + FilterString(FilterString), DumpLookups(DumpLookups), + DumpDeclTypes(DumpDeclTypes) {} + void HandleTranslationUnit(ASTContext &Context) override { TranslationUnitDecl *D = Context.getTranslationUnitDecl(); @@ -176,6 +183,19 @@ clang::CreateASTDumper(std::unique_ptr Out, StringRef FilterString, Format, FilterString, DumpLookups, DumpDeclTypes); } +std::unique_ptr +clang::CreateASTDumper(raw_ostream &Out, StringRef FilterString, bool DumpDecls, + bool Deserialize, bool DumpLookups, bool DumpDeclTypes, + ASTDumpOutputFormat Format) { + assert((DumpDecls || Deserialize || DumpLookups) && "nothing to dump"); + return std::make_unique(Out, + Deserialize ? ASTPrinter::DumpFull + : DumpDecls ? ASTPrinter::Dump + : ASTPrinter::None, + Format, FilterString, DumpLookup
[clang] [flang] [llvm] Add IR Profile-Guided Optimization (IR PGO) support to the Flang compiler (PR #136098)
github-actions[bot] wrote: @fanju110 Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr). If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! https://github.com/llvm/llvm-project/pull/136098 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxx] [llvm] [Clang] Add warnings when mixing different charN_t types (PR #138708)
jyknight wrote: I like the idea of this warning, but I'm afraid the diagnostic wording isn't sufficient to result in correct fixes to code. Instead, it seems to result in simply adding explicit casts to make the compiler shut up. Even from people who know what they're doing w.r.t. Unicode. The first response I got in a discussion about an instance of `implicit conversion from char16_t to char32_t may change the meaning of the represented code unit`, was (approximately) "What an obnoxious warning, _of course it's fine_ to zero-extend a char16_t codepoint to a char32_t codepoint!" This, from an subject matter expert, maintainer of a unicode library. And, of course, it _is_ fine if you happen to know that the char16_t was representing a valid codepoint that happens to be limited to under 64K. Which..._could_ be the case...it's just not common. And, worse, if it is true in a given case, then the API in question is dangerous and invites misuse by its callers, because it has decided upon an an unusual/unexpected use of types (char16_t as a codepoint, instead of the expected use of char16_t as a UTF-16 code-unit). So, I think that we need to somehow explain in these diagnostics -- in very few words! -- that char16_t should represent UTF-16 code-units, while char32_t represents unicode codepoints, and that you _probably_ need to refactor your code to decode a sequence of UTF-16 char16_t into char32_t codepoints, rather than simply insert an explicit cast of an individual char16_t. https://github.com/llvm/llvm-project/pull/138708 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
https://github.com/cyndyishida created https://github.com/llvm/llvm-project/pull/142161 None >From fbd695a22e88f977c8512b4cdc298dbbed7e2534 Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Thu, 29 May 2025 20:39:19 -0700 Subject: [PATCH] [clang] Rename diagnostic notes that assumed precompiled dependencies are pch's NFCI --- .../clang/Basic/DiagnosticSerializationKinds.td | 4 ++-- clang/lib/Serialization/ASTReader.cpp| 12 ++-- clang/test/Modules/module-file-modified.c| 1 + clang/test/Modules/validate-file-content.m | 2 +- clang/test/PCH/modified-module-dependency.m | 2 +- clang/test/PCH/validate-file-content.m | 2 +- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td b/clang/include/clang/Basic/DiagnosticSerializationKinds.td index 7965da593f218..a6cc87bc863c2 100644 --- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td +++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td @@ -24,8 +24,8 @@ def err_fe_ast_file_modified : Error< DefaultFatal; def err_fe_pch_file_overridden : Error< "file '%0' from the precompiled header has been overridden">; -def note_pch_required_by : Note<"'%0' required by '%1'">; -def note_pch_rebuild_required : Note<"please rebuild precompiled header '%0'">; +def note_ast_file_required_by : Note<"'%0' required by '%1'">; +def note_ast_file_rebuild_required : Note<"please rebuild precompiled file '%0'">; def note_module_cache_path : Note< "after modifying system headers, please delete the module cache at '%0'">; diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 8d2f105b2dec3..565f01221bb06 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2862,25 +2862,25 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { while (!ImportStack.back()->ImportedBy.empty()) ImportStack.push_back(ImportStack.back()->ImportedBy[0]); - // The top-level PCH is stale. - StringRef TopLevelPCHName(ImportStack.back()->FileName); + // The top-level AST file is stale. + StringRef TopLevelASTFileName(ImportStack.back()->FileName); Diag(diag::err_fe_ast_file_modified) << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) - << TopLevelPCHName << FileChange.Kind + << TopLevelASTFileName << FileChange.Kind << (FileChange.Old && FileChange.New) << llvm::itostr(FileChange.Old.value_or(0)) << llvm::itostr(FileChange.New.value_or(0)); // Print the import stack. if (ImportStack.size() > 1) { -Diag(diag::note_pch_required_by) +Diag(diag::note_ast_file_required_by) << *Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) - Diag(diag::note_pch_required_by) + Diag(diag::note_ast_file_required_by) << ImportStack[I-1]->FileName << ImportStack[I]->FileName; } - Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; + Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName; } IsOutOfDate = true; diff --git a/clang/test/Modules/module-file-modified.c b/clang/test/Modules/module-file-modified.c index 85018b521e288..57160f34a46cf 100644 --- a/clang/test/Modules/module-file-modified.c +++ b/clang/test/Modules/module-file-modified.c @@ -8,4 +8,5 @@ #include "a.h" int foo = 0; // redefinition of 'foo' // CHECK: fatal error: file {{.*}} has been modified since the module file {{.*}} was built +// CHECK: note: please rebuild precompiled file // REQUIRES: shell diff --git a/clang/test/Modules/validate-file-content.m b/clang/test/Modules/validate-file-content.m index 327a68a9b641e..9977aa4665f04 100644 --- a/clang/test/Modules/validate-file-content.m +++ b/clang/test/Modules/validate-file-content.m @@ -29,5 +29,5 @@ // CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed // CHECK: '[[M_H]]' required by '[[M_PCM:.*[/\\]m.*\.pcm]]' // CHECK: '[[M_PCM]]' required by '[[A_PCH]]' -// CHECK: please rebuild precompiled header '[[A_PCH]]' +// CHECK: please rebuild precompiled file '[[A_PCH]]' // expected-no-diagnostics diff --git a/clang/test/PCH/modified-module-dependency.m b/clang/test/PCH/modified-module-dependency.m index 44c14b3a0231c..a4710dea51169 100644 --- a/clang/test/PCH/modified-module-dependency.m +++ b/clang/test/PCH/modified-module-dependency.m @@ -17,4 +17,4 @@ // CHECK: file '[[TEST_H:.*[/\\]test\.h]]' has been modified since the precompiled header '[[PREFIX_PCH:.*/prefix\.pch]]' was built // CHECK: '[[TEST_H]]' required by '[[TEST_PCM:.*[/\\]test\.pcm]]' // CHECK: '[[TEST_PCM]]' required by '[[PREFIX_PCH]]' -// CHECK: please rebuild pre
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
https://github.com/cyndyishida updated https://github.com/llvm/llvm-project/pull/142161 >From 6229f515af60a2b04e8599a66f036217fbc98f20 Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Fri, 30 May 2025 07:53:51 -0700 Subject: [PATCH] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI --- .../clang/Basic/DiagnosticSerializationKinds.td| 5 +++-- clang/lib/Serialization/ASTReader.cpp | 14 +++--- clang/test/Modules/module-file-modified.c | 1 + clang/test/Modules/validate-file-content.m | 2 +- clang/test/PCH/modified-module-dependency.m| 2 +- clang/test/PCH/validate-file-content.m | 2 +- 6 files changed, 14 insertions(+), 12 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td b/clang/include/clang/Basic/DiagnosticSerializationKinds.td index 7965da593f218..93e31c8155ffc 100644 --- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td +++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td @@ -24,8 +24,9 @@ def err_fe_ast_file_modified : Error< DefaultFatal; def err_fe_pch_file_overridden : Error< "file '%0' from the precompiled header has been overridden">; -def note_pch_required_by : Note<"'%0' required by '%1'">; -def note_pch_rebuild_required : Note<"please rebuild precompiled header '%0'">; +def note_ast_file_required_by : Note<"'%0' required by '%1'">; +def note_ast_file_rebuild_required +: Note<"please rebuild precompiled file '%0'">; def note_module_cache_path : Note< "after modifying system headers, please delete the module cache at '%0'">; diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 8d2f105b2dec3..521d8f88d19de 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -2862,25 +2862,25 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) { while (!ImportStack.back()->ImportedBy.empty()) ImportStack.push_back(ImportStack.back()->ImportedBy[0]); - // The top-level PCH is stale. - StringRef TopLevelPCHName(ImportStack.back()->FileName); + // The top-level AST file is stale. + StringRef TopLevelASTFileName(ImportStack.back()->FileName); Diag(diag::err_fe_ast_file_modified) << *Filename << moduleKindForDiagnostic(ImportStack.back()->Kind) - << TopLevelPCHName << FileChange.Kind + << TopLevelASTFileName << FileChange.Kind << (FileChange.Old && FileChange.New) << llvm::itostr(FileChange.Old.value_or(0)) << llvm::itostr(FileChange.New.value_or(0)); // Print the import stack. if (ImportStack.size() > 1) { -Diag(diag::note_pch_required_by) +Diag(diag::note_ast_file_required_by) << *Filename << ImportStack[0]->FileName; for (unsigned I = 1; I < ImportStack.size(); ++I) - Diag(diag::note_pch_required_by) -<< ImportStack[I-1]->FileName << ImportStack[I]->FileName; + Diag(diag::note_ast_file_required_by) + << ImportStack[I - 1]->FileName << ImportStack[I]->FileName; } - Diag(diag::note_pch_rebuild_required) << TopLevelPCHName; + Diag(diag::note_ast_file_rebuild_required) << TopLevelASTFileName; } IsOutOfDate = true; diff --git a/clang/test/Modules/module-file-modified.c b/clang/test/Modules/module-file-modified.c index 85018b521e288..57160f34a46cf 100644 --- a/clang/test/Modules/module-file-modified.c +++ b/clang/test/Modules/module-file-modified.c @@ -8,4 +8,5 @@ #include "a.h" int foo = 0; // redefinition of 'foo' // CHECK: fatal error: file {{.*}} has been modified since the module file {{.*}} was built +// CHECK: note: please rebuild precompiled file // REQUIRES: shell diff --git a/clang/test/Modules/validate-file-content.m b/clang/test/Modules/validate-file-content.m index 327a68a9b641e..9977aa4665f04 100644 --- a/clang/test/Modules/validate-file-content.m +++ b/clang/test/Modules/validate-file-content.m @@ -29,5 +29,5 @@ // CHECK: file '[[M_H:.*[/\\]m\.h]]' has been modified since the precompiled header '[[A_PCH:.*/a\.pch]]' was built: content changed // CHECK: '[[M_H]]' required by '[[M_PCM:.*[/\\]m.*\.pcm]]' // CHECK: '[[M_PCM]]' required by '[[A_PCH]]' -// CHECK: please rebuild precompiled header '[[A_PCH]]' +// CHECK: please rebuild precompiled file '[[A_PCH]]' // expected-no-diagnostics diff --git a/clang/test/PCH/modified-module-dependency.m b/clang/test/PCH/modified-module-dependency.m index 44c14b3a0231c..a4710dea51169 100644 --- a/clang/test/PCH/modified-module-dependency.m +++ b/clang/test/PCH/modified-module-dependency.m @@ -17,4 +17,4 @@ // CHECK: file '[[TEST_H:.*[/\\]test\.h]]' has been modified since the precompiled header '[[PREFIX_PCH:.*/prefix\.pch]]' was built // CHECK: '[[TEST_H]]' required by '[[TEST_PCM:.*[/\\]test\.pcm]]' // CHECK: '[[TEST_PCM]]
[clang] [CIR] Skip generation of a continue block when flattening TernaryOp (PR #142165)
https://github.com/mmha created https://github.com/llvm/llvm-project/pull/142165 We used to insert a continue Block at the end of a flattened ternary op that only contained a branch to the remaing operation of the remaining Block. This patch removes that continue block and changes the true/false blocks to directly jump to the remaining ops. With this patch the CIR now generates exactly the same LLVM IR as the original codegen. This upstreams llvm/clangir#1651. >From f62994df24f912a3815cabb7fc4a47fa8c8c948e Mon Sep 17 00:00:00 2001 From: Morris Hafner Date: Fri, 30 May 2025 16:29:05 +0200 Subject: [PATCH] [CIR] Skip generation of a continue block when flattening TernaryOp We used to insert a continue Block at the end of a flattened ternary op that only contained a branch to the remaing operation of the remaining Block. This patch removes that continue block and changes the true/false blocks to directly jump to the remaining ops. With this patch the CIR now generates exactly the same LLVM IR as the original codegen. This upstreams llvm/clangir#1651. --- .../lib/CIR/Dialect/Transforms/FlattenCFG.cpp | 31 +-- clang/test/CIR/Lowering/ternary.cir | 2 -- clang/test/CIR/Transforms/ternary.cir | 4 --- 3 files changed, 15 insertions(+), 22 deletions(-) diff --git a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp index 26e5c0572f12e..6081a436f5c29 100644 --- a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp +++ b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp @@ -16,9 +16,11 @@ #include "mlir/IR/Block.h" #include "mlir/IR/Builders.h" #include "mlir/IR/PatternMatch.h" +#include "mlir/IR/ValueRange.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" +#include "clang/AST/DeclBase.h" #include "clang/CIR/Dialect/IR/CIRDialect.h" #include "clang/CIR/Dialect/Passes.h" #include "clang/CIR/MissingFeatures.h" @@ -491,15 +493,7 @@ class CIRTernaryOpFlattening : public mlir::OpRewritePattern { Location loc = op->getLoc(); Block *condBlock = rewriter.getInsertionBlock(); Block::iterator opPosition = rewriter.getInsertionPoint(); -Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition); -llvm::SmallVector locs; -// Ternary result is optional, make sure to populate the location only -// when relevant. -if (op->getResultTypes().size()) - locs.push_back(loc); -Block *continueBlock = -rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs); -rewriter.create(loc, remainingOpsBlock); +auto *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition); Region &trueRegion = op.getTrueRegion(); Block *trueBlock = &trueRegion.front(); @@ -508,24 +502,29 @@ class CIRTernaryOpFlattening : public mlir::OpRewritePattern { auto trueYieldOp = dyn_cast(trueTerminator); rewriter.replaceOpWithNewOp(trueYieldOp, trueYieldOp.getArgs(), - continueBlock); -rewriter.inlineRegionBefore(trueRegion, continueBlock); + remainingOpsBlock); +rewriter.inlineRegionBefore(trueRegion, remainingOpsBlock); -Block *falseBlock = continueBlock; Region &falseRegion = op.getFalseRegion(); +Block *falseBlock = &falseRegion.front(); -falseBlock = &falseRegion.front(); mlir::Operation *falseTerminator = falseRegion.back().getTerminator(); rewriter.setInsertionPointToEnd(&falseRegion.back()); auto falseYieldOp = dyn_cast(falseTerminator); rewriter.replaceOpWithNewOp(falseYieldOp, falseYieldOp.getArgs(), - continueBlock); -rewriter.inlineRegionBefore(falseRegion, continueBlock); + remainingOpsBlock); +rewriter.inlineRegionBefore(falseRegion, remainingOpsBlock); rewriter.setInsertionPointToEnd(condBlock); rewriter.create(loc, op.getCond(), trueBlock, falseBlock); -rewriter.replaceOp(op, continueBlock->getArguments()); +if (auto rt = op.getResultTypes(); rt.size()) { + iterator_range args = remainingOpsBlock->addArguments(rt, op.getLoc()); + SmallVector values; + llvm::copy(args, std::back_inserter(values)); + rewriter.replaceOpUsesWithinBlock(op, values, remainingOpsBlock); +} +rewriter.eraseOp(op); // Ok, we're done! return mlir::success(); diff --git a/clang/test/CIR/Lowering/ternary.cir b/clang/test/CIR/Lowering/ternary.cir index 247c6ae3a1e17..c2226cd92ece7 100644 --- a/clang/test/CIR/Lowering/ternary.cir +++ b/clang/test/CIR/Lowering/ternary.cir @@ -25,6 +25,4 @@ module { // LLVM: br label %[[M]] // LLVM: [[M]]: // LLVM: [[R:%[[:alnum:]]+]] = phi i32 [ 1, %[[B2]] ], [ 0, %[[B1]] ] -// LLVM: br label %[[B3:[[:alnum:]]+]] -// LLVM: [[B3]]: // LLVM: ret i32
[clang] [CIR] Skip generation of a continue block when flattening TernaryOp (PR #142165)
llvmbot wrote: @llvm/pr-subscribers-clangir Author: Morris Hafner (mmha) Changes We used to insert a continue Block at the end of a flattened ternary op that only contained a branch to the remaing operation of the remaining Block. This patch removes that continue block and changes the true/false blocks to directly jump to the remaining ops. With this patch the CIR now generates exactly the same LLVM IR as the original codegen. This upstreams llvm/clangir#1651. --- Full diff: https://github.com/llvm/llvm-project/pull/142165.diff 3 Files Affected: - (modified) clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp (+15-16) - (modified) clang/test/CIR/Lowering/ternary.cir (-2) - (modified) clang/test/CIR/Transforms/ternary.cir (-4) ``diff diff --git a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp index 26e5c0572f12e..6081a436f5c29 100644 --- a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp +++ b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp @@ -16,9 +16,11 @@ #include "mlir/IR/Block.h" #include "mlir/IR/Builders.h" #include "mlir/IR/PatternMatch.h" +#include "mlir/IR/ValueRange.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" +#include "clang/AST/DeclBase.h" #include "clang/CIR/Dialect/IR/CIRDialect.h" #include "clang/CIR/Dialect/Passes.h" #include "clang/CIR/MissingFeatures.h" @@ -491,15 +493,7 @@ class CIRTernaryOpFlattening : public mlir::OpRewritePattern { Location loc = op->getLoc(); Block *condBlock = rewriter.getInsertionBlock(); Block::iterator opPosition = rewriter.getInsertionPoint(); -Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition); -llvm::SmallVector locs; -// Ternary result is optional, make sure to populate the location only -// when relevant. -if (op->getResultTypes().size()) - locs.push_back(loc); -Block *continueBlock = -rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs); -rewriter.create(loc, remainingOpsBlock); +auto *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition); Region &trueRegion = op.getTrueRegion(); Block *trueBlock = &trueRegion.front(); @@ -508,24 +502,29 @@ class CIRTernaryOpFlattening : public mlir::OpRewritePattern { auto trueYieldOp = dyn_cast(trueTerminator); rewriter.replaceOpWithNewOp(trueYieldOp, trueYieldOp.getArgs(), - continueBlock); -rewriter.inlineRegionBefore(trueRegion, continueBlock); + remainingOpsBlock); +rewriter.inlineRegionBefore(trueRegion, remainingOpsBlock); -Block *falseBlock = continueBlock; Region &falseRegion = op.getFalseRegion(); +Block *falseBlock = &falseRegion.front(); -falseBlock = &falseRegion.front(); mlir::Operation *falseTerminator = falseRegion.back().getTerminator(); rewriter.setInsertionPointToEnd(&falseRegion.back()); auto falseYieldOp = dyn_cast(falseTerminator); rewriter.replaceOpWithNewOp(falseYieldOp, falseYieldOp.getArgs(), - continueBlock); -rewriter.inlineRegionBefore(falseRegion, continueBlock); + remainingOpsBlock); +rewriter.inlineRegionBefore(falseRegion, remainingOpsBlock); rewriter.setInsertionPointToEnd(condBlock); rewriter.create(loc, op.getCond(), trueBlock, falseBlock); -rewriter.replaceOp(op, continueBlock->getArguments()); +if (auto rt = op.getResultTypes(); rt.size()) { + iterator_range args = remainingOpsBlock->addArguments(rt, op.getLoc()); + SmallVector values; + llvm::copy(args, std::back_inserter(values)); + rewriter.replaceOpUsesWithinBlock(op, values, remainingOpsBlock); +} +rewriter.eraseOp(op); // Ok, we're done! return mlir::success(); diff --git a/clang/test/CIR/Lowering/ternary.cir b/clang/test/CIR/Lowering/ternary.cir index 247c6ae3a1e17..c2226cd92ece7 100644 --- a/clang/test/CIR/Lowering/ternary.cir +++ b/clang/test/CIR/Lowering/ternary.cir @@ -25,6 +25,4 @@ module { // LLVM: br label %[[M]] // LLVM: [[M]]: // LLVM: [[R:%[[:alnum:]]+]] = phi i32 [ 1, %[[B2]] ], [ 0, %[[B1]] ] -// LLVM: br label %[[B3:[[:alnum:]]+]] -// LLVM: [[B3]]: // LLVM: ret i32 [[R]] diff --git a/clang/test/CIR/Transforms/ternary.cir b/clang/test/CIR/Transforms/ternary.cir index 67ef7f95a6b52..0c22268495697 100644 --- a/clang/test/CIR/Transforms/ternary.cir +++ b/clang/test/CIR/Transforms/ternary.cir @@ -37,8 +37,6 @@ module { // CHECK:%6 = cir.const #cir.int<5> : !s32i // CHECK:cir.br ^bb3(%6 : !s32i) // CHECK: ^bb3(%7: !s32i): // 2 preds: ^bb1, ^bb2 -// CHECK:cir.br ^bb4 -// CHECK: ^bb4: // pred: ^bb3 // CHECK:cir.store %7, %1 : !s32i, !cir.ptr // CHECK:%8 = cir.load %1 : !cir.ptr, !s32i
[clang] [clang] Correct FixIt ranges for unused capture warnings (PR #141148)
@@ -0,0 +1,250 @@ +// RUN: cp %s %t +// RUN: %clang_cc1 -x c++ -Wunused-lambda-capture -Wno-unused-value -std=c++1z -fixit %t +// RUN: grep -v CHECK %t | FileCheck %s + + +#define MACRO_CAPTURE(...) __VA_ARGS__ +int main() { +int a = 0, b = 0, c = 0; +auto F0 = [a, &b]() mutable { +// CHECK: auto F0 = [a]() +a++; +}; + +auto F1 = [&a, &b]() { +// CHECK: auto F1 = []() { +}; + +auto F2 = [&a, b]() { +// CHECK: auto F2 = []() { +}; + +auto F3 = [&a, + &b]() { +// CHECK: auto F3 = []() { +}; + +auto F4 = [&a +, &b]() { +// CHECK: auto F4 = []() { +}; +auto F5 = [&a ,&b]() { +// CHECK: auto F5 = []() { +}; + +auto F0a = [a, &b]() mutable { +// CHECK: auto F0a = [a]() mutable { +a++; +}; + +auto F1a = [&a, &b]() { +// CHECK: auto F1a = [&a]() { +a++; +}; + +auto F2a = [&a, b]() { +// CHECK: auto F2a = [&a]() { +a++; +}; + +auto F3a = [&a, + &b]() { +// CHECK: auto F3a = [&a]() { +a++; +}; + +auto F4a = [&a +, &b]() { +// CHECK: auto F4a = [&a]() { +a++; +}; + +auto F5a = [&a ,&b]() { +// CHECK: auto F5a = [&a]() { +a++; +}; +auto F0b = [a, &b]() mutable { +// CHECK: auto F0b = [ &b]() mutable +b++; +}; + +auto F1b = [&a, &b]() { +// CHECK: auto F1b = [ &b]() { +b++; +}; + +auto F2b = [&a, b]() mutable { +// CHECK: auto F2b = [ b]() mutable { +b++; +}; + +auto F3b = [&a, + &b]() { +// CHECK: auto F3b = [ &b]() { +b++; +}; + +auto F4b = [&a +, &b]() { +// CHECK: auto F4b = [ &b]() { +b++; +}; +auto F5b = [&a ,&b]() { +// CHECK: auto F5b = [&b]() { +b++; +}; + +auto F6 = [&a, &b, &c]() { +// CHECK: auto F6 = [&a, &b]() { +a++; +b++; +}; +auto F7 = [&a, &b, &c]() { +// CHECK: auto F7 = [&a, &c]() { +a++; +c++; +}; +auto F8 = [&a, &b, &c]() { +// CHECK: auto F8 = [ &b, &c]() { +b++; +c++; +}; +auto F9 = [&a, &b, &c]() { ojhunt wrote: yeah, I'm currently on vacation so trying very hard not to work despite that being my default :D but having multiple unused in the middle is a good idea - I'm not sure how/if fixits merge neighboring equivalent fixits - but something like ``` ...[used, unused, used, unused, used]... ``` and ``` ...[used, unused, unused, used] ``` seems like a good call - [ ] (trying to add a task to do this in case the terrible GH UI actually surfaces tasks) https://github.com/llvm/llvm-project/pull/141148 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] add tags to Mustache namespace template (PR #142045)
@@ -0,0 +1,74 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.html + +enum Color { + RED, + BLUE, + GREEN +}; + +class Foo; + +// CHECK: +// CHECK-NEXT: Enums +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: enum Color +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: Inner Classes +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: Foo +// CHECK-NEXT: +// CHECK-NEXT: + +// CHECK: +// CHECK-NEXT: Enumerations +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: enum Color +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: Name +// CHECK-NEXT: Value +// CHECK: evelez7 wrote: Yeah I forgot to adjust the spacing after deleting `-NEXT`. We do emit a lot of strange indentation though. I turned these into `CHECKS` because the `RUN` commands are emitted as comments for every enum value. The div and table tags for those comments are a bit jumbled. The `enum Color` above on line 37 is also my own indentation, it's way further back in source. https://github.com/llvm/llvm-project/pull/142045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Correct FixIt ranges for unused capture warnings (PR #141148)
@@ -972,6 +972,12 @@ class Sema final : public SemaBase { /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); + /// Calls \c Lexer::findNextToken() to find the next token, and if the + /// locations of both ends of the token can be resolved it return that ojhunt wrote: I've been talking to @cor3ntin about this as I added some macro tests and they aren't working as I believe they should, and I think I understand my mistake (I misunderstood the docs for `Lexer::findNextToken`) my intention is to require both ends to not be in a macro, and then add an additional test for a macro in the middle wrapping a comma to make sure that if the comma comes from a macro (rather than any subset of the capture expression) we don't try to produce a fixit. In principle it would be easy to handle ```cpp #define COMMA , ``` But I think there are too many ways for macros to do weird things to warrant even trying in such a case. I think that's also a reasonable tradeoff - a macro around subsets of the capture seems vanishingly unlikely so not providing a fixit in such cases seems fair. https://github.com/llvm/llvm-project/pull/141148 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Frontend] Add overload to ASTPrinter that doesn't own output stream (PR #142163)
Michael137 wrote: thanks for the quick review! https://github.com/llvm/llvm-project/pull/142163 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
@@ -2235,11 +2235,22 @@ class CommandObjectTargetModulesDumpClangAST : CommandObjectTargetModulesModuleAutoComplete( interpreter, "target modules dump ast", "Dump the clang ast for a given module's symbol file.", -//"target modules dump ast [ ...]") -nullptr, eCommandRequiresTarget) {} +"target modules dump ast [--filter ] [ ...]", +eCommandRequiresTarget), +m_filter(LLDB_OPT_SET_1, false, "filter", 'f', 0, eArgTypeName, "TODO", + /*default_value=*/"") { +m_option_group.Append(&m_filter, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); +m_option_group.Finalize(); +AddSimpleArgumentList(eArgTypeFilename, eArgRepeatStar); Michael137 wrote: This is also probably unnecessary https://github.com/llvm/llvm-project/pull/142164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
@@ -0,0 +1,17 @@ +! RUN: env FCC_OVERRIDE_OPTIONS="#+-Os +-Oz +-O +-O3 +-Oignore +a +b +c xb Xa Omagic ^-### " %flang -target x86_64-unknown-linux-gnu %s -O2 b -O3 2>&1 | FileCheck %s abidh wrote: Indeed. Thanks for catching this. Fixed now. https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/abidh updated https://github.com/llvm/llvm-project/pull/140556 >From 5d20af48673adebc2ab3e1a6c8442f67d84f1847 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Mon, 19 May 2025 15:21:25 +0100 Subject: [PATCH 1/7] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. This PR add functionality to change flang command line using environment variable `FCC_OVERRIDE_OPTIONS`. It is quite similar to what `CCC_OVERRIDE_OPTIONS` does for clang. The `FCC_OVERRIDE_OPTIONS` seemed like the most obvious name to me but I am open to other ideas. The `applyOverrideOptions` now takes an extra argument that is the name of the environment variable. Previously `CCC_OVERRIDE_OPTIONS` was hardcoded. --- clang/include/clang/Driver/Driver.h | 2 +- clang/lib/Driver/Driver.cpp | 4 ++-- clang/tools/driver/driver.cpp | 2 +- flang/test/Driver/fcc_override.f90 | 12 flang/tools/flang-driver/driver.cpp | 7 +++ 5 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 flang/test/Driver/fcc_override.f90 diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h index b463dc2a93550..7ca848f11b561 100644 --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -879,7 +879,7 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args, /// See applyOneOverrideOption. void applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideOpts, - llvm::StringSet<> &SavedStrings, + llvm::StringSet<> &SavedStrings, StringRef EnvVar, raw_ostream *OS = nullptr); } // end namespace driver diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index a648cc928afdc..a8fea35926a0d 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -7289,7 +7289,7 @@ static void applyOneOverrideOption(raw_ostream &OS, void driver::applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideStr, llvm::StringSet<> &SavedStrings, - raw_ostream *OS) { + StringRef EnvVar, raw_ostream *OS) { if (!OS) OS = &llvm::nulls(); @@ -7298,7 +7298,7 @@ void driver::applyOverrideOptions(SmallVectorImpl &Args, OS = &llvm::nulls(); } - *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n"; + *OS << "### " << EnvVar << ": " << OverrideStr << "\n"; // This does not need to be efficient. diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index 82f47ab973064..81964c65c2892 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -305,7 +305,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) { // FIXME: Driver shouldn't take extra initial argument. driver::applyOverrideOptions(Args, OverrideStr, SavedStrings, - &llvm::errs()); + "CCC_OVERRIDE_OPTIONS", &llvm::errs()); } std::string Path = GetExecutablePath(ToolContext.Path, CanonicalPrefixes); diff --git a/flang/test/Driver/fcc_override.f90 b/flang/test/Driver/fcc_override.f90 new file mode 100644 index 0..55a07803fdde5 --- /dev/null +++ b/flang/test/Driver/fcc_override.f90 @@ -0,0 +1,12 @@ +! RUN: env FCC_OVERRIDE_OPTIONS="#+-Os +-Oz +-O +-O3 +-Oignore +a +b +c xb Xa Omagic ^-### " %flang -target x86_64-unknown-linux-gnu %s -O2 b -O3 2>&1 | FileCheck %s +! RUN: env FCC_OVERRIDE_OPTIONS="x-Werror +-g" %flang -target x86_64-unknown-linux-gnu -Werror %s -c -### 2>&1 | FileCheck %s -check-prefix=RM-WERROR + +! CHECK: "-fc1" +! CHECK-NOT: "-Oignore" +! CHECK: "-Omagic" +! CHECK-NOT: "-Oignore" + +! RM-WERROR: ### FCC_OVERRIDE_OPTIONS: x-Werror +-g +! RM-WERROR-NEXT: ### Deleting argument -Werror +! RM-WERROR-NEXT: ### Adding argument -g at end +! RM-WERROR-NOT: "-Werror" diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp index ed52988feaa59..ad0efa3279cef 100644 --- a/flang/tools/flang-driver/driver.cpp +++ b/flang/tools/flang-driver/driver.cpp @@ -111,6 +111,13 @@ int main(int argc, const char **argv) { } } + llvm::StringSet<> SavedStrings; + // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the + // scenes. + if (const char *OverrideStr = ::getenv("FCC_OVERRIDE_OPTIONS")) +clang::driver::applyOverrideOptions(args, OverrideStr, SavedStrings, +"FCC_OVERRIDE_OPTIONS", &llvm::errs()); + // Not in the frontend mode - continue in the compiler driver mode. // Create DiagnosticsEngine for the compiler driver >From d1f2c9b8abd2690612a4b886a7a85b8e7f57d359 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Thu, 29 May 2025 11:05:57 +0100 Subject:
[clang] [clang] Correct FixIt ranges for unused capture warnings (PR #141148)
@@ -2164,15 +2164,29 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, bool IsLast = (I + 1) == LSI->NumExplicitCaptures; SourceRange FixItRange; if (CaptureRange.isValid()) { +auto GetTrailingEndLocation = [&](SourceLocation StartPoint) { + SourceRange NextToken = + getRangeForNextToken(StartPoint, /*IncludeComments=*/true); + if (!NextToken.isValid()) +return SourceLocation(); + // Return the last location preceding the next token + return NextToken.getBegin().getLocWithOffset(-1); +}; if (!CurHasPreviousCapture && !IsLast) { // If there are no captures preceding this capture, remove the - // following comma. - FixItRange = SourceRange(CaptureRange.getBegin(), - getLocForEndOfToken(CaptureRange.getEnd())); + // trailing comma and anything up to the next token + SourceRange CommaRange = + getRangeForNextToken(CaptureRange.getEnd()); + SourceLocation FixItEnd = + GetTrailingEndLocation(CommaRange.getBegin()); + FixItRange = SourceRange(CaptureRange.getBegin(), FixItEnd); } else { - // Otherwise, remove the comma since the last used capture. - FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc), - CaptureRange.getEnd()); + // Otherwise, remove the comma since the last used capture, and + // anything up to the next token + SourceLocation FixItStart = getLocForEndOfToken(PrevCaptureLoc); + SourceLocation FixItEnd = + GetTrailingEndLocation(CaptureRange.getEnd()); ojhunt wrote: - [ ] trying to make a visible task https://github.com/llvm/llvm-project/pull/141148 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
@@ -2235,11 +2235,22 @@ class CommandObjectTargetModulesDumpClangAST : CommandObjectTargetModulesModuleAutoComplete( interpreter, "target modules dump ast", "Dump the clang ast for a given module's symbol file.", -//"target modules dump ast [ ...]") -nullptr, eCommandRequiresTarget) {} +"target modules dump ast [--filter ] [ ...]", +eCommandRequiresTarget), +m_filter(LLDB_OPT_SET_1, false, "filter", 'f', 0, eArgTypeName, "TODO", Michael137 wrote: Whoops left a TODO in here https://github.com/llvm/llvm-project/pull/142164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Correct FixIt ranges for unused capture warnings (PR #141148)
@@ -84,6 +84,21 @@ SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); } +SourceRange Sema::getRangeForNextToken(SourceLocation Loc, + bool IncludeComments) { + if (!Loc.isValid()) +return SourceRange(); + std::optional NextToken = + Lexer::findNextToken(Loc, SourceMgr, LangOpts, IncludeComments); ojhunt wrote: @cor3ntin ping for your copious spare time :D https://github.com/llvm/llvm-project/pull/141148 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] add tags to Mustache namespace template (PR #142045)
https://github.com/evelez7 updated https://github.com/llvm/llvm-project/pull/142045 >From 7d94cff0737804c8d91712e7758439eb0cc07ff3 Mon Sep 17 00:00:00 2001 From: Erick Velez Date: Thu, 29 May 2025 14:44:29 -0700 Subject: [PATCH 1/2] [clang-doc] add tags to Mustache namespace template namespace-template.mustache only rendered placeholder text. Enum and record tags were added to the template. Now, we can render an index.html for the global namespace and other namespaces. Added tests and deleted some of the disabled unit tests. --- .../assets/namespace-template.mustache| 79 --- .../test/clang-doc/mustache-index.cpp | 74 + .../clang-doc/mustache-separate-namespace.cpp | 13 +++ .../clang-doc/HTMLMustacheGeneratorTest.cpp | 67 4 files changed, 156 insertions(+), 77 deletions(-) create mode 100644 clang-tools-extra/test/clang-doc/mustache-index.cpp create mode 100644 clang-tools-extra/test/clang-doc/mustache-separate-namespace.cpp diff --git a/clang-tools-extra/clang-doc/assets/namespace-template.mustache b/clang-tools-extra/clang-doc/assets/namespace-template.mustache index 12dc93069d1cf..10babe1d27b0b 100644 --- a/clang-tools-extra/clang-doc/assets/namespace-template.mustache +++ b/clang-tools-extra/clang-doc/assets/namespace-template.mustache @@ -23,23 +23,82 @@ -Navbar + +{{#ProjectName}} + +{{ProjectName}} + +{{/ProjectName}} + + + +Namespace + + +Class + + + + -Lorem ipsum dolor sit amet, consectetur adipiscing elit, -sed do eiusmod tempor incididunt ut labore et dolore magna -aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco -laboris nisi ut aliquip ex ea commodo consequat. -Duis aute irure dolor in reprehenderit in voluptate velit esse -cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat -cupidatat non proident, sunt in culpa qui officia deserunt mollit -anim id est laborum +{{RecordType}} {{Name}} + +{{#Enums}} + +Enums + + +{{#Obj}} + +{{EnumName}} + +{{/Obj}} + +{{/Enums}} +{{#Typedef}} +Typedef +{{/Typedef}} +{{#Record}} + +Inner Classes + + +{{#Links}} + +{{Name}} + +{{/Links}} + +{{/Record}} + -Content +{{#Enums}} + +Enumerations + +{{#Obj}} +{{>EnumPartial}} +{{/Obj}} + + +{{/Enums}} +{{#Record}} + +Inner Classes + +{{#Links}} + +class {{Name}} + +{{/Links}} + + +{{/Record}} diff --git a/clang-tools-extra/test/clang-doc/mustache-index.cpp b/clang-tools-extra/test/clang-doc/mustache-index.cpp new file mode 100644 index 0..eed1c708eaece --- /dev/null +++ b/clang-tools-extra/test/clang-doc/mustache-index.cpp @@ -0,0 +1,74 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.html + +enum Color { + RED, + BLUE, + GREEN +}; + +class Foo; + +// CHECK: +// CHECK-NEXT: Enums +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: enum Color +// CHE
[clang] [lldb] [lldb] Add filter option to AST dump command (PR #142164)
@@ -8511,8 +8512,16 @@ TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const { } #endif -void TypeSystemClang::Dump(llvm::raw_ostream &output) { - GetTranslationUnitDecl()->dump(output); +void TypeSystemClang::Dump(llvm::raw_ostream &output, + llvm::StringRef filter_string) { + auto consumer = + clang::CreateASTDumper(output /*Dump to stdout.*/, filter_string, + /*DumpDecls=*/true, + /*Deserialize=*/false, + /*DumpLookups=*/false, + /*DumpDeclTypes=*/false, clang::ADOF_Default); + lldbassert(consumer); + consumer->HandleTranslationUnit(*m_ast_up); Michael137 wrote: should probably assert on m_ast_up too https://github.com/llvm/llvm-project/pull/142164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
@@ -24,8 +24,9 @@ def err_fe_ast_file_modified : Error< DefaultFatal; def err_fe_pch_file_overridden : Error< "file '%0' from the precompiled header has been overridden">; -def note_pch_required_by : Note<"'%0' required by '%1'">; -def note_pch_rebuild_required : Note<"please rebuild precompiled header '%0'">; +def note_ast_file_required_by : Note<"'%0' required by '%1'">; +def note_ast_file_rebuild_required +: Note<"please rebuild precompiled file '%0'">; jansvoboda11 wrote: Do we use the "precompiled file" term anywhere else? If we're trying to unify and clarify the naming, why not use "AST file"? Alternatively, we could be even more specific like we already are in `err_fe_ast_file_modified`. https://github.com/llvm/llvm-project/pull/142161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Rename diag notes that assumed precompiled dependencies are pch's, NFCI (PR #142161)
@@ -24,8 +24,9 @@ def err_fe_ast_file_modified : Error< DefaultFatal; def err_fe_pch_file_overridden : Error< "file '%0' from the precompiled header has been overridden">; -def note_pch_required_by : Note<"'%0' required by '%1'">; -def note_pch_rebuild_required : Note<"please rebuild precompiled header '%0'">; +def note_ast_file_required_by : Note<"'%0' required by '%1'">; +def note_ast_file_rebuild_required +: Note<"please rebuild precompiled file '%0'">; cyndyishida wrote: I don't feel that strongly but I don't see the value added to users seeing this diagnostic by adding "AST" to "file", and it requires less logic to qualify "module file" vs "precompiled header". My main goal is to avoid emitting an incorrect diagnostic. https://github.com/llvm/llvm-project/pull/142161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Doc][NFC] Fix a typo in SanitizerSpecialCaseList doc. (PR #142168)
https://github.com/qinkunbao edited https://github.com/llvm/llvm-project/pull/142168 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Doc][NFC] Fix a typo in SanitizerSpecialCaseList doc. (PR #142168)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Qinkun Bao (qinkunbao) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/142168.diff 1 Files Affected: - (modified) clang/docs/SanitizerSpecialCaseList.rst (+1-1) ``diff diff --git a/clang/docs/SanitizerSpecialCaseList.rst b/clang/docs/SanitizerSpecialCaseList.rst index b82db78a9203c..6f924cfa97a97 100644 --- a/clang/docs/SanitizerSpecialCaseList.rst +++ b/clang/docs/SanitizerSpecialCaseList.rst @@ -102,7 +102,7 @@ supported sanitizers. char c = toobig; // also not instrumented } -If multiple entries match the source, than the latest entry takes the +If multiple entries match the source, then the latest entry takes the precedence. .. code-block:: bash `` https://github.com/llvm/llvm-project/pull/142168 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Parser] Fix lookup of builtins with pragma intrinsic (PR #142019)
https://github.com/sarnex updated https://github.com/llvm/llvm-project/pull/142019 >From 3cf1fcb8cc722bd60a91034d9ef47240bea6a751 Mon Sep 17 00:00:00 2001 From: "Sarnie, Nick" Date: Fri, 30 May 2025 08:09:45 -0700 Subject: [PATCH] Reapply "[clang][Sema] Declare builtins used in #pragma intrinsic" (#141994)" --- clang/include/clang/Parse/Parser.h| 4 + clang/lib/Parse/ParsePragma.cpp | 111 +- .../test/Sema/Inputs/builtin-system-header.h | 9 ++ .../builtin-pragma-intrinsic-namespace.cpp| 14 +++ clang/test/Sema/builtin-pragma-intrinsic.c| 25 5 files changed, 105 insertions(+), 58 deletions(-) create mode 100644 clang/test/Sema/Inputs/builtin-system-header.h create mode 100644 clang/test/Sema/builtin-pragma-intrinsic-namespace.cpp create mode 100644 clang/test/Sema/builtin-pragma-intrinsic.c diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index c4bef4729fd36..98db8201390be 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -7074,6 +7074,10 @@ class Parser : public CodeCompletionHandler { bool HandlePragmaMSOptimize(StringRef PragmaName, SourceLocation PragmaLocation); + // #pragma intrinsic("foo") + bool HandlePragmaMSIntrinsic(StringRef PragmaName, + SourceLocation PragmaLocation); + /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index 77b61af768993..052d77d6389a1 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -300,12 +300,6 @@ struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler { PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {} }; -struct PragmaMSIntrinsicHandler : public PragmaHandler { - PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {} - void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer, -Token &FirstToken) override; -}; - // "\#pragma fenv_access (on)". struct PragmaMSFenvAccessHandler : public PragmaHandler { PragmaMSFenvAccessHandler() : PragmaHandler("fenv_access") {} @@ -517,7 +511,7 @@ void Parser::initializePragmaHandlers() { PP.AddPragmaHandler(MSOptimize.get()); MSRuntimeChecks = std::make_unique(); PP.AddPragmaHandler(MSRuntimeChecks.get()); -MSIntrinsic = std::make_unique(); +MSIntrinsic = std::make_unique("intrinsic"); PP.AddPragmaHandler(MSIntrinsic.get()); MSFenvAccess = std::make_unique(); PP.AddPragmaHandler(MSFenvAccess.get()); @@ -1046,7 +1040,8 @@ void Parser::HandlePragmaMSPragma() { .Case("strict_gs_check", &Parser::HandlePragmaMSStrictGuardStackCheck) .Case("function", &Parser::HandlePragmaMSFunction) .Case("alloc_text", &Parser::HandlePragmaMSAllocText) - .Case("optimize", &Parser::HandlePragmaMSOptimize); + .Case("optimize", &Parser::HandlePragmaMSOptimize) + .Case("intrinsic", &Parser::HandlePragmaMSIntrinsic); if (!(this->*Handler)(PragmaName, PragmaLocation)) { // Pragma handling failed, and has been diagnosed. Slurp up the tokens @@ -3762,56 +3757,6 @@ void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP, /*DisableMacroExpansion=*/false, /*IsReinject=*/false); } -/// Handle the Microsoft \#pragma intrinsic extension. -/// -/// The syntax is: -/// \code -/// #pragma intrinsic(memset) -/// #pragma intrinsic(strlen, memcpy) -/// \endcode -/// -/// Pragma intrisic tells the compiler to use a builtin version of the -/// function. Clang does it anyway, so the pragma doesn't really do anything. -/// Anyway, we emit a warning if the function specified in \#pragma intrinsic -/// isn't an intrinsic in clang and suggest to include intrin.h. -void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP, -PragmaIntroducer Introducer, -Token &Tok) { - PP.Lex(Tok); - - if (Tok.isNot(tok::l_paren)) { -PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) -<< "intrinsic"; -return; - } - PP.Lex(Tok); - - bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H"); - - while (Tok.is(tok::identifier)) { -IdentifierInfo *II = Tok.getIdentifierInfo(); -if (!II->getBuiltinID()) - PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin) - << II << SuggestIntrinH; - -PP.Lex(Tok); -if (Tok.isNot(tok::comma)) - break; -PP.Lex(Tok); - } - - if (Tok.isNot(tok::r_paren)) { -PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) -<< "intrinsic"; -return; - } - PP.Lex(Tok); - - if (Tok.isNot(tok::eod)) -PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) -<< "intrinsic"; -} -
[clang] [clang][NFC] Move Diags.isIgnored check later in checkForRedundantLoop (PR #141470)
https://github.com/tbaederr closed https://github.com/llvm/llvm-project/pull/141470 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] ccb6b0d - [clang][NFC] Move Diags.isIgnored check later in checkForRedundantLoop (#141470)
Author: Timm Baeder Date: 2025-05-30T17:26:30+02:00 New Revision: ccb6b0dafda22360edea8dbf515f78db3c31e807 URL: https://github.com/llvm/llvm-project/commit/ccb6b0dafda22360edea8dbf515f78db3c31e807 DIFF: https://github.com/llvm/llvm-project/commit/ccb6b0dafda22360edea8dbf515f78db3c31e807.diff LOG: [clang][NFC] Move Diags.isIgnored check later in checkForRedundantLoop (#141470) ... Iteration. The `isIgnored()` check is more expensive than the earlier checks, so move it last. Added: Modified: clang/lib/Sema/SemaStmt.cpp Removed: diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp index bc873937f6dc5..50f5757dff5bc 100644 --- a/clang/lib/Sema/SemaStmt.cpp +++ b/clang/lib/Sema/SemaStmt.cpp @@ -2215,16 +2215,16 @@ namespace { // Return when there is nothing to check. if (!Body || !Third) return; -if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, - Third->getBeginLoc())) - return; - // Get the last statement from the loop body. CompoundStmt *CS = dyn_cast(Body); if (!CS || CS->body_empty()) return; Stmt *LastStmt = CS->body_back(); if (!LastStmt) return; +if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, + Third->getBeginLoc())) + return; + bool LoopIncrement, LastIncrement; DeclRefExpr *LoopDRE, *LastDRE; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/tarunprabhu approved this pull request. Thanks Abid. LGTM. https://github.com/llvm/llvm-project/pull/140556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [HLSL][RootSignature] Add parsing of filter enum for StaticSampler (PR #140294)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `bolt-x86_64-ubuntu-nfc` running on `bolt-worker` while building `clang,llvm` at step 8 "test-build-bolt-check-bolt". Full details are available at: https://lab.llvm.org/buildbot/#/builders/92/builds/19697 Here is the relevant piece of the build log for the reference ``` Step 8 (test-build-bolt-check-bolt) failure: test (failure) 0.015 [608/18/1] Building CXX object tools/llvm-config/CMakeFiles/llvm-config.dir/llvm-config.cpp.o 0.022 [607/18/2] Generating VCSVersion.inc 0.035 [604/18/3] Generating VCSVersion.inc 0.044 [601/18/4] Building CXX object lib/Passes/CMakeFiles/LLVMPasses.dir/PassBuilder.cpp.o 0.180 [600/18/5] Linking CXX executable bin/llvm-config 0.241 [599/18/6] Linking CXX static library lib/libLLVMPasses.a 1.594 [598/18/7] Building CXX object tools/clang/lib/Lex/CMakeFiles/obj.clangLex.dir/LexHLSLRootSignature.cpp.o 1.839 [597/18/8] Linking CXX static library lib/libclangLex.a 2.078 [596/18/9] Building CXX object lib/Frontend/HLSL/CMakeFiles/LLVMFrontendHLSL.dir/HLSLRootSignature.cpp.o FAILED: lib/Frontend/HLSL/CMakeFiles/LLVMFrontendHLSL.dir/HLSLRootSignature.cpp.o ccache /usr/bin/c++ -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/build/lib/Frontend/HLSL -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/lib/Frontend/HLSL -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/build/include -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -O3 -DNDEBUG -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -std=c++17 -MD -MT lib/Frontend/HLSL/CMakeFiles/LLVMFrontendHLSL.dir/HLSLRootSignature.cpp.o -MF lib/Frontend/HLSL/CMakeFiles/LLVMFrontendHLSL.dir/HLSLRootSignature.cpp.o.d -o lib/Frontend/HLSL/CMakeFiles/LLVMFrontendHLSL.dir/HLSLRootSignature.cpp.o -c /home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/lib/Frontend/HLSL/HLSLRootSignature.cpp In file included from /home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/lib/Frontend/HLSL/HLSLRootSignature.cpp:13: /home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h:212:10: error: declaration of ‘llvm::hlsl::rootsig::Filter llvm::hlsl::rootsig::StaticSampler::Filter’ changes meaning of ‘Filter’ [-fpermissive] 212 | Filter Filter = Filter::Anisotropic; | ^~ /home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/include/llvm/Frontend/HLSL/HLSLRootSignature.h:84:12: note: ‘Filter’ declared here as ‘enum class llvm::hlsl::rootsig::Filter’ 84 | enum class Filter { |^~ 4.744 [596/17/10] Building CXX object tools/clang/lib/Edit/CMakeFiles/obj.clangEdit.dir/RewriteObjCFoundationAPI.cpp.o FAILED: tools/clang/lib/Edit/CMakeFiles/obj.clangEdit.dir/RewriteObjCFoundationAPI.cpp.o ccache /usr/bin/c++ -DCLANG_EXPORTS -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/build/tools/clang/lib/Edit -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/clang/lib/Edit -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/clang/include -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/build/tools/clang/include -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/build/include -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-nfc/llvm-project/llvm/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual -fno-strict-aliasing -O3 -DNDEBUG -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -std=c++17 -MD -MT tools/clang/lib/Edit/CMakeFiles/obj.clangEdit.dir/RewriteObjCFoundationAPI.cpp.o -MF tools/clang/lib/Edit/CMakeFiles/obj.clangEdit.dir/RewriteObjCFoundationAPI.cpp.o.d -o tools/clang/lib/Edit/CMa
[clang] [clang-format][NFC] Clean up AnnotatingParser::consumeToken() (PR #142104)
https://github.com/HazardyKnusperkeks approved this pull request. https://github.com/llvm/llvm-project/pull/142104 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 3f0a530 - [clang-format][NFC] Clean up AnnotatingParser::consumeToken() (#142104)
Author: Owen Pan Date: 2025-05-30T01:51:23-07:00 New Revision: 3f0a5305b483560275fa494d2c1b117c6ebe350a URL: https://github.com/llvm/llvm-project/commit/3f0a5305b483560275fa494d2c1b117c6ebe350a DIFF: https://github.com/llvm/llvm-project/commit/3f0a5305b483560275fa494d2c1b117c6ebe350a.diff LOG: [clang-format][NFC] Clean up AnnotatingParser::consumeToken() (#142104) Added: Modified: clang/lib/Format/TokenAnnotator.cpp Removed: diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 23c26c821bec9..51ececc0c0e81 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1306,14 +1306,15 @@ class AnnotatingParser { // Multi-line string itself is a single annotated token. if (Tok->is(TT_TableGenMultiLineString)) return true; +auto *Prev = Tok->getPreviousNonComment(); switch (bool IsIf = false; Tok->Tok.getKind()) { case tok::plus: case tok::minus: - if (!Tok->getPreviousNonComment() && Line.MustBeDeclaration) + if (!Prev && Line.MustBeDeclaration) Tok->setType(TT_ObjCMethodSpecifier); break; case tok::colon: - if (!Tok->Previous) + if (!Prev) return false; // Goto labels and case labels are already identified in // UnwrappedLineParser. @@ -1346,8 +1347,7 @@ class AnnotatingParser { } else if (Style.isVerilog() && Tok->isNot(TT_BinaryOperator)) { // The distribution weight operators are labeled // TT_BinaryOperator by the lexer. -if (Keywords.isVerilogEnd(*Tok->Previous) || -Keywords.isVerilogBegin(*Tok->Previous)) { +if (Keywords.isVerilogEnd(*Prev) || Keywords.isVerilogBegin(*Prev)) { Tok->setType(TT_VerilogBlockLabelColon); } else if (Contexts.back().ContextKind == tok::l_square) { Tok->setType(TT_BitFieldColon); @@ -1371,50 +1371,43 @@ class AnnotatingParser { Tok->setType(TT_InlineASMColon); } else if (Contexts.back().ColonIsDictLiteral || Style.isProto()) { Tok->setType(TT_DictLiteral); -if (Style.isTextProto()) { - if (FormatToken *Previous = Tok->getPreviousNonComment()) -Previous->setType(TT_SelectorName); -} +if (Prev && Style.isTextProto()) + Prev->setType(TT_SelectorName); } else if (Contexts.back().ColonIsObjCMethodExpr || Line.startsWith(TT_ObjCMethodSpecifier)) { Tok->setType(TT_ObjCMethodExpr); -const FormatToken *BeforePrevious = Tok->Previous->Previous; +const auto *PrevPrev = Prev->Previous; // Ensure we tag all identifiers in method declarations as // TT_SelectorName. bool UnknownIdentifierInMethodDeclaration = Line.startsWith(TT_ObjCMethodSpecifier) && -Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown); -if (!BeforePrevious || +Prev->is(tok::identifier) && Prev->is(TT_Unknown); +if (!PrevPrev || // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. -!(BeforePrevious->is(TT_CastRParen) || - (BeforePrevious->is(TT_ObjCMethodExpr) && - BeforePrevious->is(tok::colon))) || -BeforePrevious->is(tok::r_square) || +!(PrevPrev->is(TT_CastRParen) || + (PrevPrev->is(TT_ObjCMethodExpr) && PrevPrev->is(tok::colon))) || +PrevPrev->is(tok::r_square) || Contexts.back().LongestObjCSelectorName == 0 || UnknownIdentifierInMethodDeclaration) { - Tok->Previous->setType(TT_SelectorName); - if (!Contexts.back().FirstObjCSelectorName) { -Contexts.back().FirstObjCSelectorName = Tok->Previous; - } else if (Tok->Previous->ColumnWidth > - Contexts.back().LongestObjCSelectorName) { -Contexts.back().LongestObjCSelectorName = -Tok->Previous->ColumnWidth; - } - Tok->Previous->ParameterIndex = + Prev->setType(TT_SelectorName); + if (!Contexts.back().FirstObjCSelectorName) +Contexts.back().FirstObjCSelectorName = Prev; + else if (Prev->ColumnWidth > Contexts.back().LongestObjCSelectorName) +Contexts.back().LongestObjCSelectorName = Prev->ColumnWidth; + Prev->ParameterIndex = Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; } } else if (Contexts.back().ColonIsForRangeExpr) { Tok->setType(TT_RangeBasedForLoopColon); -for (auto *Prev = Tok->Previous; - Prev && !Prev->isOneOf(tok::semi, tok::l_paren); - Prev = Prev->Previous) { - if (Prev->isPointerOrReference()) -Prev
[clang] [clang-format][NFC] Clean up AnnotatingParser::consumeToken() (PR #142104)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/142104 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 5483190 - [RISCV] Add shlcofideleg extension (#141572)
Author: Ying Chen Date: 2025-05-30T16:52:08+08:00 New Revision: 5483190216cb0ff3b9f0e1a3ca901ad1b259ba82 URL: https://github.com/llvm/llvm-project/commit/5483190216cb0ff3b9f0e1a3ca901ad1b259ba82 DIFF: https://github.com/llvm/llvm-project/commit/5483190216cb0ff3b9f0e1a3ca901ad1b259ba82.diff LOG: [RISCV] Add shlcofideleg extension (#141572) This is for `shlcofideleg` extension, that supports delegating LCOFI interrupts to VS-mode. Spec: https://github.com/riscv/riscv-isa-manual/blob/main/src/hypervisor.adoc Added: Modified: clang/test/Driver/print-supported-extensions-riscv.c clang/test/Preprocessor/riscv-target-features.c llvm/docs/RISCVUsage.rst llvm/docs/ReleaseNotes.md llvm/lib/Target/RISCV/RISCVFeatures.td llvm/test/CodeGen/RISCV/attributes.ll llvm/test/CodeGen/RISCV/features-info.ll llvm/test/MC/RISCV/attribute-arch.s llvm/unittests/TargetParser/RISCVISAInfoTest.cpp Removed: diff --git a/clang/test/Driver/print-supported-extensions-riscv.c b/clang/test/Driver/print-supported-extensions-riscv.c index 7b4f46cdb4443..95464f06378e2 100644 --- a/clang/test/Driver/print-supported-extensions-riscv.c +++ b/clang/test/Driver/print-supported-extensions-riscv.c @@ -119,6 +119,7 @@ // CHECK-NEXT: sha 1.0 'Sha' (Augmented Hypervisor) // CHECK-NEXT: shcounterenw 1.0 'Shcounterenw' (Support writeable hcounteren enable bit for any hpmcounter that is not read-only zero) // CHECK-NEXT: shgatpa 1.0 'Shgatpa' (SvNNx4 mode supported for all modes supported by satp, as well as Bare) +// CHECK-NEXT: shlcofideleg 1.0 'Shlcofideleg' (Delegating LCOFI Interrupts to VS-mode) // CHECK-NEXT: shtvala 1.0 'Shtvala' (htval provides all needed values) // CHECK-NEXT: shvsatpa 1.0 'Shvsatpa' (vsatp supports all modes supported by satp) // CHECK-NEXT: shvstvala1.0 'Shvstvala' (vstval provides all needed values) diff --git a/clang/test/Preprocessor/riscv-target-features.c b/clang/test/Preprocessor/riscv-target-features.c index e3b456e0245f7..86085c21a95aa 100644 --- a/clang/test/Preprocessor/riscv-target-features.c +++ b/clang/test/Preprocessor/riscv-target-features.c @@ -24,6 +24,7 @@ // CHECK-NOT: __riscv_sha {{.*$}} // CHECK-NOT: __riscv_shcounterenw {{.*$}} // CHECK-NOT: __riscv_shgatpa {{.*$}} +// CHECK-NOT: __riscv_shlcofideleg {{.*$}} // CHECK-NOT: __riscv_shtvala {{.*$}} // CHECK-NOT: __riscv_shvsatpa {{.*$}} // CHECK-NOT: __riscv_shvstvala {{.*$}} @@ -370,6 +371,14 @@ // RUN: -o - | FileCheck --check-prefix=CHECK-SHGATPA-EXT %s // CHECK-SHGATPA-EXT: __riscv_shgatpa 100{{$}} +// RUN: %clang --target=riscv32-unknown-linux-gnu \ +// RUN: -march=rv32ishlcofideleg -E -dM %s \ +// RUN: -o - | FileCheck --check-prefix=CHECK-SHLCOFIDELEG-EXT %s +// RUN: %clang --target=riscv64-unknown-linux-gnu \ +// RUN: -march=rv64ishlcofideleg -E -dM %s \ +// RUN: -o - | FileCheck --check-prefix=CHECK-SHLCOFIDELEG-EXT %s +// CHECK-SHLCOFIDELEG-EXT: __riscv_shlcofideleg 100{{$}} + // RUN: %clang --target=riscv32-unknown-linux-gnu \ // RUN: -march=rv32ishtvala -E -dM %s \ // RUN: -o - | FileCheck --check-prefix=CHECK-SHTVALA-EXT %s diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst index 9ac21052eb66c..7d0d0cc21a27d 100644 --- a/llvm/docs/RISCVUsage.rst +++ b/llvm/docs/RISCVUsage.rst @@ -123,6 +123,7 @@ on support follow. ``Sha`` Supported ``Shcounterenw`` Assembly Support (`See note <#riscv-profiles-extensions-note>`__) ``Shgatpa`` Assembly Support (`See note <#riscv-profiles-extensions-note>`__) + ``Shlcofideleg`` Supported ``Shtvala`` Assembly Support (`See note <#riscv-profiles-extensions-note>`__) ``Shvsatpa`` Assembly Support (`See note <#riscv-profiles-extensions-note>`__) ``Shvstvala`` Assembly Support (`See note <#riscv-profiles-extensions-note>`__) diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md index f1d1ce0ada227..d69000d639db4 100644 --- a/llvm/docs/ReleaseNotes.md +++ b/llvm/docs/ReleaseNotes.md @@ -201,6 +201,7 @@ Changes to the RISC-V Backend * Adds experimental assembler support for the SiFive Xsfmm* Attached Matrix Extensions. * `-mcpu=andes-a25` and `-mcpu=andes-ax25` were added. +* The `Shlcofideleg` extension was added. Changes to the WebAssembly Backend -- diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td b/llvm/lib/Target/RISCV/RISCVFeatures.td index 86576ed190d14..690068d05aaab 100644 --- a/llvm/lib/Target/RISCV/RISCVFeatures.td +++ b/llvm/lib/Target/RISCV/RISCVFeatures.td @@ -906,6 +906,10 @@ def FeatureStdExtShvsatpa : RISCVExtension<1, 0, "vsatp supports all modes supported by satp">; +def FeatureStd
[clang] [clang-format] Handle bit-field colon of non-numeric-constant size (PR #142110)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fix #142050 --- Full diff: https://github.com/llvm/llvm-project/pull/142110.diff 2 Files Affected: - (modified) clang/lib/Format/TokenAnnotator.cpp (+3-1) - (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+8) ``diff diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 51ececc0c0e81..f8272811bbe6c 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1411,7 +1411,9 @@ class AnnotatingParser { assert(Prev); if (Prev->isPointerOrReference()) Prev->setFinalizedType(TT_PointerOrReference); - } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { + } else if ((CurrentToken && CurrentToken->is(tok::numeric_constant)) || + (Prev && Prev->is(TT_StartOfName) && !Scopes.empty() && + Scopes.back() == ST_Class)) { Tok->setType(TT_BitFieldColon); } else if (Contexts.size() == 1 && !Line.getFirstNonComment()->isOneOf(tok::kw_enum, tok::kw_case, diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index f39468424a393..1a5ed4b9040c2 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -4076,6 +4076,14 @@ TEST_F(TokenAnnotatorTest, EnumColonInTypedef) { EXPECT_TOKEN(Tokens[2], tok::colon, TT_Unknown); // Not TT_InheritanceColon. } +TEST_F(TokenAnnotatorTest, BitFieldColon) { + auto Tokens = annotate("class C {\n" + " int f : SIZE;\n" + "};"); + ASSERT_EQ(Tokens.size(), 11u) << Tokens; + EXPECT_TOKEN(Tokens[5], tok::colon, TT_BitFieldColon); +} + } // namespace } // namespace format } // namespace clang `` https://github.com/llvm/llvm-project/pull/142110 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add shlcofideleg extension (PR #141572)
https://github.com/wangpc-pp closed https://github.com/llvm/llvm-project/pull/141572 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [UBSan][Ignorelist] Expanding =sanitize to fun. (PR #142074)
https://github.com/qinkunbao updated https://github.com/llvm/llvm-project/pull/142074 >From e12e5dfc241bcc9eb28f616e96cc9eebba918b7c Mon Sep 17 00:00:00 2001 From: Qinkun Bao Date: Fri, 30 May 2025 01:21:37 + Subject: [PATCH 1/3] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?= =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created using spr 1.3.6 [skip ci] --- clang/include/clang/Basic/NoSanitizeList.h | 2 ++ clang/lib/Basic/NoSanitizeList.cpp | 27 ++ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/clang/include/clang/Basic/NoSanitizeList.h b/clang/include/clang/Basic/NoSanitizeList.h index 43415859fcd54..266dfc0d217cb 100644 --- a/clang/include/clang/Basic/NoSanitizeList.h +++ b/clang/include/clang/Basic/NoSanitizeList.h @@ -29,6 +29,8 @@ class SanitizerSpecialCaseList; class NoSanitizeList { std::unique_ptr SSCL; SourceManager &SM; + bool containsPrefix(SanitizerMask Mask, StringRef Prefix, StringRef Name, + StringRef Category = StringRef()) const; public: NoSanitizeList(const std::vector &NoSanitizeListPaths, diff --git a/clang/lib/Basic/NoSanitizeList.cpp b/clang/lib/Basic/NoSanitizeList.cpp index 9f0f1c64995cb..a1ca31ea0e970 100644 --- a/clang/lib/Basic/NoSanitizeList.cpp +++ b/clang/lib/Basic/NoSanitizeList.cpp @@ -27,6 +27,21 @@ NoSanitizeList::NoSanitizeList(const std::vector &NoSanitizePaths, NoSanitizeList::~NoSanitizeList() = default; +bool NoSanitizeList::containsPrefix(SanitizerMask Mask, StringRef Prefix, +StringRef Name, StringRef Category) const { + std::pair NoSan = + SSCL->inSectionBlame(Mask, Prefix, Name, Category); + if (NoSan == llvm::SpecialCaseList::NotFound) +return false; + std::pair San = + SSCL->inSectionBlame(Mask, Prefix, Name, "sanitize"); + // The statement evaluates to true under the following conditions: + // 1. The string "prefix:*=sanitize" is absent. + // 2. If "prefix:*=sanitize" is present, its (File Index, Line Number) is less + // than that of "prefix:*". + return San == llvm::SpecialCaseList::NotFound || NoSan > San; +} + bool NoSanitizeList::containsGlobal(SanitizerMask Mask, StringRef GlobalName, StringRef Category) const { return SSCL->inSection(Mask, "global", GlobalName, Category); @@ -34,11 +49,7 @@ bool NoSanitizeList::containsGlobal(SanitizerMask Mask, StringRef GlobalName, bool NoSanitizeList::containsType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category) const { - auto NoSan = SSCL->inSectionBlame(Mask, "type", MangledTypeName, Category); - if (NoSan == llvm::SpecialCaseList::NotFound) -return false; - auto San = SSCL->inSectionBlame(Mask, "type", MangledTypeName, "sanitize"); - return San == llvm::SpecialCaseList::NotFound || NoSan > San; + return containsPrefix(Mask, "type", MangledTypeName, Category); } bool NoSanitizeList::containsFunction(SanitizerMask Mask, @@ -48,11 +59,7 @@ bool NoSanitizeList::containsFunction(SanitizerMask Mask, bool NoSanitizeList::containsFile(SanitizerMask Mask, StringRef FileName, StringRef Category) const { - auto NoSan = SSCL->inSectionBlame(Mask, "src", FileName, Category); - if (NoSan == llvm::SpecialCaseList::NotFound) -return false; - auto San = SSCL->inSectionBlame(Mask, "src", FileName, "sanitize"); - return San == llvm::SpecialCaseList::NotFound || NoSan > San; + return containsPrefix(Mask, "src", FileName, Category); } bool NoSanitizeList::containsMainFile(SanitizerMask Mask, StringRef FileName, >From bfd9272989f83e9c3eca47c03919335830f1995d Mon Sep 17 00:00:00 2001 From: Qinkun Bao Date: Thu, 29 May 2025 21:23:21 -0400 Subject: [PATCH 2/3] Update clang/test/CodeGen/ubsan-function-ignorelist.test Co-authored-by: Copilot <175728472+copi...@users.noreply.github.com> --- clang/test/CodeGen/ubsan-function-ignorelist.test | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/test/CodeGen/ubsan-function-ignorelist.test b/clang/test/CodeGen/ubsan-function-ignorelist.test index ce8d37253e2fc..0107e761ba029 100644 --- a/clang/test/CodeGen/ubsan-function-ignorelist.test +++ b/clang/test/CodeGen/ubsan-function-ignorelist.test @@ -14,7 +14,7 @@ // The same type can appear multiple times within an ignorelist. Any ``=sanitize`` type // entries enable sanitizer instrumentation, even if it was ignored by entries before. -// If multiple entries match the source, than the latest entry takes the +// If multiple entries match the source, then the latest entry takes the // precedence. >From 61f995364bdd2c353801e8570aa3dd90afc17c71 Mon Sep 17 00:00:00 2001 From: Qinkun Bao Date: Fri, 30 May 2025 02:20:00 + Subject: [PATCH 3/3] Fix the test. Created using spr 1.3.6
[clang] [NoSanitizeList][NFI] Add containsPrefix to remove duplicated logics. (PR #142027)
https://github.com/qinkunbao closed https://github.com/llvm/llvm-project/pull/142027 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/abidh updated https://github.com/llvm/llvm-project/pull/140556 >From 5d20af48673adebc2ab3e1a6c8442f67d84f1847 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Mon, 19 May 2025 15:21:25 +0100 Subject: [PATCH 1/5] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. This PR add functionality to change flang command line using environment variable `FCC_OVERRIDE_OPTIONS`. It is quite similar to what `CCC_OVERRIDE_OPTIONS` does for clang. The `FCC_OVERRIDE_OPTIONS` seemed like the most obvious name to me but I am open to other ideas. The `applyOverrideOptions` now takes an extra argument that is the name of the environment variable. Previously `CCC_OVERRIDE_OPTIONS` was hardcoded. --- clang/include/clang/Driver/Driver.h | 2 +- clang/lib/Driver/Driver.cpp | 4 ++-- clang/tools/driver/driver.cpp | 2 +- flang/test/Driver/fcc_override.f90 | 12 flang/tools/flang-driver/driver.cpp | 7 +++ 5 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 flang/test/Driver/fcc_override.f90 diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h index b463dc2a93550..7ca848f11b561 100644 --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -879,7 +879,7 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args, /// See applyOneOverrideOption. void applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideOpts, - llvm::StringSet<> &SavedStrings, + llvm::StringSet<> &SavedStrings, StringRef EnvVar, raw_ostream *OS = nullptr); } // end namespace driver diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index a648cc928afdc..a8fea35926a0d 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -7289,7 +7289,7 @@ static void applyOneOverrideOption(raw_ostream &OS, void driver::applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideStr, llvm::StringSet<> &SavedStrings, - raw_ostream *OS) { + StringRef EnvVar, raw_ostream *OS) { if (!OS) OS = &llvm::nulls(); @@ -7298,7 +7298,7 @@ void driver::applyOverrideOptions(SmallVectorImpl &Args, OS = &llvm::nulls(); } - *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n"; + *OS << "### " << EnvVar << ": " << OverrideStr << "\n"; // This does not need to be efficient. diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index 82f47ab973064..81964c65c2892 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -305,7 +305,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) { // FIXME: Driver shouldn't take extra initial argument. driver::applyOverrideOptions(Args, OverrideStr, SavedStrings, - &llvm::errs()); + "CCC_OVERRIDE_OPTIONS", &llvm::errs()); } std::string Path = GetExecutablePath(ToolContext.Path, CanonicalPrefixes); diff --git a/flang/test/Driver/fcc_override.f90 b/flang/test/Driver/fcc_override.f90 new file mode 100644 index 0..55a07803fdde5 --- /dev/null +++ b/flang/test/Driver/fcc_override.f90 @@ -0,0 +1,12 @@ +! RUN: env FCC_OVERRIDE_OPTIONS="#+-Os +-Oz +-O +-O3 +-Oignore +a +b +c xb Xa Omagic ^-### " %flang -target x86_64-unknown-linux-gnu %s -O2 b -O3 2>&1 | FileCheck %s +! RUN: env FCC_OVERRIDE_OPTIONS="x-Werror +-g" %flang -target x86_64-unknown-linux-gnu -Werror %s -c -### 2>&1 | FileCheck %s -check-prefix=RM-WERROR + +! CHECK: "-fc1" +! CHECK-NOT: "-Oignore" +! CHECK: "-Omagic" +! CHECK-NOT: "-Oignore" + +! RM-WERROR: ### FCC_OVERRIDE_OPTIONS: x-Werror +-g +! RM-WERROR-NEXT: ### Deleting argument -Werror +! RM-WERROR-NEXT: ### Adding argument -g at end +! RM-WERROR-NOT: "-Werror" diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp index ed52988feaa59..ad0efa3279cef 100644 --- a/flang/tools/flang-driver/driver.cpp +++ b/flang/tools/flang-driver/driver.cpp @@ -111,6 +111,13 @@ int main(int argc, const char **argv) { } } + llvm::StringSet<> SavedStrings; + // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the + // scenes. + if (const char *OverrideStr = ::getenv("FCC_OVERRIDE_OPTIONS")) +clang::driver::applyOverrideOptions(args, OverrideStr, SavedStrings, +"FCC_OVERRIDE_OPTIONS", &llvm::errs()); + // Not in the frontend mode - continue in the compiler driver mode. // Create DiagnosticsEngine for the compiler driver >From d1f2c9b8abd2690612a4b886a7a85b8e7f57d359 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Thu, 29 May 2025 11:05:57 +0100 Subject:
[clang] 2a3afa2 - [NoSanitizeList][NFI] Add containsPrefix to remove duplicated logics. (#142027)
Author: Qinkun Bao Date: 2025-05-30T05:26:41-04:00 New Revision: 2a3afa2feb90844ad0f8b0bc57663e2aec06cd0a URL: https://github.com/llvm/llvm-project/commit/2a3afa2feb90844ad0f8b0bc57663e2aec06cd0a DIFF: https://github.com/llvm/llvm-project/commit/2a3afa2feb90844ad0f8b0bc57663e2aec06cd0a.diff LOG: [NoSanitizeList][NFI] Add containsPrefix to remove duplicated logics. (#142027) See https://github.com/llvm/llvm-project/pull/142006 and https://github.com/llvm/llvm-project/issues/139128 - Co-authored-by: Vitaly Buka Added: Modified: clang/include/clang/Basic/NoSanitizeList.h clang/lib/Basic/NoSanitizeList.cpp Removed: diff --git a/clang/include/clang/Basic/NoSanitizeList.h b/clang/include/clang/Basic/NoSanitizeList.h index 43415859fcd54..a7a7a29d50a9a 100644 --- a/clang/include/clang/Basic/NoSanitizeList.h +++ b/clang/include/clang/Basic/NoSanitizeList.h @@ -29,6 +29,8 @@ class SanitizerSpecialCaseList; class NoSanitizeList { std::unique_ptr SSCL; SourceManager &SM; + bool containsPrefix(SanitizerMask Mask, StringRef Prefix, StringRef Name, + StringRef Category) const; public: NoSanitizeList(const std::vector &NoSanitizeListPaths, diff --git a/clang/lib/Basic/NoSanitizeList.cpp b/clang/lib/Basic/NoSanitizeList.cpp index 9f0f1c64995cb..a1ca31ea0e970 100644 --- a/clang/lib/Basic/NoSanitizeList.cpp +++ b/clang/lib/Basic/NoSanitizeList.cpp @@ -27,6 +27,21 @@ NoSanitizeList::NoSanitizeList(const std::vector &NoSanitizePaths, NoSanitizeList::~NoSanitizeList() = default; +bool NoSanitizeList::containsPrefix(SanitizerMask Mask, StringRef Prefix, +StringRef Name, StringRef Category) const { + std::pair NoSan = + SSCL->inSectionBlame(Mask, Prefix, Name, Category); + if (NoSan == llvm::SpecialCaseList::NotFound) +return false; + std::pair San = + SSCL->inSectionBlame(Mask, Prefix, Name, "sanitize"); + // The statement evaluates to true under the following conditions: + // 1. The string "prefix:*=sanitize" is absent. + // 2. If "prefix:*=sanitize" is present, its (File Index, Line Number) is less + // than that of "prefix:*". + return San == llvm::SpecialCaseList::NotFound || NoSan > San; +} + bool NoSanitizeList::containsGlobal(SanitizerMask Mask, StringRef GlobalName, StringRef Category) const { return SSCL->inSection(Mask, "global", GlobalName, Category); @@ -34,11 +49,7 @@ bool NoSanitizeList::containsGlobal(SanitizerMask Mask, StringRef GlobalName, bool NoSanitizeList::containsType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category) const { - auto NoSan = SSCL->inSectionBlame(Mask, "type", MangledTypeName, Category); - if (NoSan == llvm::SpecialCaseList::NotFound) -return false; - auto San = SSCL->inSectionBlame(Mask, "type", MangledTypeName, "sanitize"); - return San == llvm::SpecialCaseList::NotFound || NoSan > San; + return containsPrefix(Mask, "type", MangledTypeName, Category); } bool NoSanitizeList::containsFunction(SanitizerMask Mask, @@ -48,11 +59,7 @@ bool NoSanitizeList::containsFunction(SanitizerMask Mask, bool NoSanitizeList::containsFile(SanitizerMask Mask, StringRef FileName, StringRef Category) const { - auto NoSan = SSCL->inSectionBlame(Mask, "src", FileName, Category); - if (NoSan == llvm::SpecialCaseList::NotFound) -return false; - auto San = SSCL->inSectionBlame(Mask, "src", FileName, "sanitize"); - return San == llvm::SpecialCaseList::NotFound || NoSan > San; + return containsPrefix(Mask, "src", FileName, Category); } bool NoSanitizeList::containsMainFile(SanitizerMask Mask, StringRef FileName, ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. (PR #140556)
https://github.com/abidh updated https://github.com/llvm/llvm-project/pull/140556 >From 5d20af48673adebc2ab3e1a6c8442f67d84f1847 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Mon, 19 May 2025 15:21:25 +0100 Subject: [PATCH 1/6] [flang][driver] Introduce FCC_OVERRIDE_OPTIONS. This PR add functionality to change flang command line using environment variable `FCC_OVERRIDE_OPTIONS`. It is quite similar to what `CCC_OVERRIDE_OPTIONS` does for clang. The `FCC_OVERRIDE_OPTIONS` seemed like the most obvious name to me but I am open to other ideas. The `applyOverrideOptions` now takes an extra argument that is the name of the environment variable. Previously `CCC_OVERRIDE_OPTIONS` was hardcoded. --- clang/include/clang/Driver/Driver.h | 2 +- clang/lib/Driver/Driver.cpp | 4 ++-- clang/tools/driver/driver.cpp | 2 +- flang/test/Driver/fcc_override.f90 | 12 flang/tools/flang-driver/driver.cpp | 7 +++ 5 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 flang/test/Driver/fcc_override.f90 diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h index b463dc2a93550..7ca848f11b561 100644 --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -879,7 +879,7 @@ llvm::Error expandResponseFiles(SmallVectorImpl &Args, /// See applyOneOverrideOption. void applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideOpts, - llvm::StringSet<> &SavedStrings, + llvm::StringSet<> &SavedStrings, StringRef EnvVar, raw_ostream *OS = nullptr); } // end namespace driver diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index a648cc928afdc..a8fea35926a0d 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -7289,7 +7289,7 @@ static void applyOneOverrideOption(raw_ostream &OS, void driver::applyOverrideOptions(SmallVectorImpl &Args, const char *OverrideStr, llvm::StringSet<> &SavedStrings, - raw_ostream *OS) { + StringRef EnvVar, raw_ostream *OS) { if (!OS) OS = &llvm::nulls(); @@ -7298,7 +7298,7 @@ void driver::applyOverrideOptions(SmallVectorImpl &Args, OS = &llvm::nulls(); } - *OS << "### CCC_OVERRIDE_OPTIONS: " << OverrideStr << "\n"; + *OS << "### " << EnvVar << ": " << OverrideStr << "\n"; // This does not need to be efficient. diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index 82f47ab973064..81964c65c2892 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -305,7 +305,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { if (const char *OverrideStr = ::getenv("CCC_OVERRIDE_OPTIONS")) { // FIXME: Driver shouldn't take extra initial argument. driver::applyOverrideOptions(Args, OverrideStr, SavedStrings, - &llvm::errs()); + "CCC_OVERRIDE_OPTIONS", &llvm::errs()); } std::string Path = GetExecutablePath(ToolContext.Path, CanonicalPrefixes); diff --git a/flang/test/Driver/fcc_override.f90 b/flang/test/Driver/fcc_override.f90 new file mode 100644 index 0..55a07803fdde5 --- /dev/null +++ b/flang/test/Driver/fcc_override.f90 @@ -0,0 +1,12 @@ +! RUN: env FCC_OVERRIDE_OPTIONS="#+-Os +-Oz +-O +-O3 +-Oignore +a +b +c xb Xa Omagic ^-### " %flang -target x86_64-unknown-linux-gnu %s -O2 b -O3 2>&1 | FileCheck %s +! RUN: env FCC_OVERRIDE_OPTIONS="x-Werror +-g" %flang -target x86_64-unknown-linux-gnu -Werror %s -c -### 2>&1 | FileCheck %s -check-prefix=RM-WERROR + +! CHECK: "-fc1" +! CHECK-NOT: "-Oignore" +! CHECK: "-Omagic" +! CHECK-NOT: "-Oignore" + +! RM-WERROR: ### FCC_OVERRIDE_OPTIONS: x-Werror +-g +! RM-WERROR-NEXT: ### Deleting argument -Werror +! RM-WERROR-NEXT: ### Adding argument -g at end +! RM-WERROR-NOT: "-Werror" diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp index ed52988feaa59..ad0efa3279cef 100644 --- a/flang/tools/flang-driver/driver.cpp +++ b/flang/tools/flang-driver/driver.cpp @@ -111,6 +111,13 @@ int main(int argc, const char **argv) { } } + llvm::StringSet<> SavedStrings; + // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the + // scenes. + if (const char *OverrideStr = ::getenv("FCC_OVERRIDE_OPTIONS")) +clang::driver::applyOverrideOptions(args, OverrideStr, SavedStrings, +"FCC_OVERRIDE_OPTIONS", &llvm::errs()); + // Not in the frontend mode - continue in the compiler driver mode. // Create DiagnosticsEngine for the compiler driver >From d1f2c9b8abd2690612a4b886a7a85b8e7f57d359 Mon Sep 17 00:00:00 2001 From: Abid Qadeer Date: Thu, 29 May 2025 11:05:57 +0100 Subject:
[clang] [flang] [mlir] [flang] Add support for -mrecip[=] (PR #142172)
@@ -1251,6 +1251,164 @@ static bool parseIntegerOverflowArgs(CompilerInvocation &invoc, return true; } +/// This is a helper function for validating the optional refinement step +/// parameter in reciprocal argument strings. Return false if there is an error +/// parsing the refinement step. Otherwise, return true and set the Position +/// of the refinement step in the input string. +/// +/// \param [in] in The input string +/// \param [in] a The compiler invocation arguments to parse +/// \param [out] position The position of the refinement step in input string +/// \param [out] diags DiagnosticsEngine to report erros with +static bool getRefinementStep(llvm::StringRef in, const llvm::opt::Arg &a, + size_t &position, + clang::DiagnosticsEngine &diags) { + const char refinementStepToken = ':'; + position = in.find(refinementStepToken); + if (position != llvm::StringRef::npos) { +llvm::StringRef option = a.getOption().getName(); +llvm::StringRef refStep = in.substr(position + 1); +// Allow exactly one numeric character for the additional refinement +// step parameter. This is reasonable for all currently-supported +// operations and architectures because we would expect that a larger value +// of refinement steps would cause the estimate "optimization" to +// under-perform the native operation. Also, if the estimate does not +// converge quickly, it probably will not ever converge, so further +// refinement steps will not produce a better answer. +if (refStep.size() != 1) { + diags.Report(clang::diag::err_drv_invalid_value) << option << refStep; + return false; +} +char refStepChar = refStep[0]; +if (refStepChar < '0' || refStepChar > '9') { + diags.Report(clang::diag::err_drv_invalid_value) << option << refStep; + return false; +} + } + return true; +} + +/// Parses all -mrecip= arguments and populates the +/// CompilerInvocation accordingly. Returns false if new errors are generated. +/// +/// \param [out] invoc Stores the processed arguments +/// \param [in] args The compiler invocation arguments to parse +/// \param [out] diags DiagnosticsEngine to report erros with +static bool parseMRecip(CompilerInvocation &invoc, llvm::opt::ArgList &args, +clang::DiagnosticsEngine &diags) { + llvm::StringRef disabledPrefixIn = "!"; + llvm::StringRef disabledPrefixOut = "!"; + llvm::StringRef enabledPrefixOut = ""; + llvm::StringRef out = ""; + Fortran::frontend::CodeGenOptions &opts = invoc.getCodeGenOpts(); + + const llvm::opt::Arg *a = + args.getLastArg(clang::driver::options::OPT_mrecip, + clang::driver::options::OPT_mrecip_EQ); + if (!a) +return true; + + unsigned numOptions = a->getNumValues(); + if (numOptions == 0) { +// No option is the same as "all". +opts.Reciprocals = "all"; +return true; + } + + // Pass through "all", "none", or "default" with an optional refinement step. + if (numOptions == 1) { +llvm::StringRef val = a->getValue(0); +size_t refStepLoc; +if (!getRefinementStep(val, *a, refStepLoc, diags)) + return false; +llvm::StringRef valBase = val.slice(0, refStepLoc); +if (valBase == "all" || valBase == "none" || valBase == "default") { + opts.Reciprocals = args.MakeArgString(val); + return true; +} + } + + // Each reciprocal type may be enabled or disabled individually. + // Check each input value for validity, concatenate them all back together, + // and pass through. + + llvm::StringMap optionStrings; + optionStrings.insert(std::make_pair("divd", false)); + optionStrings.insert(std::make_pair("divf", false)); + optionStrings.insert(std::make_pair("divh", false)); + optionStrings.insert(std::make_pair("vec-divd", false)); + optionStrings.insert(std::make_pair("vec-divf", false)); + optionStrings.insert(std::make_pair("vec-divh", false)); + optionStrings.insert(std::make_pair("sqrtd", false)); + optionStrings.insert(std::make_pair("sqrtf", false)); + optionStrings.insert(std::make_pair("sqrth", false)); + optionStrings.insert(std::make_pair("vec-sqrtd", false)); + optionStrings.insert(std::make_pair("vec-sqrtf", false)); + optionStrings.insert(std::make_pair("vec-sqrth", false)); eugeneepshteyn wrote: FYI, it may be cleaner to do something like this: `optionStrings["divd"] = false;`, etc. https://github.com/llvm/llvm-project/pull/142172 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [mlir] [flang] Add support for -mrecip[=] (PR #142172)
@@ -1251,6 +1251,164 @@ static bool parseIntegerOverflowArgs(CompilerInvocation &invoc, return true; } +/// This is a helper function for validating the optional refinement step +/// parameter in reciprocal argument strings. Return false if there is an error +/// parsing the refinement step. Otherwise, return true and set the Position +/// of the refinement step in the input string. +/// +/// \param [in] in The input string +/// \param [in] a The compiler invocation arguments to parse +/// \param [out] position The position of the refinement step in input string +/// \param [out] diags DiagnosticsEngine to report erros with +static bool getRefinementStep(llvm::StringRef in, const llvm::opt::Arg &a, + size_t &position, + clang::DiagnosticsEngine &diags) { + const char refinementStepToken = ':'; + position = in.find(refinementStepToken); + if (position != llvm::StringRef::npos) { +llvm::StringRef option = a.getOption().getName(); +llvm::StringRef refStep = in.substr(position + 1); +// Allow exactly one numeric character for the additional refinement +// step parameter. This is reasonable for all currently-supported +// operations and architectures because we would expect that a larger value +// of refinement steps would cause the estimate "optimization" to +// under-perform the native operation. Also, if the estimate does not +// converge quickly, it probably will not ever converge, so further +// refinement steps will not produce a better answer. +if (refStep.size() != 1) { + diags.Report(clang::diag::err_drv_invalid_value) << option << refStep; + return false; +} +char refStepChar = refStep[0]; +if (refStepChar < '0' || refStepChar > '9') { + diags.Report(clang::diag::err_drv_invalid_value) << option << refStep; + return false; +} + } + return true; +} + +/// Parses all -mrecip= arguments and populates the +/// CompilerInvocation accordingly. Returns false if new errors are generated. +/// +/// \param [out] invoc Stores the processed arguments +/// \param [in] args The compiler invocation arguments to parse +/// \param [out] diags DiagnosticsEngine to report erros with +static bool parseMRecip(CompilerInvocation &invoc, llvm::opt::ArgList &args, +clang::DiagnosticsEngine &diags) { + llvm::StringRef disabledPrefixIn = "!"; + llvm::StringRef disabledPrefixOut = "!"; + llvm::StringRef enabledPrefixOut = ""; + llvm::StringRef out = ""; + Fortran::frontend::CodeGenOptions &opts = invoc.getCodeGenOpts(); + + const llvm::opt::Arg *a = + args.getLastArg(clang::driver::options::OPT_mrecip, + clang::driver::options::OPT_mrecip_EQ); + if (!a) +return true; + + unsigned numOptions = a->getNumValues(); + if (numOptions == 0) { +// No option is the same as "all". +opts.Reciprocals = "all"; +return true; + } + + // Pass through "all", "none", or "default" with an optional refinement step. + if (numOptions == 1) { +llvm::StringRef val = a->getValue(0); +size_t refStepLoc; +if (!getRefinementStep(val, *a, refStepLoc, diags)) + return false; +llvm::StringRef valBase = val.slice(0, refStepLoc); +if (valBase == "all" || valBase == "none" || valBase == "default") { + opts.Reciprocals = args.MakeArgString(val); + return true; +} + } + + // Each reciprocal type may be enabled or disabled individually. + // Check each input value for validity, concatenate them all back together, + // and pass through. + + llvm::StringMap optionStrings; + optionStrings.insert(std::make_pair("divd", false)); + optionStrings.insert(std::make_pair("divf", false)); + optionStrings.insert(std::make_pair("divh", false)); + optionStrings.insert(std::make_pair("vec-divd", false)); + optionStrings.insert(std::make_pair("vec-divf", false)); + optionStrings.insert(std::make_pair("vec-divh", false)); + optionStrings.insert(std::make_pair("sqrtd", false)); + optionStrings.insert(std::make_pair("sqrtf", false)); + optionStrings.insert(std::make_pair("sqrth", false)); + optionStrings.insert(std::make_pair("vec-sqrtd", false)); + optionStrings.insert(std::make_pair("vec-sqrtf", false)); + optionStrings.insert(std::make_pair("vec-sqrth", false)); + + for (unsigned i = 0; i != numOptions; ++i) { +llvm::StringRef val = a->getValue(i); + +bool isDisabled = val.starts_with(disabledPrefixIn); +// Ignore the disablement token for string matching. +if (isDisabled) + val = val.substr(1); + +size_t refStep; +if (!getRefinementStep(val, *a, refStep, diags)) + return false; + +llvm::StringRef valBase = val.slice(0, refStep); +llvm::StringMap::iterator optionIter = optionStrings.find(valBase); +if (optionIter == optionStrings.end()) { + // Try again specifying float suffix. + optionIter = optionStrings.find(valBase.str() + 'f')
[clang] [flang] [mlir] [flang] Add support for -mrecip[=] (PR #142172)
https://github.com/vzakhari commented: LGTM, though, I think we'd better reuse the code from `Clang.cpp`. `flangFrontend` already depends on `clangDriver`, so we just need to export `ParseMRecip` and `getRefinementStep` from `clangDriver` (and probably replace their `Driver` argument with a `DiagnosticEngine` argument, so that it works for both clang and flang). https://github.com/llvm/llvm-project/pull/142172 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] add tags to Mustache namespace template (PR #142045)
https://github.com/evelez7 edited https://github.com/llvm/llvm-project/pull/142045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 45218e0 - [NFC] Tweak docs for unique-object-duplication warning (#142158)
Author: Devon Loehr Date: 2025-05-30T11:54:44-04:00 New Revision: 45218e01d69ecb6428afcff19c9dde2cc792cdd6 URL: https://github.com/llvm/llvm-project/commit/45218e01d69ecb6428afcff19c9dde2cc792cdd6 DIFF: https://github.com/llvm/llvm-project/commit/45218e01d69ecb6428afcff19c9dde2cc792cdd6.diff LOG: [NFC] Tweak docs for unique-object-duplication warning (#142158) This improves the documentation for the unique-object-duplication warning. It clarifies the conditions for the warning to fire, provides clearer instructions on how to resolve it, and adjusts wording to be more precise. Added: Modified: clang/include/clang/Basic/DiagnosticGroups.td Removed: diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index abb5cefb1d2bb..60c650583801a 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -811,7 +811,7 @@ changes to one object won't affect the others, the object's initializer will run once per copy, etc. Specifically, this warning fires when it detects an object which: - 1. Appears in a header file (so it might get compiled into multiple libaries), and + 1. Is defined as ``inline`` in a header file (so it might get compiled into multiple libaries), and 2. Has external linkage (otherwise it's supposed to be duplicated), and 3. Has hidden visibility. @@ -819,13 +819,17 @@ As well as one of the following: 1. The object is mutable, or 2. The object's initializer definitely has side effects. -The warning is best resolved by making the object ``const`` (if possible), or by explicitly -giving the object non-hidden visibility, e.g. using ``__attribute((visibility("default")))``. -Note that all levels of a pointer variable must be constant; ``const int*`` will -trigger the warning because the pointer itself is mutable. +The warning can be resolved by removing one of the conditions above. In rough +order of preference, this may be done by: + 1. Marking the object ``const`` (if possible) + 2. Moving the object's definition to a source file + 3. Giving the object non-hidden visibility, e.g. using ``__attribute((visibility("default")))``. -This warning is currently disabled on Windows since it uses import/export rules -instead of visibility. +Note that for (2), all levels of a pointer variable must be constant; +``const int*`` will trigger the warning because the pointer itself is mutable. + +This warning is not yet implemented for Windows, since Windows uses +import/export rules instead of visibility. }]; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits