[clang] [llvm] [Clang] -fseparate-named-sections option (PR #91028)
MaskRay wrote: > This is an alternative approach to address the issue described in > [discourse.llvm.org/t/rfc-support-for-memory-regions-in-elf/78570](https://discourse.llvm.org/t/rfc-support-for-memory-regions-in-elf/78570) > which doesn't require a custom section type. This RFC is about `SHT_LLVM_MEMORY` while this patch seems orthogonal? I agree that the option is useful in some cases. If `ld -r` is used, `--unique` will be needed to not destroy granularity. https://github.com/llvm/llvm-project/pull/91028 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang] -fseparate-named-sections option (PR #91028)
@@ -75,6 +75,10 @@ static cl::opt JumpTableInFunctionSection( "jumptable-in-function-section", cl::Hidden, cl::init(false), cl::desc("Putting Jump Table in function section")); +static cl::opt UniqueExplicitSections( +"unique-explicit-sections", cl::Hidden, cl::init(true), MaskRay wrote: untested https://github.com/llvm/llvm-project/pull/91028 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][Driver] Clean up RenderFloatingPointOptions() (PR #91017)
https://github.com/MaskRay approved this pull request. https://github.com/llvm/llvm-project/pull/91017 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxxabi] [llvm] Add support for WASI builds (PR #91051)
https://github.com/veluca93 created https://github.com/llvm/llvm-project/pull/91051 This PR modifies the LLVM source code to compile (and run) in a WASI environment. The question of whether having WASI support in LLVM is one that doesn't have a clear answer for me (although of course I can see some use cases), but since the patch ended up being small enough I figured I'd create a PR and see what the LLVM community would make of it :-) The code compiles & runs successfully when compiled with an unmodified wasi-libc (I only tested running clang++ and wasm-ld). Caveats: - a bunch of things are not supported. Most importantly, executing binaries is not supported, but also memory mapping, signals, dynamic linking, set/longjump, and JIT. - There are no tests. I also would not know how to go about adding tests. - Some projects are disabled on WASI. >From efed655cadea23fe2bf2e3bd4b555f0a815af4fc Mon Sep 17 00:00:00 2001 From: Luca Versari Date: Wed, 1 May 2024 15:42:57 +0200 Subject: [PATCH 1/2] Adapt the build system for WASI. --- clang/CMakeLists.txt | 2 +- libcxxabi/src/CMakeLists.txt | 4 ++-- llvm/cmake/modules/HandleLLVMOptions.cmake | 4 llvm/lib/CMakeLists.txt| 2 ++ llvm/lib/Transforms/CMakeLists.txt | 2 ++ llvm/tools/CMakeLists.txt | 4 6 files changed, 15 insertions(+), 3 deletions(-) diff --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt index cf97e3c6e851ae..8e2a59566702fd 100644 --- a/clang/CMakeLists.txt +++ b/clang/CMakeLists.txt @@ -427,7 +427,7 @@ CMAKE_DEPENDENT_OPTION(CLANG_PLUGIN_SUPPORT # If libstdc++ is statically linked, clang-repl needs to statically link libstdc++ # itself, which is not possible in many platforms because of current limitations in # JIT stack. (more platforms need to be supported by JITLink) -if(NOT LLVM_STATIC_LINK_CXX_STDLIB) +if(NOT LLVM_STATIC_LINK_CXX_STDLIB AND NOT WASI) set(HAVE_CLANG_REPL_SUPPORT ON) endif() diff --git a/libcxxabi/src/CMakeLists.txt b/libcxxabi/src/CMakeLists.txt index c8cc93de50777b..9c86ba7051ad1c 100644 --- a/libcxxabi/src/CMakeLists.txt +++ b/libcxxabi/src/CMakeLists.txt @@ -36,8 +36,8 @@ else() ) endif() -if (LIBCXXABI_ENABLE_THREADS AND (UNIX OR FUCHSIA) AND NOT (APPLE OR CYGWIN) -AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX")) +if (LIBCXXABI_ENABLE_THREADS AND (UNIX OR FUCHSIA OR WASI) AND NOT + (APPLE OR CYGWIN) AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX")) list(APPEND LIBCXXABI_SOURCES cxa_thread_atexit.cpp ) diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake b/llvm/cmake/modules/HandleLLVMOptions.cmake index 185266c0861e86..292a5c957f1104 100644 --- a/llvm/cmake/modules/HandleLLVMOptions.cmake +++ b/llvm/cmake/modules/HandleLLVMOptions.cmake @@ -217,6 +217,10 @@ elseif(FUCHSIA OR UNIX) else() set(LLVM_HAVE_LINK_VERSION_SCRIPT 1) endif() +elseif(WASI) + set(LLVM_ON_WIN32 0) + set(LLVM_ON_UNIX 1) + set(LLVM_HAVE_LINK_VERSION_SCRIPT 0) elseif(CMAKE_SYSTEM_NAME STREQUAL "Generic") set(LLVM_ON_WIN32 0) set(LLVM_ON_UNIX 0) diff --git a/llvm/lib/CMakeLists.txt b/llvm/lib/CMakeLists.txt index 74e2d03c07953d..b32411ae0b8600 100644 --- a/llvm/lib/CMakeLists.txt +++ b/llvm/lib/CMakeLists.txt @@ -31,7 +31,9 @@ add_subdirectory(Remarks) add_subdirectory(Debuginfod) add_subdirectory(DebugInfo) add_subdirectory(DWP) +if (NOT WASI) add_subdirectory(ExecutionEngine) +endif () add_subdirectory(Target) add_subdirectory(AsmParser) add_subdirectory(LineEditor) diff --git a/llvm/lib/Transforms/CMakeLists.txt b/llvm/lib/Transforms/CMakeLists.txt index 84a7e34147d084..1843abf1bdaa46 100644 --- a/llvm/lib/Transforms/CMakeLists.txt +++ b/llvm/lib/Transforms/CMakeLists.txt @@ -5,7 +5,9 @@ add_subdirectory(InstCombine) add_subdirectory(Scalar) add_subdirectory(IPO) add_subdirectory(Vectorize) +if (NOT WASI) add_subdirectory(Hello) +endif () add_subdirectory(ObjCARC) add_subdirectory(Coroutines) add_subdirectory(CFGuard) diff --git a/llvm/tools/CMakeLists.txt b/llvm/tools/CMakeLists.txt index db66dad5dc0dbd..acd3cde1f85c11 100644 --- a/llvm/tools/CMakeLists.txt +++ b/llvm/tools/CMakeLists.txt @@ -28,12 +28,14 @@ endif() # Add LTO, llvm-ar, llvm-config, and llvm-profdata before clang, ExternalProject # requires targets specified in DEPENDS to exist before the call to # ExternalProject_Add. +if (NOT WASI) add_llvm_tool_subdirectory(lto) add_llvm_tool_subdirectory(gold) add_llvm_tool_subdirectory(llvm-ar) add_llvm_tool_subdirectory(llvm-config) add_llvm_tool_subdirectory(llvm-lto) add_llvm_tool_subdirectory(llvm-profdata) +endif () # Projects supported via LLVM_EXTERNAL_*_SOURCE_DIR need to be explicitly # specified. @@ -43,6 +45,7 @@ add_llvm_external_project(mlir) # accordingly so place them afterwards add_llvm_external_project(clang) add_llvm_external_project(flang) +if (NOT WASI) add_llvm_external_project(lldb) add_llvm_external_project(bolt) @@ -54,6 +57,7 @@ ad
[clang] [libcxxabi] [llvm] Add support for WASI builds (PR #91051)
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/91051 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Treat (foo())->bar() like foo()->bar(). (PR #91052)
https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/91052 None >From 357b8bfa0cef2632930e3f037ed66360b0fa3615 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Sat, 4 May 2024 00:38:08 -0700 Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Treat (foo())->bar() like foo()->bar(). --- clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp | 4 clang/test/Analysis/Checkers/WebKit/call-args.cpp | 11 +++ 2 files changed, 15 insertions(+) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp index b36fa95bc73f3e..4b14cdbf10a3da 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp @@ -27,6 +27,10 @@ tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) { E = tempExpr->getSubExpr(); continue; } +if (auto* tempExpr = dyn_cast(E)) { + E = tempExpr->getSubExpr(); + continue; +} if (auto *cast = dyn_cast(E)) { if (StopAtFirstRefCountedObj) { if (auto *ConversionFunc = diff --git a/clang/test/Analysis/Checkers/WebKit/call-args.cpp b/clang/test/Analysis/Checkers/WebKit/call-args.cpp index 2a4b6bb1f1063a..45d900d4ba880e 100644 --- a/clang/test/Analysis/Checkers/WebKit/call-args.cpp +++ b/clang/test/Analysis/Checkers/WebKit/call-args.cpp @@ -313,6 +313,17 @@ namespace default_arg { } } +namespace cxx_member_func { + Ref provideProtected(); + void foo() { +provide()->trivial(); +provide()->method(); +// expected-warning@-1{{Call argument for 'this' parameter is uncounted and unsafe}} +provideProtected()->method(); +(provideProtected())->method(); + }; +} + namespace cxx_member_operator_call { // The hidden this-pointer argument without a corresponding parameter caused couple bugs in parameter <-> argument attribution. struct Foo { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 294eecd - [clang][docs] fix rendering issue in UsersManual.rst (#90308)
Author: Nikita Kniazev Date: 2024-05-04T09:57:38+02:00 New Revision: 294eecd4cbd8a1e0dcc0cdbe1238817b92ba7668 URL: https://github.com/llvm/llvm-project/commit/294eecd4cbd8a1e0dcc0cdbe1238817b92ba7668 DIFF: https://github.com/llvm/llvm-project/commit/294eecd4cbd8a1e0dcc0cdbe1238817b92ba7668.diff LOG: [clang][docs] fix rendering issue in UsersManual.rst (#90308) Added: Modified: clang/docs/UsersManual.rst Removed: diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst index 370de7d9c769e8..80ba70f67126fa 100644 --- a/clang/docs/UsersManual.rst +++ b/clang/docs/UsersManual.rst @@ -3504,7 +3504,7 @@ Differences between ``*17`` and ``*23`` modes: - ``nullptr`` and ``nullptr_t`` are supported, only in ``*23`` mode. - ``ATOMIC_VAR_INIT`` is removed from ``*23`` mode. - ``bool``, ``true``, ``false``, ``alignas``, ``alignof``, ``static_assert``, - and ``thread_local` are now first-class keywords, only in ``*23`` mode. + and ``thread_local`` are now first-class keywords, only in ``*23`` mode. - ``typeof`` and ``typeof_unqual`` are supported, only ``*23`` mode. - Bit-precise integers (``_BitInt(N)``) are supported by default in ``*23`` mode, and as an extension in ``*17`` and earlier modes. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix rendering issue in UsersManual.rst (PR #90308)
https://github.com/cor3ntin closed https://github.com/llvm/llvm-project/pull/90308 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Implement P2809: Trivial infinite loops are not Undefined Behavior (PR #90066)
@@ -908,6 +908,69 @@ void CodeGenFunction::EmitIfStmt(const IfStmt &S) { incrementProfileCounter(&S); } +bool CodeGenFunction::checkIfLoopMustProgress(const Expr *ControllingExpression, + bool HasEmptyBody) { + if (CGM.getCodeGenOpts().getFiniteLoops() == + CodeGenOptions::FiniteLoopsKind::Never) +return false; + + // Now apply rules for plain C (see 6.8.5.6 in C11). + // Loops with constant conditions do not have to make progress in any C + // version. + // As an extension, we consisider loops whose constant expression + // can be constant-folded. + Expr::EvalResult Result; + bool CondIsConstInt = cor3ntin wrote: > I guess we could also say that if the condition would evaluate to false if > we treat it as manifestly constant-evaluated, it's not manifestly > constant-evaluated. So we'd amend [expr.const]p20 to say something like: "An > expression or conversion is manifestly constant-evaluated if it is [...] the > condition of trivially empty iteration statement, is a constant expression > when interpreted as a constant-expression, and the constant expression would > evaluate to true". Do we have _any_ motivation for doing so? In addition of being extremely mind-bendy, there is no practical application. https://github.com/llvm/llvm-project/pull/90066 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AArch64] Add support for Qualcomm Oryon processor (PR #91022)
pinskia wrote: Note the corresponding GCC patch: https://gcc.gnu.org/pipermail/gcc-patches/2024-May/650664.html https://github.com/llvm/llvm-project/pull/91022 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AArch64] Support preserve_none calling convention (PR #91046)
pinskia wrote: I don't think you can use x16 and x17 for argument passing due to them being reserved for PLTs and call veneers. https://github.com/llvm/llvm-project/pull/91046 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Use `const&` avoiding copies (PR #90334)
lipracer wrote: This change seems to be unrelated to the platform, and I don't think it's the change that caused the CI error. From the compiled log, it seems that there is not enough memory space. https://github.com/llvm/llvm-project/assets/22370779/d1acbd6b-45e4-46c0-b297-9d0a8f8abedb";> https://github.com/llvm/llvm-project/pull/90334 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
https://github.com/rymiel approved this pull request. I can definitely think of cases where an expression might contain `...` and still have redundant parentheses, i.e. if the ellipsis isn't part of a fold expression For example: ```c++ template std::tuple foo() { return (std::tuple{}); } ``` Those parens around the returned expression are redundant, but they would now no longer be removed. I wouldn't worry too much about this, but, pedantically, you can be sure it's a fold expression if the ellipsis is followed with or preceded by an operator https://eel.is/c++draft/expr.prim.fold#nt:fold-operator https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Don't allow comma in front of structural enum (PR #91056)
https://github.com/rymiel created https://github.com/llvm/llvm-project/pull/91056 Assume that a comma in front of `enum` means it is actually a part of an elaborated type in a template parameter list. Fixes https://github.com/llvm/llvm-project/issues/47782 >From f625311fe7259a07607cc2bb8c13e05715775c68 Mon Sep 17 00:00:00 2001 From: Emilia Kond Date: Sat, 4 May 2024 12:57:49 +0300 Subject: [PATCH] [clang-format] Don't allow comma in front of structural enum Assume that a comma in front of `enum` means it is actually a part of an elaborated type in a template parameter list. Fixes https://github.com/llvm/llvm-project/issues/47782 --- clang/lib/Format/UnwrappedLineParser.cpp | 5 +++-- clang/unittests/Format/TokenAnnotatorTest.cpp | 4 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index e8a8dd58d07eea..b5415fa9ecab55 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -1763,8 +1763,9 @@ void UnwrappedLineParser::parseStructuralElement( break; } case tok::kw_enum: - // Ignore if this is part of "template enum". - if (Previous && Previous->isOneOf(tok::less, tok::arrow)) { + // Ignore if this is part of "template enum" or + // "template <..., enum ...>". + if (Previous && Previous->isOneOf(tok::less, tok::arrow, tok::comma)) { nextToken(); break; } diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index 01daf8dee505bc..b424424b85777b 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -489,6 +489,10 @@ TEST_F(TokenAnnotatorTest, UnderstandsStructs) { EXPECT_TOKEN(Tokens[24], tok::amp, TT_UnaryOperator); EXPECT_TOKEN(Tokens[27], tok::l_square, TT_ArraySubscriptLSquare); EXPECT_TOKEN(Tokens[32], tok::r_brace, TT_StructRBrace); + + Tokens = annotate("template struct S {};"); + ASSERT_EQ(Tokens.size(), 15u) << Tokens; + EXPECT_TOKEN(Tokens[11], tok::l_brace, TT_StructLBrace); } TEST_F(TokenAnnotatorTest, UnderstandsUnions) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Use `const&` avoiding copies (PR #90334)
SimplyDanny wrote: > This change seems to be unrelated to the platform, and I don't think it's the > change that caused the CI error. From the compiled log, it seems that there > is not enough memory space. width="1499" > src="https://private-user-images.githubusercontent.com/22370779/327938136-d1acbd6b-45e4-46c0-b297-9d0a8f8abedb.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MTQ4MTkzMTYsIm5iZiI6MTcxNDgxOTAxNiwicGF0aCI6Ii8yMjM3MDc3OS8zMjc5MzgxMzYtZDFhY2JkNmItNDVlNC00NmMwLWIyOTctOWQwYThmOGFiZWRiLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA1MDQlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNTA0VDEwMzY1NlomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTU1ZjVkZGVkZmFmODA0OWM0MmI4Zjg5OTRkYTBmZWJjNGFmNTc5MmM1ZjY0YmQ4ZmRmZGM5YzIyYzgxMDhkZGMmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.QXRMCiD3fniqXEUHLPOAjqAcfAM3jDgBr3ZFcNQ4jNc";> Okay, that's good news. I wasn't sure because I've not found any other builds to fail like this and mine reported failure twice. But indeed I face the same excessive RAM consumption when building the `flang` target locally on `main`. https://github.com/llvm/llvm-project/pull/90334 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Throw error when calling atomic with pointer to zero size object (PR #91057)
https://github.com/HendrikHuebner created https://github.com/llvm/llvm-project/pull/91057 When an atomic builtin is called with a pointer to an object of size zero, an arithmetic exception gets thrown because there is a modulo operation with the objects size in codegen. This is described here: #90330 I have added a check to SemaChecking.cpp, which throws an error if this is the case. From fc0588cb0d3558d518dc7d352f6590e0fbae0608 Mon Sep 17 00:00:00 2001 From: hhuebner Date: Sat, 4 May 2024 13:49:38 +0200 Subject: [PATCH] [Clang] Throw error when calling atomic with pointer to zero size object --- .../clang/Basic/DiagnosticFrontendKinds.td| 3 ++ clang/lib/Sema/SemaChecking.cpp | 12 ++- clang/test/Sema/atomic-ops.c | 32 +++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index fcffadacc8e631..0c50f125b8e05d 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -328,6 +328,9 @@ def warn_atomic_op_misaligned : Warning< "; the expected alignment (%0 bytes) exceeds the actual alignment (%1 bytes)">, InGroup; +def err_atomic_op_size_zero : Error< + "First argument cannot be a pointer to an object of size zero">; + def warn_atomic_op_oversized : Warning< "large atomic operation may incur " "significant performance penalty" diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index e33113ab9c4c1d..d822fbedc9ae68 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -40,6 +40,7 @@ #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" @@ -8495,7 +8496,9 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, << 0 << AdjustedNumArgs << static_cast(Args.size()) << /*is non object*/ 0 << ExprRange; return ExprError(); - } else if (Args.size() > AdjustedNumArgs) { + } + + if (Args.size() > AdjustedNumArgs) { Diag(Args[AdjustedNumArgs]->getBeginLoc(), diag::err_typecheck_call_too_many_args) << 0 << AdjustedNumArgs << static_cast(Args.size()) @@ -8542,6 +8545,13 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, } } + // pointer to object of size zero is not allowed + if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) { +Diag(ExprRange.getBegin(), diag::err_atomic_op_size_zero) +<< Ptr->getSourceRange(); +return ExprError(); + } + // For an arithmetic operation, the implied arithmetic must be well-formed. if (Form == Arithmetic) { // GCC does not enforce these rules for GNU atomics, but we do to help catch diff --git a/clang/test/Sema/atomic-ops.c b/clang/test/Sema/atomic-ops.c index 1d36667d6cf409..97da2582312bbb 100644 --- a/clang/test/Sema/atomic-ops.c +++ b/clang/test/Sema/atomic-ops.c @@ -639,6 +639,38 @@ void memory_checks(_Atomic(int) *Ap, int *p, int val) { (void)__atomic_compare_exchange_n(p, p, val, 0, memory_order_seq_cst, -1); // expected-warning {{memory order argument to atomic operation is invalid}} } +struct Z { + char z[]; +}; + +void zeroSizeArgError(struct Z *a, struct Z *b, struct Z *c) { + __atomic_exchange(b, b, c, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_release); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_exchange(b, b, c, memory_order_seq_cst); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_relaxed); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acq_rel); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_acquire); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_consume); // expected-error {{First argument cannot be a pointer to an object of size zero}} + __atomic_load(a, b, memory_order_release); // expected-error {{First argument cannot be
[clang] [Clang] Throw error when calling atomic with pointer to zero size object (PR #91057)
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/91057 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
cjappl wrote: I can confirm that now if I try to use any argument with `blocking` I get: ``` /Users/topher/Desktop/test_radsan/main.cpp:25:40: error: 'blocking' attribute takes no arguments 25 | float process (float* data) noexcept [[clang::blocking(false)]] ``` Great! https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
cjappl wrote: Possibly another bug here (or user error). I am trying to see the warnings show up for a simple test program. The clang used in this example is the tip of your branch at time of writing b95964c2570c11d1d80ae6874be5e400f7b504ad ```cpp #include #include int* process () [[clang::nonblocking]] { // THIS MALLOC SHOULD WARN, RIGHT? int* malloced_data = (int*)std::malloc(sizeof(int)); malloced_data[0] = 7; return malloced_data; } int main() { int* y = process(); printf("y[0] = %d\n", y[0]); return (int)y[0]; } ``` When I run compile and run this code, it runs, with the proper "7" exit code, but does not give me any warnings on compilation. ``` > /Users/topher/code/radsan_cjappl/build/bin/clang++ main.cpp -isysroot > /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.4.sdk > -Wfunction-effects -Werror > ./a.out y[0] = 7 > echo $? 7 ``` I highly suspect I'm doing something wrong, but can't figure out what it might be. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][PowerPC] Add flag to enable compatibility with GNU for complex arguments (PR #77732)
https://github.com/diggerlin edited https://github.com/llvm/llvm-project/pull/77732 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -1870,6 +1870,28 @@ bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, FromFn = QT->getAs(); Changed = true; } + +// For C, when called from checkPointerTypesForAssignment, +// we need not to alter FromFn, or else even an innocuous cast +// like dropping effects will fail. In C++ however we do want to +// alter FromFn. TODO: Is this correct? cjappl wrote: Did you ever get clarity on if this was correct? Calling it out as I peruse this PR, I don't have the answer but it's hidden in here so wanted to bring attention to it. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -18347,7 +18347,7 @@ void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, } } -bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, +bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New, cjappl wrote: It seems possibly strange to me that a function called "Check" would mutate a value passed into it. I would expect it to be passive. Can the mutation come later, or in a different function, or perhaps this should be renamed? https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -7963,6 +7967,148 @@ static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { llvm_unreachable("unexpected attribute kind!"); } +ExprResult Sema::ActOnEffectExpression(Expr *CondExpr, FunctionEffectMode &Mode, + bool RequireConstexpr) { + // see checkFunctionConditionAttr, Sema::CheckCXXBooleanCondition + if (RequireConstexpr || !CondExpr->isTypeDependent()) { +ExprResult E = PerformContextuallyConvertToBool(CondExpr); +if (E.isInvalid()) + return E; +CondExpr = E.get(); +if (RequireConstexpr || !CondExpr->isValueDependent()) { + llvm::APSInt CondInt; + E = VerifyIntegerConstantExpression( + E.get(), &CondInt, + // TODO: have our own diagnostic + diag::err_constexpr_if_condition_expression_is_not_constant); + if (E.isInvalid()) { +return E; + } + Mode = + (CondInt != 0) ? FunctionEffectMode::True : FunctionEffectMode::False; +} else { + Mode = FunctionEffectMode::Dependent; +} + } else { +Mode = FunctionEffectMode::Dependent; + } + return CondExpr; +} + +static bool +handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, + ParsedAttr &PAttr, QualType &QT, + FunctionTypeUnwrapper &Unwrapped) { + // Delay if this is not a function type. + if (!Unwrapped.isFunctionType()) +return false; + + // Require FunctionProtoType + auto *FPT = Unwrapped.get()->getAs(); + if (FPT == nullptr) { +// TODO: special diagnostic? +return false; + } + + // Parse the new attribute. + // non/blocking or non/allocating? Or conditional (computed)? + const bool isNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking || + PAttr.getKind() == ParsedAttr::AT_Blocking; + Sema &S = TPState.getSema(); + + FunctionEffectMode NewMode = FunctionEffectMode::None; + Expr *CondExpr = nullptr; // only valid if dependent + + if (PAttr.getKind() == ParsedAttr::AT_NonBlocking || + PAttr.getKind() == ParsedAttr::AT_NonAllocating) { +if (!PAttr.checkAtMostNumArgs(S, 1)) { + PAttr.setInvalid(); + return true; +} + +// Parse the conditional expression, if any +if (PAttr.getNumArgs() == 1) { + CondExpr = PAttr.getArgAsExpr(0); + ExprResult E = S.ActOnEffectExpression(CondExpr, NewMode); + if (E.isInvalid()) +return false; + CondExpr = NewMode == FunctionEffectMode::Dependent ? E.get() : nullptr; +} else { + NewMode = FunctionEffectMode::True; +} + } else { +// This is the `blocking` or `allocating` attribute. +if (S.CheckAttrNoArgs(PAttr)) + return true; +NewMode = FunctionEffectMode::False; + } + + const FunctionEffect::Kind FEKind = + (NewMode == FunctionEffectMode::False) + ? (isNonBlocking ? FunctionEffect::Kind::Blocking + : FunctionEffect::Kind::Allocating) + : (isNonBlocking ? FunctionEffect::Kind::NonBlocking + : FunctionEffect::Kind::NonAllocating); + const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind), + FunctionEffectCondition(CondExpr)}; + + // Diagnose the newly provided attribute as incompatible with a previous one. + auto incompatible = [&](const FunctionEffectWithCondition &PrevEC) { +S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) +<< ("'" + NewEC.description() + "'") +<< ("'" + PrevEC.description() + "'") << false; +// we don't necessarily have the location of the previous attribute, +// so no note. +PAttr.setInvalid(); +return true; + }; + + // Find previous attributes + std::optional PrevNonBlocking; + std::optional PrevNonAllocating; + + for (const FunctionEffectWithCondition &PrevEC : FPT->getFunctionEffects()) { +if (PrevEC.Effect.kind() == FEKind || +PrevEC.Effect.oppositeKind() == FEKind) + return incompatible(PrevEC); +switch (PrevEC.Effect.kind()) { +case FunctionEffect::Kind::Blocking: +case FunctionEffect::Kind::NonBlocking: + PrevNonBlocking = PrevEC; + break; +case FunctionEffect::Kind::Allocating: +case FunctionEffect::Kind::NonAllocating: + PrevNonAllocating = PrevEC; + break; +default: + break; +} + } + + if (isNonBlocking) { cjappl wrote: minor: only var I've seen so far not UpperCamelCase https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -7963,6 +7967,148 @@ static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { llvm_unreachable("unexpected attribute kind!"); } +ExprResult Sema::ActOnEffectExpression(Expr *CondExpr, FunctionEffectMode &Mode, + bool RequireConstexpr) { + // see checkFunctionConditionAttr, Sema::CheckCXXBooleanCondition + if (RequireConstexpr || !CondExpr->isTypeDependent()) { +ExprResult E = PerformContextuallyConvertToBool(CondExpr); +if (E.isInvalid()) + return E; +CondExpr = E.get(); +if (RequireConstexpr || !CondExpr->isValueDependent()) { + llvm::APSInt CondInt; + E = VerifyIntegerConstantExpression( + E.get(), &CondInt, + // TODO: have our own diagnostic + diag::err_constexpr_if_condition_expression_is_not_constant); + if (E.isInvalid()) { cjappl wrote: Minor funky 4 spacing for the first few lines here https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
https://github.com/cjappl commented: Just doing a first pass review. The guts of this are above my paygrade, but after playing with this functionally for a few days it seems to behave as intended from the realtime sanitizer team! :) https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
https://github.com/cjappl edited https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -0,0 +1,124 @@ +// RUN: %clang_cc1 %s -ast-dump -fblocks | FileCheck %s + +// Make sure that the attribute gets parsed and attached to the correct AST elements. + +#pragma clang diagnostic ignored "-Wunused-variable" + +// = +// Square brackets, true + +namespace square_brackets { + +// On the type of the FunctionDecl +void nl_function() [[clang::nonblocking]]; +// CHECK: FunctionDecl {{.*}} nl_function 'void () __attribute__((clang_nonblocking))' + +// On the type of the VarDecl holding a function pointer +void (*nl_func_a)() [[clang::nonblocking]]; +// CHECK: VarDecl {{.*}} nl_func_a 'void (*)() __attribute__((clang_nonblocking))' + +// On the type of the ParmVarDecl of a function parameter +static void nlReceiver(void (*nl_func)() [[clang::nonblocking]]); +// CHECK: ParmVarDecl {{.*}} nl_func 'void (*)() __attribute__((clang_nonblocking))' + +// As an AttributedType within the nested types of a typedef +typedef void (*nl_fp_type)() [[clang::nonblocking]]; +// CHECK: TypedefDecl {{.*}} nl_fp_type 'void (*)() __attribute__((clang_nonblocking))' +using nl_fp_talias = void (*)() [[clang::nonblocking]]; +// CHECK: TypeAliasDecl {{.*}} nl_fp_talias 'void (*)() __attribute__((clang_nonblocking))' + +// From a typedef or typealias, on a VarDecl +nl_fp_type nl_fp_var1; +// CHECK: VarDecl {{.*}} nl_fp_var1 'nl_fp_type':'void (*)() __attribute__((clang_nonblocking))' +nl_fp_talias nl_fp_var2; +// CHECK: VarDecl {{.*}} nl_fp_var2 'nl_fp_talias':'void (*)() __attribute__((clang_nonblocking))' + +// On type of a FieldDecl +struct Struct { + void (*nl_func_field)() [[clang::nonblocking]]; +// CHECK: FieldDecl {{.*}} nl_func_field 'void (*)() __attribute__((clang_nonblocking))' +}; + +// nonallocating should NOT be subsumed into nonblocking +void nl1() [[clang::nonblocking]] [[clang::nonallocating]]; +// CHECK: FunctionDecl {{.*}} nl1 'void () __attribute__((clang_nonblocking)) __attribute__((clang_nonallocating))' + +void nl2() [[clang::nonallocating]] [[clang::nonblocking]]; +// CHECK: FunctionDecl {{.*}} nl2 'void () __attribute__((clang_nonblocking)) __attribute__((clang_nonallocating))' + +decltype(nl1) nl3; +// CHECK: FunctionDecl {{.*}} nl3 'decltype(nl1)':'void () __attribute__((clang_nonblocking)) __attribute__((clang_nonallocating))' + +// Attribute propagates from base class virtual method to overrides. +struct Base { + virtual void nb_method() [[clang::nonblocking]]; +}; +struct Derived : public Base { + void nb_method() override; + // CHECK: CXXMethodDecl {{.*}} nb_method 'void () __attribute__((clang_nonblocking))' +}; + +// Dependent expression +template +struct Dependent { + void nb_method2() [[clang::nonblocking(V)]]; + // CHECK: CXXMethodDecl {{.*}} nb_method2 'void () __attribute__((clang_nonblocking(V)))' +}; + +// --- Blocks --- + +// On the type of the VarDecl holding a BlockDecl +void (^nl_block1)() [[clang::nonblocking]] = ^() [[clang::nonblocking]] {}; +// CHECK: VarDecl {{.*}} nl_block1 'void (^)() __attribute__((clang_nonblocking))' + +int (^nl_block2)() [[clang::nonblocking]] = ^() [[clang::nonblocking]] { return 0; }; +// CHECK: VarDecl {{.*}} nl_block2 'int (^)() __attribute__((clang_nonblocking))' + +// The operand of the CallExpr is an ImplicitCastExpr of a DeclRefExpr -> nl_block which hold the attribute +static void blockCaller() { nl_block1(); } +// CHECK: DeclRefExpr {{.*}} 'nl_block1' 'void (^)() __attribute__((clang_nonblocking))' + +// --- Lambdas --- + +// On the operator() of a lambda's CXXMethodDecl +auto nl_lambda = []() [[clang::nonblocking]] {}; +// CHECK: CXXMethodDecl {{.*}} operator() 'void () const __attribute__((clang_nonblocking))' inline + +// = +// Square brackets, false + +void nl_func_false() [[clang::blocking]]; +// CHECK: FunctionDecl {{.*}} nl_func_false 'void () __attribute__((clang_blocking))' + +// TODO: This exposes a bug where a type attribute is lost when inferring a lambda's +// return type. +auto nl_lambda_false = []() [[clang::blocking]] {}; + +} // namespace square_brackets + +// = +// GNU-style attribute, true + +// TODO: Duplicate more of the above for GNU-style attribute + +namespace gnu_style { + +// On the type of the FunctionDecl +void nl_function() __attribute__((clang_nonblocking)); +// CHECK: FunctionDecl {{.*}} nl_function 'void () __attribute__((clang_nonblocking))' + +// Alternate placement on the FunctionDecl +__attribute__((clang_nonblocking)) void nl_function(); +// CHECK: FunctionDecl {{.*}} nl_function 'void () __attribute__((clang_nonblocking))' + +// On the type of the VarDecl holding a function pointer +void (*nl_func_a)() __attribute__((clang_nonblocking)); +// CHECK: VarDecl {{.*}} nl_fun
[clang] [clang] Enable FPContract with optnone (PR #91061)
https://github.com/spavloff created https://github.com/llvm/llvm-project/pull/91061 Previously treatment of the attribute `optnone` was modified in https://github.com/llvm/llvm-project/pull/85605 ([clang] Set correct FPOptions if attribute 'optnone' presents). As a side effect FPContract was disabled for optnone. It created unneeded divergence with the behavior of -O0, which enables this optimization. In the discussion https://github.com/llvm/llvm-project/pull/85605#issuecomment-2089350379 it was pointed out that FP contraction should be enabled even if all optimizations are turned off, otherwise results of calculations would be different. This change enables FPContract at optnone. >From 32c0ec8a03b0c669dc595894730dd6f8a7933dea Mon Sep 17 00:00:00 2001 From: Serge Pavlov Date: Sat, 4 May 2024 12:26:22 +0700 Subject: [PATCH] [clang] Enable FPContract with optnone Previously treatment of the attribute `optnone` was modified in https://github.com/llvm/llvm-project/pull/85605 ([clang] Set correct FPOptions if attribute 'optnone' presents). As a side effect FPContract was disabled for optnone. It created unneeded divergence with the behavior of -O0, which enables this optimization. In the discussion https://github.com/llvm/llvm-project/pull/85605#issuecomment-2089350379 it was pointed out that FP contraction should be enabled even if all optimizations are turned off, otherwise results of calculations would be different. This change enables FPContract at optnone. --- clang/include/clang/Basic/LangOptions.h | 1 - clang/test/AST/ast-dump-fpfeatures.cpp | 18 +- clang/test/AST/ast-dump-fpfeatures.m | 4 ++-- clang/test/AST/ast-dump-late-parsing.cpp | 8 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index e2a2aa71b880b3..dbf4595790480a 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -970,7 +970,6 @@ class FPOptionsOverride { void setDisallowOptimizations() { setFPPreciseEnabled(true); -setDisallowFPContract(); } storage_type getAsOpaqueInt() const { diff --git a/clang/test/AST/ast-dump-fpfeatures.cpp b/clang/test/AST/ast-dump-fpfeatures.cpp index 68144e31a93043..27558cdac833b6 100644 --- a/clang/test/AST/ast-dump-fpfeatures.cpp +++ b/clang/test/AST/ast-dump-fpfeatures.cpp @@ -198,7 +198,7 @@ float func_19(float x, float y) { // CHECK-LABEL: FunctionDecl {{.*}} func_19 'float (float, float)' // CHECK: CompoundStmt {{.*}} MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) float func_20(float x, float y) try { @@ -210,7 +210,7 @@ float func_20(float x, float y) try { // CHECK-LABEL: FunctionDecl {{.*}} func_20 'float (float, float)' // CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 struct C21 { C21(float x, float y); @@ -221,15 +221,15 @@ struct C21 { }; // CHECK-LABEL: CXXMethodDecl {{.*}} a_method 'float (float, float)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '*' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '*' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) C21::C21(float x, float y) : member(x + y) {} // CHECK-LABEL: CXXConstructorDecl {{.*}} C21 'void (float, float)' // CHECK: CXXCtorInitializer {{.*}} 'member' 'float' -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 template __attribute__((optnone)) T func_22(T x, T y) { @@ -238,13 +238,13 @@ __attribute__((optnone)) T func_22(T x, T y) { // CHECK-LABEL: FunctionTemplateDecl {{.*}} func_22 // CHECK: FunctionDecl {{.*}} func_22 'T (T, T)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1
[clang] [clang] Enable FPContract with optnone (PR #91061)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Serge Pavlov (spavloff) Changes Previously treatment of the attribute `optnone` was modified in https://github.com/llvm/llvm-project/pull/85605 ([clang] Set correct FPOptions if attribute 'optnone' presents). As a side effect FPContract was disabled for optnone. It created unneeded divergence with the behavior of -O0, which enables this optimization. In the discussion https://github.com/llvm/llvm-project/pull/85605#issuecomment-2089350379 it was pointed out that FP contraction should be enabled even if all optimizations are turned off, otherwise results of calculations would be different. This change enables FPContract at optnone. --- Full diff: https://github.com/llvm/llvm-project/pull/91061.diff 4 Files Affected: - (modified) clang/include/clang/Basic/LangOptions.h (-1) - (modified) clang/test/AST/ast-dump-fpfeatures.cpp (+9-9) - (modified) clang/test/AST/ast-dump-fpfeatures.m (+2-2) - (modified) clang/test/AST/ast-dump-late-parsing.cpp (+4-4) ``diff diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index e2a2aa71b880b3..dbf4595790480a 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -970,7 +970,6 @@ class FPOptionsOverride { void setDisallowOptimizations() { setFPPreciseEnabled(true); -setDisallowFPContract(); } storage_type getAsOpaqueInt() const { diff --git a/clang/test/AST/ast-dump-fpfeatures.cpp b/clang/test/AST/ast-dump-fpfeatures.cpp index 68144e31a93043..27558cdac833b6 100644 --- a/clang/test/AST/ast-dump-fpfeatures.cpp +++ b/clang/test/AST/ast-dump-fpfeatures.cpp @@ -198,7 +198,7 @@ float func_19(float x, float y) { // CHECK-LABEL: FunctionDecl {{.*}} func_19 'float (float, float)' // CHECK: CompoundStmt {{.*}} MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) float func_20(float x, float y) try { @@ -210,7 +210,7 @@ float func_20(float x, float y) try { // CHECK-LABEL: FunctionDecl {{.*}} func_20 'float (float, float)' // CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 struct C21 { C21(float x, float y); @@ -221,15 +221,15 @@ struct C21 { }; // CHECK-LABEL: CXXMethodDecl {{.*}} a_method 'float (float, float)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '*' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '*' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) C21::C21(float x, float y) : member(x + y) {} // CHECK-LABEL: CXXConstructorDecl {{.*}} C21 'void (float, float)' // CHECK: CXXCtorInitializer {{.*}} 'member' 'float' -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 template __attribute__((optnone)) T func_22(T x, T y) { @@ -238,13 +238,13 @@ __attribute__((optnone)) T func_22(T x, T y) { // CHECK-LABEL: FunctionTemplateDecl {{.*}} func_22 // CHECK: FunctionDecl {{.*}} func_22 'T (T, T)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: FunctionDecl {{.*}} func_22 'float (float, float)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 float func_23(float x, float y) { return func_22(x, y); diff --git a/clang/test/AST/ast-dump-fpfeatures.m b/clang/test/AST/ast-dump-fpfeatures.m index cf77529a756811..2294c0a14a5e38 100644 --- a/clang/test/AST/ast-dump-f
[clang] [CIR] Build out AST consumer patterns to reach the entry point into CIRGen (PR #91007)
llvmbot wrote: @llvm/pr-subscribers-clangir Author: Nathan Lanza (lanza) Changes Build out the necessary infrastructure for the main entry point into ClangIR generation -- CIRGenModule. A set of boilerplate classes exist to facilitate this -- CIRGenerator, CIRGenAction, EmitCIRAction and CIRGenConsumer. These all mirror the corresponding types from LLVM generation by Clang's CodeGen. The main entry point to CIR generation is `CIRGenModule::buildTopLevelDecl`. It is currently just an empty function. We've added a test to ensure that the pipeline reaches this point and doesn't fail, but does nothing else. This will be removed in one of the subsequent patches that'll add basic `cir.func` emission. This patch also re-adds `-emit-cir` to the driver. lib/Driver/Driver.cpp requires that a driver flag exists to facilirate the selection of the right actions for the driver to create. Without a driver flag you get the standard behaviors of `-S`, `-c`, etc. If we want to emit CIR IR and, eventually, bytecode we'll need a driver flag to force this. This is why `-emit-llvm` is a driver flag. Notably, `-emit-llvm-bc` as a cc1 flag doesn't ever do the right thing. Without a driver flag it is incorrectly ignored and an executable is emitted. With `-S` a file named `something.s` is emitted which actually contains bitcode. --- Full diff: https://github.com/llvm/llvm-project/pull/91007.diff 16 Files Affected: - (added) clang/include/clang/CIR/CIRGenerator.h (+59) - (added) clang/include/clang/CIRFrontendAction/CIRGenAction.h (+61) - (modified) clang/include/clang/Driver/Options.td (+1-1) - (modified) clang/lib/CIR/CMakeLists.txt (+2) - (added) clang/lib/CIR/CodeGen/CIRGenModule.cpp (+35) - (added) clang/lib/CIR/CodeGen/CIRGenModule.h (+61) - (added) clang/lib/CIR/CodeGen/CIRGenTypeCache.h (+27) - (added) clang/lib/CIR/CodeGen/CIRGenerator.cpp (+46) - (added) clang/lib/CIR/CodeGen/CMakeLists.txt (+23) - (added) clang/lib/CIR/FrontendAction/CIRGenAction.cpp (+88) - (added) clang/lib/CIR/FrontendAction/CMakeLists.txt (+17) - (modified) clang/lib/Driver/ToolChains/Clang.cpp (+3) - (modified) clang/lib/FrontendTool/CMakeLists.txt (+15) - (modified) clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp (+18) - (added) clang/test/CIR/hello.c (+4) - (added) clang/test/CIR/lit.local.cfg (+2) ``diff diff --git a/clang/include/clang/CIR/CIRGenerator.h b/clang/include/clang/CIR/CIRGenerator.h new file mode 100644 index 00..c9505d2473b437 --- /dev/null +++ b/clang/include/clang/CIR/CIRGenerator.h @@ -0,0 +1,59 @@ +//===- CIRGenerator.h - CIR Generation from Clang AST -===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +// +// This file declares a simple interface to perform CIR generation from Clang +// AST +// +//===--===// + +#ifndef CLANG_CIRGENERATOR_H_ +#define CLANG_CIRGENERATOR_H_ + +#include "clang/AST/ASTConsumer.h" +#include "clang/AST/DeclGroup.h" +#include "clang/Basic/CodeGenOptions.h" +#include "clang/Basic/Diagnostic.h" + +#include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/Support/VirtualFileSystem.h" + +#include + +namespace mlir { +class MLIRContext; +} // namespace mlir +namespace cir { +class CIRGenModule; + +class CIRGenerator : public clang::ASTConsumer { + virtual void anchor(); + clang::DiagnosticsEngine &Diags; + clang::ASTContext *astCtx; + llvm::IntrusiveRefCntPtr + fs; // Only used for debug info. + + const clang::CodeGenOptions codeGenOpts; // Intentionally copied in. + + [[maybe_unused]] unsigned HandlingTopLevelDecls; + +protected: + std::unique_ptr mlirCtx; + std::unique_ptr CGM; + +public: + CIRGenerator(clang::DiagnosticsEngine &diags, + llvm::IntrusiveRefCntPtr FS, + const clang::CodeGenOptions &CGO); + ~CIRGenerator(); + void Initialize(clang::ASTContext &Context) override; + bool HandleTopLevelDecl(clang::DeclGroupRef D) override; +}; + +} // namespace cir + +#endif // CLANG_CIRGENERATOR_H_ diff --git a/clang/include/clang/CIRFrontendAction/CIRGenAction.h b/clang/include/clang/CIRFrontendAction/CIRGenAction.h new file mode 100644 index 00..aaf73ec2bffc47 --- /dev/null +++ b/clang/include/clang/CIRFrontendAction/CIRGenAction.h @@ -0,0 +1,61 @@ +//=== CIRGenAction.h - CIR Code Generation Frontend Action -*- C++ -*--===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_CIR_CIRGENACTION_H
[clang] [clang-format] Don't remove parentheses of fold expressions (PR #91045)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fixes #90966. --- Full diff: https://github.com/llvm/llvm-project/pull/91045.diff 2 Files Affected: - (modified) clang/lib/Format/UnwrappedLineParser.cpp (+6-1) - (modified) clang/unittests/Format/FormatTest.cpp (+9) ``diff diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index e8a8dd58d07eea..7d0278bce9a9c6 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2510,6 +2510,7 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { assert(FormatTok->is(tok::l_paren) && "'(' expected."); auto *LeftParen = FormatTok; bool SeenEqual = false; + bool MightBeFoldExpr = false; const bool MightBeStmtExpr = Tokens->peekNextToken()->is(tok::l_brace); nextToken(); do { @@ -2521,7 +2522,7 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { parseChildBlock(); break; case tok::r_paren: - if (!MightBeStmtExpr && !Line->InMacroBody && + if (!MightBeStmtExpr && !MightBeFoldExpr && !Line->InMacroBody && Style.RemoveParentheses > FormatStyle::RPS_Leave) { const auto *Prev = LeftParen->Previous; const auto *Next = Tokens->peekNextToken(); @@ -2564,6 +2565,10 @@ bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) { parseBracedList(); } break; +case tok::ellipsis: + MightBeFoldExpr = true; + nextToken(); + break; case tok::equal: SeenEqual = true; if (Style.isCSharp() && FormatTok->is(TT_FatArrow)) diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 32ba6b6853c799..e6f8e4a06515ea 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -27204,8 +27204,14 @@ TEST_F(FormatTest, RemoveParentheses) { "if ((({ a; })))\n" " b;", Style); + verifyFormat("static_assert((std::is_constructible_v && ...));", + "static_assert(((std::is_constructible_v && ...)));", + Style); verifyFormat("return (0);", "return (((0)));", Style); verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style); + verifyFormat("return ((... && std::is_convertible_v));", + "return (((... && std::is_convertible_v)));", + Style); Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement; verifyFormat("#define Return0 return (0);", Style); @@ -27213,6 +27219,9 @@ TEST_F(FormatTest, RemoveParentheses) { verifyFormat("co_return 0;", "co_return ((0));", Style); verifyFormat("return 0;", "return (((0)));", Style); verifyFormat("return ({ 0; });", "return ((({ 0; })));", Style); + verifyFormat("return (... && std::is_convertible_v);", + "return (((... && std::is_convertible_v)));", + Style); verifyFormat("inline decltype(auto) f() {\n" " if (a) {\n" "return (a);\n" `` https://github.com/llvm/llvm-project/pull/91045 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Implement 202x conforming literals (PR #91015)
llvmbot wrote: @llvm/pr-subscribers-hlsl Author: Chris B (llvm-beanz) Changes This implements the HLSL 202x conforming literals feature. The feature proposal is available here: https://github.com/microsoft/hlsl-specs/blob/main/proposals/0017-conforming-literals.md The language specification for this behavior is available in (poorly rendered) HTML or PDF: https://microsoft.github.io/hlsl-specs/specs/hlsl.html#Lex.Literal.Float https://microsoft.github.io/hlsl-specs/specs/hlsl.pdf The main implementation details are: 1) Unsuffixed floating literals are `float`. 2) The integer `ll` suffix specifies `int64_t (aka long)` which is 64-bit because HLSL has no defined `long` keyword or `long long` type. Resolves #85714 --- Patch is 27.07 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/91015.diff 7 Files Affected: - (modified) clang/lib/Sema/SemaExpr.cpp (+11) - (modified) clang/test/AST/HLSL/vector-constructors.hlsl (+62-73) - (modified) clang/test/CodeGenHLSL/builtins/ScalarSwizzles.hlsl (+14-3) - (renamed) clang/test/SemaHLSL/Types/Arithmetic/literal_suffixes.hlsl (+1-4) - (added) clang/test/SemaHLSL/Types/Arithmetic/literal_suffixes_202x.hlsl (+115) - (renamed) clang/test/SemaHLSL/Types/Arithmetic/literal_suffixes_no_16bit.hlsl (+1-4) - (modified) clang/test/SemaHLSL/Types/BuiltinVector/ScalarSwizzles.hlsl (+11-2) ``diff diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 7190e50b156f7b..5b42cf65cf80ff 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -4103,6 +4103,8 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { Ty = Context.Float16Ty; else if (Literal.isFloat128) Ty = Context.Float128Ty; +else if (getLangOpts().HLSL) + Ty = Context.FloatTy; else Ty = Context.DoubleTy; @@ -4173,6 +4175,15 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // be an unsigned int. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; + // HLSL doesn't really have `long` or `long long`. We support the `ll` + // suffix for portability of code with C++, but both `l` and `ll` are + // 64-bit integer types, and we want the type of `1l` and `1ll` to be the + // same. + if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) { +Literal.isLong = true; +Literal.isLongLong = false; + } + // Check from smallest to largest, picking the smallest type we can. unsigned Width = 0; diff --git a/clang/test/AST/HLSL/vector-constructors.hlsl b/clang/test/AST/HLSL/vector-constructors.hlsl index 7861d5209b5d3e..5e0900bb623693 100644 --- a/clang/test/AST/HLSL/vector-constructors.hlsl +++ b/clang/test/AST/HLSL/vector-constructors.hlsl @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -ast-dump -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -ast-dump -o - %s | FileCheck %s typedef float float2 __attribute__((ext_vector_type(2))); typedef float float3 __attribute__((ext_vector_type(3))); @@ -11,41 +11,36 @@ void entry() { // For the float2 vector, we just expect a conversion from constructor // parameters to an initialization list -// CHECK: VarDecl 0x{{[0-9a-fA-F]+}} col:10 used Vec2 'float2':'float __attribute__((ext_vector_type(2)))' cinit -// CHECK-NEXT: CXXFunctionalCastExpr 0x{{[0-9a-fA-F]+}} 'float2':'float __attribute__((ext_vector_type(2)))' functional cast to float2 -// CHECK-NEXT: InitListExpr 0x{{[0-9a-fA-F]+}} 'float2':'float __attribute__((ext_vector_type(2)))' -// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-fA-F]+}} 'float' -// CHECK-NEXT: FloatingLiteral 0x{{[0-9a-fA-F]+}} 'double' 1.00e+00 -// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-fA-F]+}} 'float' -// CHECK-NEXT: FloatingLiteral 0x{{[0-9a-fA-F]+}} 'double' 2.00e+00 +// CHECK-LABEL: VarDecl 0x{{[0-9a-fA-F]+}} {{.*}} used Vec2 'float2':'float __attribute__((ext_vector_type(2)))' cinit +// CHECK-NEXT: CXXFunctionalCastExpr 0x{{[0-9a-fA-F]+}} {{.*}} 'float2':'float __attribute__((ext_vector_type(2)))' functional cast to float2 +// CHECK-NEXT: InitListExpr 0x{{[0-9a-fA-F]+}} {{.*}} 'float2':'float __attribute__((ext_vector_type(2)))' +// CHECK-NEXT: FloatingLiteral 0x{{[0-9a-fA-F]+}} {{.*}} 'float' 1.00e+00 +// CHECK-NEXT: FloatingLiteral 0x{{[0-9a-fA-F]+}} {{.*}} 'float' 2.00e+00 // For the float 3 things get fun... // Here we expect accesses to the vec2 to provide the first and second // components using ArraySubscriptExpr -// CHECK: VarDecl 0x{{[0-9a-fA-F]+}} col:10 Vec3 'float3':'float __attribute__((ext_vector_type(3)))' cinit -// CHECK-NEXT: CXXFunctionalCastExpr 0x{{[0-9a-fA-F]+}} 'float3':'float __attribute__((ext_vector_type(3)))' functional cast to float3 -// CHECK-NEXT: InitListExpr 0x{{[0-9a-fA-F]+}} 'float3':'flo
[clang] [AMDGPU] Allow the `__builtin_flt_rounds` functions on AMDGPU (PR #90994)
llvmbot wrote: @llvm/pr-subscribers-backend-amdgpu Author: Joseph Huber (jhuber6) Changes Summary: Previous patches added support for the LLVM rounding intrinsic functions. This patch allows them to me emitted using the clang builtins when targeting AMDGPU. --- Full diff: https://github.com/llvm/llvm-project/pull/90994.diff 2 Files Affected: - (modified) clang/lib/Sema/SemaChecking.cpp (+8-8) - (modified) clang/test/CodeGenOpenCL/builtins-amdgcn.cl (+12) ``diff diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index cf8840c63024d4..f5af0de57b1628 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2535,18 +2535,18 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, case Builtin::BI_bittestandset64: case Builtin::BI_interlockedbittestandreset64: case Builtin::BI_interlockedbittestandset64: -if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall, - {llvm::Triple::x86_64, llvm::Triple::arm, - llvm::Triple::thumb, - llvm::Triple::aarch64})) +if (CheckBuiltinTargetInSupported( +*this, BuiltinID, TheCall, +{llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb, + llvm::Triple::aarch64, llvm::Triple::amdgcn})) return ExprError(); break; case Builtin::BI__builtin_set_flt_rounds: -if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall, - {llvm::Triple::x86, llvm::Triple::x86_64, - llvm::Triple::arm, llvm::Triple::thumb, - llvm::Triple::aarch64})) +if (CheckBuiltinTargetInSupported( +*this, BuiltinID, TheCall, +{llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm, + llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn})) return ExprError(); break; diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl index bdca97c8878670..338d6bc95655a3 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl @@ -839,6 +839,18 @@ unsigned test_wavefrontsize() { return __builtin_amdgcn_wavefrontsize(); } +// CHECK-LABEL test_flt_rounds( +unsigned test_flt_rounds() { + + // CHECK: call i32 @llvm.get.rounding() + unsigned mode = __builtin_flt_rounds(); + + // CHECK: call void @llvm.set.rounding(i32 %0) + __builtin_set_flt_rounds(mode); + + return mode; +} + // CHECK-LABEL test_get_fpenv( unsigned long test_get_fpenv() { // CHECK: call i64 @llvm.get.fpenv.i64() `` https://github.com/llvm/llvm-project/pull/90994 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Enable FPContract with optnone (PR #91061)
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 1aeb64c8ec7b96b2301929d8a325a6e1d9ddaa2f 32c0ec8a03b0c669dc595894730dd6f8a7933dea -- clang/include/clang/Basic/LangOptions.h clang/test/AST/ast-dump-fpfeatures.cpp clang/test/AST/ast-dump-late-parsing.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index dbf4595790..75e88afbd9 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -968,9 +968,7 @@ public: setAllowFPContractAcrossStatement(); } - void setDisallowOptimizations() { -setFPPreciseEnabled(true); - } + void setDisallowOptimizations() { setFPPreciseEnabled(true); } storage_type getAsOpaqueInt() const { return (static_cast(Options.getAsOpaqueInt()) `` https://github.com/llvm/llvm-project/pull/91061 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Set correct FPOptions if attribute 'optnone' presents (PR #85605)
spavloff wrote: Hi @wjristow, Thank you for your detailed analysis. Indeed, FPContract looks more like mandatory option rather than optional optimization. I prepared PR: https://github.com/llvm/llvm-project/pull/91061, which fixes this issue. https://github.com/llvm/llvm-project/pull/85605 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
HerrCai0907 wrote: > * The auto-fix should be configurable to choose `static` or anonymous > namespace. Should I implement auto-fix for this check? Maybe some functions / variables will be marked incorrectly and cause link error because the coder just forget to include the header file but this check mark it as internal linkage. WDYT? @carlosgalvezp @PiotrZSL @EugeneZelenko @SimplyDanny https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedCallArgsChecker] Treat (foo())->bar() like foo()->bar(). (PR #91052)
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 37f6ba4fb2db2c78cda7d0a69cd0a2eff2b924e3 357b8bfa0cef2632930e3f037ed66360b0fa3615 -- clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp clang/test/Analysis/Checkers/WebKit/call-args.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp index 4b14cdbf10..5c49eecacc 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp @@ -27,7 +27,7 @@ tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) { E = tempExpr->getSubExpr(); continue; } -if (auto* tempExpr = dyn_cast(E)) { +if (auto *tempExpr = dyn_cast(E)) { E = tempExpr->getSubExpr(); continue; } `` https://github.com/llvm/llvm-project/pull/91052 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reland "[OpenMP][TR12] change property of map-type modifier." (PR #90935)
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 a8fbe500fe2ecdbd3c09ed06788092937819411f ae7c7fd37eed7ff76ffddd778685450f084f3162 -- clang/lib/Parse/ParseOpenMP.cpp clang/test/OpenMP/target_ast_print.cpp clang/test/OpenMP/target_map_messages.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index bb1cbcc233..5265d8f192 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -4323,8 +4323,8 @@ static OpenMPMapClauseKind isMapType(Parser &P) { if (!Tok.isOneOf(tok::identifier, tok::kw_delete)) return OMPC_MAP_unknown; Preprocessor &PP = P.getPreprocessor(); - unsigned MapType = getOpenMPSimpleClauseType( - OMPC_map, PP.getSpelling(Tok), P.getLangOpts()); + unsigned MapType = + getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok), P.getLangOpts()); if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc || MapType == OMPC_MAP_delete || MapType == OMPC_MAP_release) `` https://github.com/llvm/llvm-project/pull/90935 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reland "[OpenMP][TR12] change property of map-type modifier." (PR #90935)
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 a8fbe500fe2ecdbd3c09ed06788092937819411f ebb6ac3dc1cc5f4e604ec3c7e68821432856920f -- clang/lib/Parse/ParseOpenMP.cpp clang/test/OpenMP/target_ast_print.cpp clang/test/OpenMP/target_map_messages.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index 8a85e7582f..5265d8f192 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -4323,7 +4323,7 @@ static OpenMPMapClauseKind isMapType(Parser &P) { if (!Tok.isOneOf(tok::identifier, tok::kw_delete)) return OMPC_MAP_unknown; Preprocessor &PP = P.getPreprocessor(); - unsigned MapType = + unsigned MapType = getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok), P.getLangOpts()); if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc || `` https://github.com/llvm/llvm-project/pull/90935 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [webkit.RefCntblBaseVirtualDtor] Ignore WTF::RefCounted and its variants missing virtual destructor (PR #91009)
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 37f6ba4fb2db2c78cda7d0a69cd0a2eff2b924e3 2b5782f9a7f6473174ccefa005268debb79aa744 -- clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor-templates.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp index 5d3a20315f..7f4c3a7b78 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp @@ -6,8 +6,8 @@ // //===--===// -#include "DiagOutputUtils.h" #include "ASTUtils.h" +#include "DiagOutputUtils.h" #include "PtrTypesSemantics.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/RecursiveASTVisitor.h" @@ -168,7 +168,7 @@ public: return false; } - static bool isRefCountedClass(const CXXRecordDecl* D) { + static bool isRefCountedClass(const CXXRecordDecl *D) { if (!D->getTemplateInstantiationPattern()) return false; auto *NsDecl = D->getParent(); @@ -177,8 +177,9 @@ public: auto NamespaceName = safeGetName(NsDecl); auto ClsNameStr = safeGetName(D); StringRef ClsName = ClsNameStr; // FIXME: Make safeGetName return StringRef. -return NamespaceName == "WTF" && (ClsName.ends_with("RefCounted") || -ClsName == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr"); +return NamespaceName == "WTF" && + (ClsName.ends_with("RefCounted") || +ClsName == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr"); } void reportBug(const CXXRecordDecl *DerivedClass, `` https://github.com/llvm/llvm-project/pull/91009 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [webkit.RefCntblBaseVirtualDtor] Ignore WTF::RefCounted and its variants missing virtual destructor (PR #91009)
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 37f6ba4fb2db2c78cda7d0a69cd0a2eff2b924e3 a9eb73de2ee7d2eadb742498bc0efb651e0b4d9a -- clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor-templates.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp index e4d311851d..7f4c3a7b78 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp @@ -6,8 +6,8 @@ // //===--===// -#include "DiagOutputUtils.h" #include "ASTUtils.h" +#include "DiagOutputUtils.h" #include "PtrTypesSemantics.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/RecursiveASTVisitor.h" `` https://github.com/llvm/llvm-project/pull/91009 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][Driver] Clean up RenderFloatingPointOptions() (PR #91017)
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 7ec698e6edf5add1f0b49b42fba707bea4b80225 82e51e4cea0cb889842273fcac874bb52d6bd780 -- clang/lib/Driver/ToolChains/Clang.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 9286076629..76f6b94b3f 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -2800,7 +2800,8 @@ static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, for (const Arg *A : Args) { switch (A->getOption().getID()) { // If this isn't an FP option skip the claim below -default: continue; +default: + continue; case options::OPT_fcx_limited_range: if (GccRangeComplexOption.empty()) { `` https://github.com/llvm/llvm-project/pull/91017 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use constant rounding mode for floating literals (PR #90877)
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 1aeb64c8ec7b96b2301929d8a325a6e1d9ddaa2f aeb607513587924106081213335f73ba6eb0 -- clang/include/clang/Lex/LiteralSupport.h clang/lib/Lex/LiteralSupport.cpp clang/lib/Sema/SemaExpr.cpp clang/test/AST/const-fpfeatures.c clang/test/AST/const-fpfeatures.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index da107a6844..a344d1281e 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -3861,8 +3861,7 @@ static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode(); if (RM == llvm::RoundingMode::Dynamic) RM = llvm::RoundingMode::NearestTiesToEven; - APFloat::opStatus result = - Literal.GetFloatValue(Val, RM); + APFloat::opStatus result = Literal.GetFloatValue(Val, RM); // Overflow is always an error, but underflow is only an error if // we underflowed to zero (APFloat reports denormals as underflow). `` https://github.com/llvm/llvm-project/pull/90877 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Use constant rounding mode for floating literals (PR #90877)
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 1aeb64c8ec7b96b2301929d8a325a6e1d9ddaa2f cf6ff55ad4a45875a821b3ac82c22bb7917b4d67 -- clang/include/clang/Lex/LiteralSupport.h clang/lib/Lex/LiteralSupport.cpp clang/lib/Sema/SemaExpr.cpp clang/test/AST/const-fpfeatures.c clang/test/AST/const-fpfeatures.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index da107a6844..a344d1281e 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -3861,8 +3861,7 @@ static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode(); if (RM == llvm::RoundingMode::Dynamic) RM = llvm::RoundingMode::NearestTiesToEven; - APFloat::opStatus result = - Literal.GetFloatValue(Val, RM); + APFloat::opStatus result = Literal.GetFloatValue(Val, RM); // Overflow is always an error, but underflow is only an error if // we underflowed to zero (APFloat reports denormals as underflow). `` https://github.com/llvm/llvm-project/pull/90877 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Use `const&` avoiding copies (PR #90334)
https://github.com/SimplyDanny updated https://github.com/llvm/llvm-project/pull/90334 From 5b74f02a766d66cfdd97adf4e89c091b9aa1823d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danny=20M=C3=B6sch?= Date: Sat, 27 Apr 2024 11:38:20 +0200 Subject: [PATCH] [NFC] Use const& avoiding copies --- clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp index d58f5bb0919906..f8dced5dbafb60 100644 --- a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp +++ b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp @@ -295,7 +295,7 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer { OS << "Symbols:\n"; for (const auto &E : Symbols) { const MangledSymbol &Symbol = E.second; -for (auto Name : Symbol.Names) { +for (const auto &Name : Symbol.Names) { OS << " - { Name: \"" << (Symbol.ParentName.empty() || Instance.getLangOpts().CPlusPlus ? "" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e87859..8f58d9f24ba491 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e5..d389287e8f4909 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 00..4970d3339ef05d --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH 1/2] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e87859..8f58d9f24ba491 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e5..d389287e8f4909 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 00..4970d3339ef05d --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
@@ -1,4 +1,4 @@ -//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//===--- UseInternalLinkageCheck.cpp - clang-tidy EugeneZelenko wrote: Please merge into single line. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
@@ -1,7 +1,7 @@ -.. title:: clang-tidy - readability-unnecessary-external-linkage +.. title:: clang-tidy - misc-use-internal-linkage -readability-unnecessary-external-linkage - +misc-use-internal-linkage += Detects variable and function can be marked as static. EugeneZelenko wrote: Please synchronize with Release Notes after change there. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
@@ -151,8 +151,8 @@ New checks Enforces consistent style for enumerators' initialization, covering three styles: none, first only, or all initialized explicitly. -- New :doc:`readability-unnecessary-external-linkage - ` check. +- New :doc:`misc-use-internal-linkage EugeneZelenko wrote: Please keep alphabetical order (by check name) in this section. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Add 'apply all clangd fixes' and 'apply all '_' fixes' QuickFixes (PR #79867)
torshepherd wrote: Bump @HighCommander4 - did you get a chance to review this? I've been using this with great success in my local build for several months now, and the feature is _extremely_ handy. There is a slight bug that overlapping fixes are troublesome if you choose "clangd apply all", but it's minor. I can pretty easily push a fix to this, but I don't want to work more on this unless it has a chance of being reviewed/accepted https://github.com/llvm/llvm-project/pull/79867 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [llvm] [clangd] Add CodeAction to swap operands to binary operators (PR #78999)
torshepherd wrote: Ping https://github.com/llvm/llvm-project/pull/78999 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -18347,7 +18347,7 @@ void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, } } -bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, +bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New, Sirraide wrote: Afaik there are a bunch of `Check...` functions that mutate their arguments, so this doesn’t seem too strange to me—that said, if this function never actually mutates anything, then I’m fine w/ adding the `const` to document that. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
carlosgalvezp wrote: > Should I implement auto-fix for this check? As a first step we can have it without auto-fix and add that as a second step once we figure out a good way to do it. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Implement P3034R1 Module Declarations Shouldn’t be Macros (PR #90574)
cor3ntin wrote: > > I think the approach looks good. > > Do we have existing tests for the use of `module` as an identifier outside > > of a module declaration? > > IIUC, do you mean something looks like the following? I didn't find it in the > test case: > > ``` > void foo() { > int module = 0; > } > ``` Yes, it might be useful to have that somewhere I think in `ParseModuleDecl`, you want to reset the lexer kind before parsing attributes. (and add tests for that) Here is a test: ```cpp #define ATTRS [[]] #define SEMICOLON module unexpanded : unexpanded : ATTRS SEMICOLON ``` Sorry i did not notice that earlier. The goal of the paper is that the name of the module is not a macro. everything else can be, including attributes attached to the module https://github.com/llvm/llvm-project/pull/90574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH 1/3] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e87859..8f58d9f24ba491 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e5..d389287e8f4909 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 00..4970d3339ef05d --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang-tools-extra] [clang-tidy] new check readability-mark-static (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH 1/3] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e87859..8f58d9f24ba491 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e5..d389287e8f4909 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 00..4970d3339ef05d --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/HerrCai0907 edited https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/HerrCai0907 edited https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/SimplyDanny edited https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/SimplyDanny approved this pull request. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,79 @@ +//===--- UseInternalLinkageCheck.cpp - clang-tidy--===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseInternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/ADT/STLExtras.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::misc { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + return llvm::all_of(Node.redecls(), [&](const Decl *D) { +return Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation()); + }); +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.getStorageClass() == SC_Extern; +} + +} // namespace + +void UseInternalLinkageCheck::registerMatchers(MatchFinder *Finder) { + auto Common = allOf(isFirstDecl(), isInMainFile(), + unless(anyOf( + // 1. internal linkage + isStaticStorageClass(), isInAnonymousNamespace(), + // 2. explicit external linkage + isExternStorageClass(), isExternC(), + // 3. template + isExplicitTemplateSpecialization(), + clang::ast_matchers::isTemplateInstantiation(), + // 4. friend + hasAncestor(friendDecl(); + Finder->addMatcher( + functionDecl(Common, unless(cxxMethodDecl()), unless(isMain())) + .bind("fn"), + this); + Finder->addMatcher(varDecl(Common, hasGlobalStorage()).bind("var"), this); +} + +static constexpr StringRef Message = +"%0 %1 can be can be made static or moved into an anonymous namespace " +"to enforce internal linkage."; SimplyDanny wrote: Typically, messages don't end with a period: ```suggestion "%0 %1 can be made static or moved into an anonymous namespace " "to enforce internal linkage"; ``` https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
@@ -0,0 +1,26 @@ +.. title:: clang-tidy - readability-mark-static + +readability-mark-static +=== + +Detects variable and function can be marked as static. + +Static functions and variables are scoped to a single file. Marking functions +and variables as static helps to better remove dead code. In addition, it gives +the compiler more information and can help compiler make more aggressive +optimizations. + EugeneZelenko wrote: I'm not sure about automatic fixes for anonymous namespaces. For example, in my work project we keep single monolithic anonymous namespace, so function body move would be required. https://github.com/llvm/llvm-project/pull/90830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] clang-format: Allow open brace with trailing comment (no line break) (PR #89956)
GertyP wrote: Ping https://github.com/llvm/llvm-project/pull/89956 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/90830 >From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Thu, 2 May 2024 15:44:45 +0800 Subject: [PATCH 1/4] reformat --- .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + .../UnnecessaryExternalLinkageCheck.cpp | 82 +++ .../UnnecessaryExternalLinkageCheck.h | 33 clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../unnecessary-external-linkage.rst | 26 ++ .../readability/Inputs/mark-static-var/func.h | 3 + .../readability/Inputs/mark-static-var/var.h | 3 + .../unnecessary-external-linkage-func.cpp | 30 +++ .../unnecessary-external-linkage-var.cpp | 40 + 11 files changed, 227 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 41065fc8e87859..8f58d9f24ba491 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule IdentifierLengthCheck.cpp IdentifierNamingCheck.cpp ImplicitBoolConversionCheck.cpp + UnnecessaryExternalLinkageCheck.cpp RedundantInlineSpecifierCheck.cpp InconsistentDeclarationParameterNameCheck.cpp IsolateDeclarationCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index d61c0ba39658e5..d389287e8f4909 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -58,6 +58,7 @@ #include "StringCompareCheck.h" #include "SuspiciousCallArgumentCheck.h" #include "UniqueptrDeleteReleaseCheck.h" +#include "UnnecessaryExternalLinkageCheck.h" #include "UppercaseLiteralSuffixCheck.h" #include "UseAnyOfAllOfCheck.h" #include "UseStdMinMaxCheck.h" @@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-identifier-naming"); CheckFactories.registerCheck( "readability-implicit-bool-conversion"); +CheckFactories.registerCheck( +"readability-unnecessary-external-linkage"); CheckFactories.registerCheck( "readability-math-missing-parentheses"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp new file mode 100644 index 00..4970d3339ef05d --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp @@ -0,0 +1,82 @@ +//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy +//-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UnnecessaryExternalLinkageCheck.h" +#include "clang/AST/Decl.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchersMacros.h" +#include "clang/Basic/Specifiers.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_POLYMORPHIC_MATCHER(isFirstDecl, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +VarDecl)) { + return Node.isFirstDecl(); +} + +AST_MATCHER(Decl, isInMainFile) { + for (const Decl *D : Node.redecls()) +if (!Finder->getASTContext().getSourceManager().isInMainFile( +D->getLocation())) + return false; + return true; +} + +AST_POLYMORPHIC_MATCHER(isExternStorageClass, +AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, +
[clang] cb015b9 - [clang][CodeGen] Propagate pragma set fast-math flags to floating point builtins (#90377)
Author: Karl-Johan Karlsson Date: 2024-05-04T17:47:48+02:00 New Revision: cb015b9ec9446b3a1303980c095fa442d5e46fbf URL: https://github.com/llvm/llvm-project/commit/cb015b9ec9446b3a1303980c095fa442d5e46fbf DIFF: https://github.com/llvm/llvm-project/commit/cb015b9ec9446b3a1303980c095fa442d5e46fbf.diff LOG: [clang][CodeGen] Propagate pragma set fast-math flags to floating point builtins (#90377) This is a fix for the issue #87758 where fast-math flags are not propagated all builtins. It seems like pragmas with fast math flags was only propagated to calls of unary floating point builtins. This patch propagate them also for binary and ternary floating point builtins. Added: clang/test/CodeGen/pr87758.c Modified: clang/lib/CodeGen/CGBuiltin.cpp clang/test/CodeGen/math-errno.c Removed: diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 9d0e6627a52016..8e31652f4dabef 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -513,8 +513,8 @@ static Value *emitBinaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); + CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); if (CGF.Builder.getIsFPConstrained()) { -CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType()); return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 }); } else { @@ -530,8 +530,8 @@ static Value *emitBinaryExpMaybeConstrainedFPBuiltin( llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); + CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); if (CGF.Builder.getIsFPConstrained()) { -CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, {Src0->getType(), Src1->getType()}); return CGF.Builder.CreateConstrainedFPCall(F, {Src0, Src1}); @@ -551,8 +551,8 @@ static Value *emitTernaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2)); + CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); if (CGF.Builder.getIsFPConstrained()) { -CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType()); return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 }); } else { @@ -704,6 +704,7 @@ static Value *EmitSignBit(CodeGenFunction &CGF, Value *V) { static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E, llvm::Constant *calleeValue) { + CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD)); return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot()); } @@ -2660,7 +2661,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, if (OP.hasMathErrnoOverride()) ErrnoOverriden = OP.getMathErrnoOverride(); } - // True if 'atttibute__((optnone)) is used. This attibute overrides + // True if 'attribute__((optnone))' is used. This attribute overrides // fast-math which implies math-errno. bool OptNone = CurFuncDecl && CurFuncDecl->hasAttr(); diff --git a/clang/test/CodeGen/math-errno.c b/clang/test/CodeGen/math-errno.c index b5354e47e26b77..15340a11150c1a 100644 --- a/clang/test/CodeGen/math-errno.c +++ b/clang/test/CodeGen/math-errno.c @@ -27,7 +27,7 @@ float f1(float x) { // CHECK: tail call float @sqrtf(float noundef {{.*}}) #[[ATTR4_O2:[0-9]+]] // FAST-LABEL: define {{.*}} nofpclass(nan inf) float @f1 -// FAST: call fast nofpclass(nan inf) float @sqrtf(float noundef nofpclass(nan inf) {{.*}}) #[[ATTR3_FAST:[0-9]+]] +// FAST: call nofpclass(nan inf) float @sqrtf(float noundef nofpclass(nan inf) {{.*}}) #[[ATTR3_FAST:[0-9]+]] // NOOPT-LABEL: define {{.*}} float @f1 // NOOPT: call float @sqrtf(float noundef {{.*}}) #[[ATTR4_NOOPT:[0-9]+]] @@ -44,7 +44,7 @@ float f2(float x) { // FAST: call fast float @llvm.sqrt.f32(float {{.*}}) // NOOPT-LABEL: define {{.*}} float @f2 -// NOOPT: call float @sqrtf(float {{.*}}) #[[ATTR4_NOOPT:[0-9]+]] +// NOOPT: call fast float @sqrtf(float {{.*}}) #[[ATTR4_NOOPT:[0-9]+]] __attribute__((optnone)) float f3(float x) { @@ -56,7 +56,7 @@ float f3(float x) { // CHECK: call float @sqrtf(float noundef {{.*}}) // FAST-LABEL: define {{.*}} nofpclass(nan inf) float @f3 -// FAST: call fast nofpclass(nan inf) float @sqrtf(float noundef nofpclass(nan inf) {{.*}}) #[[ATTR4_FAST:[0-9]+]] +// FAST: call nofpclass(nan inf) float @sqrtf(float noundef nofpclas
[clang] [clang][CodeGen] Propagate pragma set fast-math flags to floating point builtins (PR #90377)
https://github.com/karka228 closed https://github.com/llvm/llvm-project/pull/90377 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Implement P3034R1 Module Declarations Shouldn’t be Macros (PR #90574)
yronglin wrote: Thanks! I'd like to move the implementation from Parser to Preprocessor. I think It would make more sense to do these checks during lexing. https://github.com/llvm/llvm-project/pull/90574 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
@@ -0,0 +1,107 @@ +//===--- UseStdFormatCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseStdFormatCheck.h" +#include "../utils/FormatStringConverter.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { +AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); } +} // namespace + +UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StrictMode(Options.getLocalOrGlobal("StrictMode", false)), + StrFormatLikeFunctions(utils::options::parseStringList( + Options.get("StrFormatLikeFunctions", ""))), + ReplacementFormatFunction( + Options.get("ReplacementFormatFunction", "std::format")), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), + MaybeHeaderToInclude(Options.get("FormatHeader")) { + if (StrFormatLikeFunctions.empty()) +StrFormatLikeFunctions.push_back("absl::StrFormat"); + + if (!MaybeHeaderToInclude && ReplacementFormatFunction == "std::format") +MaybeHeaderToInclude = ""; +} + +void UseStdFormatCheck::registerPPCallbacks(const SourceManager &SM, +Preprocessor *PP, +Preprocessor *ModuleExpanderPP) { + IncludeInserter.registerPreprocessor(PP); +} + +void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr(argumentCountAtLeast(1), + hasArgument(0, stringLiteral(isOrdinary())), + callee(functionDecl(unless(cxxMethodDecl()), + matchers::matchesAnyListedName( + StrFormatLikeFunctions)) + .bind("func_decl"))) + .bind("strformat"), + this); +} + +void UseStdFormatCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { + using utils::options::serializeStringList; + Options.store(Opts, "StrictMode", StrictMode); + Options.store(Opts, "StrFormatLikeFunctions", +serializeStringList(StrFormatLikeFunctions)); + Options.store(Opts, "ReplacementFormatFunction", ReplacementFormatFunction); + Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle()); + if (MaybeHeaderToInclude) +Options.store(Opts, "FormatHeader", *MaybeHeaderToInclude); +} + +void UseStdFormatCheck::check(const MatchFinder::MatchResult &Result) { + const unsigned FormatArgOffset = 0; + const auto *OldFunction = Result.Nodes.getNodeAs("func_decl"); + const auto *StrFormat = Result.Nodes.getNodeAs("strformat"); + + utils::FormatStringConverter::Configuration ConverterConfig; + ConverterConfig.StrictMode = StrictMode; + utils::FormatStringConverter Converter(Result.Context, StrFormat, + FormatArgOffset, ConverterConfig, + getLangOpts()); + const Expr *StrFormatCall = StrFormat->getCallee(); + if (!Converter.canApply()) { +DiagnosticBuilder Diag = diag(StrFormat->getBeginLoc(), mikecrowe wrote: True. I'll fix that. https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
@@ -0,0 +1,107 @@ +//===--- UseStdFormatCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseStdFormatCheck.h" +#include "../utils/FormatStringConverter.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { +AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); } +} // namespace + +UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StrictMode(Options.getLocalOrGlobal("StrictMode", false)), + StrFormatLikeFunctions(utils::options::parseStringList( + Options.get("StrFormatLikeFunctions", ""))), + ReplacementFormatFunction( + Options.get("ReplacementFormatFunction", "std::format")), + IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", + utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()), + MaybeHeaderToInclude(Options.get("FormatHeader")) { + if (StrFormatLikeFunctions.empty()) +StrFormatLikeFunctions.push_back("absl::StrFormat"); + + if (!MaybeHeaderToInclude && ReplacementFormatFunction == "std::format") +MaybeHeaderToInclude = ""; +} + +void UseStdFormatCheck::registerPPCallbacks(const SourceManager &SM, +Preprocessor *PP, +Preprocessor *ModuleExpanderPP) { + IncludeInserter.registerPreprocessor(PP); +} + +void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr(argumentCountAtLeast(1), + hasArgument(0, stringLiteral(isOrdinary())), + callee(functionDecl(unless(cxxMethodDecl()), + matchers::matchesAnyListedName( + StrFormatLikeFunctions)) + .bind("func_decl"))) + .bind("strformat"), + this); +} + +void UseStdFormatCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { + using utils::options::serializeStringList; + Options.store(Opts, "StrictMode", StrictMode); + Options.store(Opts, "StrFormatLikeFunctions", +serializeStringList(StrFormatLikeFunctions)); + Options.store(Opts, "ReplacementFormatFunction", ReplacementFormatFunction); + Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle()); + if (MaybeHeaderToInclude) +Options.store(Opts, "FormatHeader", *MaybeHeaderToInclude); +} + +void UseStdFormatCheck::check(const MatchFinder::MatchResult &Result) { + const unsigned FormatArgOffset = 0; + const auto *OldFunction = Result.Nodes.getNodeAs("func_decl"); + const auto *StrFormat = Result.Nodes.getNodeAs("strformat"); + + utils::FormatStringConverter::Configuration ConverterConfig; + ConverterConfig.StrictMode = StrictMode; + utils::FormatStringConverter Converter(Result.Context, StrFormat, + FormatArgOffset, ConverterConfig, + getLangOpts()); + const Expr *StrFormatCall = StrFormat->getCallee(); + if (!Converter.canApply()) { +DiagnosticBuilder Diag = diag(StrFormat->getBeginLoc(), + "unable to use '%0' instead of %1 because %2") + << ReplacementFormatFunction + << OldFunction->getIdentifier() + << Converter.conversionNotPossibleReason(); mikecrowe wrote: OK. It looks like use-std-print needs that fix too, so I'll do that in a separate change. Is there a way to get the lit test to check for this? https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
@@ -0,0 +1,84 @@ +.. title:: clang-tidy - modernize-use-std-format + +modernize-use-std-format + + +Converts calls to ``absl::StrFormat``, or other functions via +configuration options, to C++20's ``std::format``, or another function +via a configuration option, modifying the format string appropriately and +removing now-unnecessary calls to ``std::string::c_str()`` and +``std::string::data()``. + +For example, it turns lines like + +.. code-block:: c++ + + return absl::StrFormat("The %s is %3d", description.c_str(), value); + +into: + +.. code-block:: c++ + + return std::format("The {} is {:3}", description, value); + +The check uses the same format-string-conversion algorithm as +`modernize-use-std-print <../modernize/use-std-print.html>`_ and its +shortcomings are described in the documentation for that check. + +Options +--- + +.. option:: StrictMode + + When `true`, the check will add casts when converting from variadic + functions and printing signed or unsigned integer types (including + fixed-width integer types from , ``ptrdiff_t``, ``size_t`` + and ``ssize_t``) as the opposite signedness to ensure that the output + would matches that of a simple wrapper for ``std::sprintf`` that + accepted a C-style variable argument list. For example, with + `StrictMode` enabled, + + .. code-block:: c++ + +extern std::string strprintf(const char *format, ...); +int i = -42; +unsigned int u = 0x; +return strprintf("%d %u\n", i, u); + + would be converted to + + .. code-block:: c++ + +return std::format("{} {}\n", static_cast(i), static_cast(u)); + + to ensure that the output will continue to be the unsigned representation + of -42 and the signed representation of 0x (often 4294967254 + and -1 respectively). When `false` (which is the default), these casts + will not be added which may cause a change in the output. Note that this + option makes no difference for the default value of + `StrFormatLikeFunctions` since ``absl::StrFormat`` takes a function + parameter pack and is not a variadic function. + +.. option:: StrFormatLikeFunctions + + A semicolon-separated list of (fully qualified) extra function names to mikecrowe wrote: True. I'll fix that. https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
https://github.com/mikecrowe edited https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Use `const&` avoiding copies (PR #90334)
https://github.com/SimplyDanny updated https://github.com/llvm/llvm-project/pull/90334 From e8420d3d39d729ee83e187913bb3a8d790f5779d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Danny=20M=C3=B6sch?= Date: Sat, 27 Apr 2024 11:38:20 +0200 Subject: [PATCH] [NFC] Use const& avoiding copies --- clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp index d58f5bb0919906..f8dced5dbafb60 100644 --- a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp +++ b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp @@ -295,7 +295,7 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer { OS << "Symbols:\n"; for (const auto &E : Symbols) { const MangledSymbol &Symbol = E.second; -for (auto Name : Symbol.Names) { +for (const auto &Name : Symbol.Names) { OS << " - { Name: \"" << (Symbol.ParentName.empty() || Instance.getLangOpts().CPlusPlus ? "" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
https://github.com/mikhailramalho created https://github.com/llvm/llvm-project/pull/91068 This patch also updates safeGetName to get names from operators without hitting an assertion >From 7f59654193385e78e1635c9bb2a627522f888b8d Mon Sep 17 00:00:00 2001 From: "Mikhail R. Gadelha" Date: Sat, 4 May 2024 13:08:32 -0300 Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type This patch also updates safeGetName to get names from operators without hitting an assertion --- .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 11 + .../WebKit/UncountedLocalVarsChecker.cpp | 23 +++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h index e35ea4ef05dd17..d9049fea897be1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h @@ -67,12 +67,13 @@ template std::string safeGetName(const T *ASTNode) { if (!ND) return ""; - // In case F is for example "operator|" the getName() method below would - // assert. - if (!ND->getDeclName().isIdentifier()) -return ""; + if (const auto *Identifier = ND->getIdentifier()) +return Identifier->getName().str(); - return ND->getName().str(); + std::string Name; + llvm::raw_string_ostream OS(Name); + ND->printName(OS); + return OS.str().empty() ? "" : OS.str(); } } // namespace clang diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 6036ad58cf253c..2d33e63f66ad7c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -225,11 +225,34 @@ class UncountedLocalVarsChecker } } + bool isVarIsAVMRefType(const VarDecl *V) const { +auto* type = V->getType()->getAs(); +if(!type) + return false; + +auto ClassDecl = type->getPointeeType()->getUnqualifiedDesugaredType()->getAsCXXRecordDecl(); +if (!ClassDecl) + return false; + +auto *NsDecl = ClassDecl->getParent(); +if (!NsDecl || !isa(NsDecl)) + return false; + +auto ClsNameStr = safeGetName(ClassDecl); +auto NamespaceName = safeGetName(NsDecl); + +// FIXME: These should be implemented via attributes. +return NamespaceName == "JSC" && ClsNameStr == "VM"; + } + bool shouldSkipVarDecl(const VarDecl *V) const { assert(V); if (!V->isLocalVarDecl()) return true; +if (isVarIsAVMRefType(V)) + return true; + return false; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
mikecrowe wrote: Thanks! I wasn't aware that was possible since I started with all these checks before fbf611ed2a768999202e2c5e1e1a6c3c6bb94725 and had been battling with the JSON syntax. https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Mikhail R. Gadelha (mikhailramalho) Changes This patch also updates safeGetName to get names from operators without hitting an assertion --- Full diff: https://github.com/llvm/llvm-project/pull/91068.diff 2 Files Affected: - (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h (+6-5) - (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp (+23) ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h index e35ea4ef05dd17..d9049fea897be1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h @@ -67,12 +67,13 @@ template std::string safeGetName(const T *ASTNode) { if (!ND) return ""; - // In case F is for example "operator|" the getName() method below would - // assert. - if (!ND->getDeclName().isIdentifier()) -return ""; + if (const auto *Identifier = ND->getIdentifier()) +return Identifier->getName().str(); - return ND->getName().str(); + std::string Name; + llvm::raw_string_ostream OS(Name); + ND->printName(OS); + return OS.str().empty() ? "" : OS.str(); } } // namespace clang diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 6036ad58cf253c..2d33e63f66ad7c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -225,11 +225,34 @@ class UncountedLocalVarsChecker } } + bool isVarIsAVMRefType(const VarDecl *V) const { +auto* type = V->getType()->getAs(); +if(!type) + return false; + +auto ClassDecl = type->getPointeeType()->getUnqualifiedDesugaredType()->getAsCXXRecordDecl(); +if (!ClassDecl) + return false; + +auto *NsDecl = ClassDecl->getParent(); +if (!NsDecl || !isa(NsDecl)) + return false; + +auto ClsNameStr = safeGetName(ClassDecl); +auto NamespaceName = safeGetName(NsDecl); + +// FIXME: These should be implemented via attributes. +return NamespaceName == "JSC" && ClsNameStr == "VM"; + } + bool shouldSkipVarDecl(const VarDecl *V) const { assert(V); if (!V->isLocalVarDecl()) return true; +if (isVarIsAVMRefType(V)) + return true; + return false; } `` https://github.com/llvm/llvm-project/pull/91068 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
mikhailramalho wrote: Hey @rniwa, if you want I can send the `safeGetName` changes in a separate patch. I was planning to unify this with `isMethodOnWTFContainerType` so there is some duplicated code here. I'll update the PR next week with some tests. https://github.com/llvm/llvm-project/pull/91068 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
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 76aa042dde6ba9ba57c680950f5818259ee02690 7f59654193385e78e1635c9bb2a627522f888b8d -- clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 2d33e63f66..2f5e8e1397 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -226,11 +226,13 @@ public: } bool isVarIsAVMRefType(const VarDecl *V) const { -auto* type = V->getType()->getAs(); -if(!type) +auto *type = V->getType()->getAs(); +if (!type) return false; -auto ClassDecl = type->getPointeeType()->getUnqualifiedDesugaredType()->getAsCXXRecordDecl(); +auto ClassDecl = type->getPointeeType() + ->getUnqualifiedDesugaredType() + ->getAsCXXRecordDecl(); if (!ClassDecl) return false; `` https://github.com/llvm/llvm-project/pull/91068 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
https://github.com/mikhailramalho updated https://github.com/llvm/llvm-project/pull/91068 >From dde31272c1599a699c49117c1612ae72d0491384 Mon Sep 17 00:00:00 2001 From: "Mikhail R. Gadelha" Date: Sat, 4 May 2024 13:08:32 -0300 Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type This patch also updates safeGetName to get names from operators without hitting an assertion --- .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 11 + .../WebKit/UncountedLocalVarsChecker.cpp | 23 +++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h index e35ea4ef05dd17..d9049fea897be1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h @@ -67,12 +67,13 @@ template std::string safeGetName(const T *ASTNode) { if (!ND) return ""; - // In case F is for example "operator|" the getName() method below would - // assert. - if (!ND->getDeclName().isIdentifier()) -return ""; + if (const auto *Identifier = ND->getIdentifier()) +return Identifier->getName().str(); - return ND->getName().str(); + std::string Name; + llvm::raw_string_ostream OS(Name); + ND->printName(OS); + return OS.str().empty() ? "" : OS.str(); } } // namespace clang diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 6036ad58cf253c..2d33e63f66ad7c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -225,11 +225,34 @@ class UncountedLocalVarsChecker } } + bool isVarIsAVMRefType(const VarDecl *V) const { +auto* type = V->getType()->getAs(); +if(!type) + return false; + +auto ClassDecl = type->getPointeeType()->getUnqualifiedDesugaredType()->getAsCXXRecordDecl(); +if (!ClassDecl) + return false; + +auto *NsDecl = ClassDecl->getParent(); +if (!NsDecl || !isa(NsDecl)) + return false; + +auto ClsNameStr = safeGetName(ClassDecl); +auto NamespaceName = safeGetName(NsDecl); + +// FIXME: These should be implemented via attributes. +return NamespaceName == "JSC" && ClsNameStr == "VM"; + } + bool shouldSkipVarDecl(const VarDecl *V) const { assert(V); if (!V->isLocalVarDecl()) return true; +if (isVarIsAVMRefType(V)) + return true; + return false; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Enable FPContract with optnone (PR #91061)
https://github.com/spavloff updated https://github.com/llvm/llvm-project/pull/91061 >From 32c0ec8a03b0c669dc595894730dd6f8a7933dea Mon Sep 17 00:00:00 2001 From: Serge Pavlov Date: Sat, 4 May 2024 12:26:22 +0700 Subject: [PATCH 1/2] [clang] Enable FPContract with optnone Previously treatment of the attribute `optnone` was modified in https://github.com/llvm/llvm-project/pull/85605 ([clang] Set correct FPOptions if attribute 'optnone' presents). As a side effect FPContract was disabled for optnone. It created unneeded divergence with the behavior of -O0, which enables this optimization. In the discussion https://github.com/llvm/llvm-project/pull/85605#issuecomment-2089350379 it was pointed out that FP contraction should be enabled even if all optimizations are turned off, otherwise results of calculations would be different. This change enables FPContract at optnone. --- clang/include/clang/Basic/LangOptions.h | 1 - clang/test/AST/ast-dump-fpfeatures.cpp | 18 +- clang/test/AST/ast-dump-fpfeatures.m | 4 ++-- clang/test/AST/ast-dump-late-parsing.cpp | 8 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/clang/include/clang/Basic/LangOptions.h b/clang/include/clang/Basic/LangOptions.h index e2a2aa71b880b3..dbf4595790480a 100644 --- a/clang/include/clang/Basic/LangOptions.h +++ b/clang/include/clang/Basic/LangOptions.h @@ -970,7 +970,6 @@ class FPOptionsOverride { void setDisallowOptimizations() { setFPPreciseEnabled(true); -setDisallowFPContract(); } storage_type getAsOpaqueInt() const { diff --git a/clang/test/AST/ast-dump-fpfeatures.cpp b/clang/test/AST/ast-dump-fpfeatures.cpp index 68144e31a93043..27558cdac833b6 100644 --- a/clang/test/AST/ast-dump-fpfeatures.cpp +++ b/clang/test/AST/ast-dump-fpfeatures.cpp @@ -198,7 +198,7 @@ float func_19(float x, float y) { // CHECK-LABEL: FunctionDecl {{.*}} func_19 'float (float, float)' // CHECK: CompoundStmt {{.*}} MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) float func_20(float x, float y) try { @@ -210,7 +210,7 @@ float func_20(float x, float y) try { // CHECK-LABEL: FunctionDecl {{.*}} func_20 'float (float, float)' // CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 struct C21 { C21(float x, float y); @@ -221,15 +221,15 @@ struct C21 { }; // CHECK-LABEL: CXXMethodDecl {{.*}} a_method 'float (float, float)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '*' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '*' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 __attribute__((optnone)) C21::C21(float x, float y) : member(x + y) {} // CHECK-LABEL: CXXConstructorDecl {{.*}} C21 'void (float, float)' // CHECK: CXXCtorInitializer {{.*}} 'member' 'float' -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 template __attribute__((optnone)) T func_22(T x, T y) { @@ -238,13 +238,13 @@ __attribute__((optnone)) T func_22(T x, T y) { // CHECK-LABEL: FunctionTemplateDecl {{.*}} func_22 // CHECK: FunctionDecl {{.*}} func_22 'T (T, T)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: FunctionDecl {{.*}} func_22 'float (float, float)' -// CHECK: CompoundStmt {{.*}} ConstRoundingMode=downward MathErrno=1 +// CHECK: CompoundStmt {{.*}} FPContractMode=1 ConstRoundingMode=downward MathErrno=1 // CHECK: ReturnStmt -// CHECK: BinaryOperator {{.*}} 'float' '+' ConstRoundingMode=downward MathErrno=1 +// CHECK: BinaryOperator {{.*}} 'float' '+' FPContractMode=1 ConstRoundingMode=downward MathErrno=1 float func_23(float x, float y) { return func_22(x, y); diff --git a/clang/test/AST/ast-dump-fpfeatures.m b
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
https://github.com/mikecrowe updated https://github.com/llvm/llvm-project/pull/90397 >From 0d6ede5d59cc70d803bfe2c7997737c1be358c75 Mon Sep 17 00:00:00 2001 From: Mike Crowe Date: Sun, 28 Apr 2024 12:41:46 +0100 Subject: [PATCH 01/16] [clang-tidy] Add modernize-use-std-format check Add a new clang-tidy check that converts absl::StrFormat (and similar functions) to std::format (and similar functions.) Split the configuration of FormatStringConverter out to a separate Configuration class so that we don't risk confusion by passing two boolean configuration parameters into the constructor. Add AllowTrailingNewlineRemoval option since we never want to remove trailing newlines in this check. Differential Revision: https://reviews.llvm.org/D154287 --- .../clang-tidy/modernize/CMakeLists.txt | 1 + .../modernize/ModernizeTidyModule.cpp | 2 + .../modernize/UseStdFormatCheck.cpp | 108 ++ .../clang-tidy/modernize/UseStdFormatCheck.h | 50 .../clang-tidy/modernize/UseStdPrintCheck.cpp | 5 +- .../utils/FormatStringConverter.cpp | 10 +- .../clang-tidy/utils/FormatStringConverter.h | 9 +- clang-tools-extra/docs/ReleaseNotes.rst | 9 ++ .../docs/clang-tidy/checks/list.rst | 1 + .../checks/modernize/use-std-format.rst | 84 ++ .../modernize/use-std-format-custom.cpp | 76 .../checkers/modernize/use-std-format-fmt.cpp | 37 ++ .../checkers/modernize/use-std-format.cpp | 97 13 files changed, 483 insertions(+), 6 deletions(-) create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-custom.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-fmt.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index 8005d6e91c060c..576805c4c7f181 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -41,6 +41,7 @@ add_clang_library(clangTidyModernizeModule UseNullptrCheck.cpp UseOverrideCheck.cpp UseStartsEndsWithCheck.cpp + UseStdFormatCheck.cpp UseStdNumbersCheck.cpp UseStdPrintCheck.cpp UseTrailingReturnTypeCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp index 776558433c5baa..b9c7a2dc383e88 100644 --- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp @@ -42,6 +42,7 @@ #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" #include "UseStartsEndsWithCheck.h" +#include "UseStdFormatCheck.h" #include "UseStdNumbersCheck.h" #include "UseStdPrintCheck.h" #include "UseTrailingReturnTypeCheck.h" @@ -76,6 +77,7 @@ class ModernizeModule : public ClangTidyModule { "modernize-use-designated-initializers"); CheckFactories.registerCheck( "modernize-use-starts-ends-with"); + CheckFactories.registerCheck("modernize-use-std-format"); CheckFactories.registerCheck( "modernize-use-std-numbers"); CheckFactories.registerCheck("modernize-use-std-print"); diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp new file mode 100644 index 00..d22ebe857cf415 --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp @@ -0,0 +1,108 @@ +//===--- UseStdFormatCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseStdFormatCheck.h" +#include "../utils/FormatStringConverter.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { +AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); } +} // namespace + +UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StrictMode(Options.getLocalOrGlobal("StrictMode", false)), + StrFormatLikeFunctions(utils::options::par
[clang] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type (PR #91068)
https://github.com/mikhailramalho updated https://github.com/llvm/llvm-project/pull/91068 >From a770060da101720ffddc033fd37db790eaa17710 Mon Sep 17 00:00:00 2001 From: "Mikhail R. Gadelha" Date: Sat, 4 May 2024 13:08:32 -0300 Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Ignore local vars of JSC::VM& type This patch also updates safeGetName to get names from operators without hitting an assertion --- .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h | 11 .../WebKit/UncountedLocalVarsChecker.cpp | 25 +++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h index e35ea4ef05dd17..d9049fea897be1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h @@ -67,12 +67,13 @@ template std::string safeGetName(const T *ASTNode) { if (!ND) return ""; - // In case F is for example "operator|" the getName() method below would - // assert. - if (!ND->getDeclName().isIdentifier()) -return ""; + if (const auto *Identifier = ND->getIdentifier()) +return Identifier->getName().str(); - return ND->getName().str(); + std::string Name; + llvm::raw_string_ostream OS(Name); + ND->printName(OS); + return OS.str().empty() ? "" : OS.str(); } } // namespace clang diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp index 6036ad58cf253c..2f5e8e139709f6 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp @@ -225,11 +225,36 @@ class UncountedLocalVarsChecker } } + bool isVarIsAVMRefType(const VarDecl *V) const { +auto *type = V->getType()->getAs(); +if (!type) + return false; + +auto ClassDecl = type->getPointeeType() + ->getUnqualifiedDesugaredType() + ->getAsCXXRecordDecl(); +if (!ClassDecl) + return false; + +auto *NsDecl = ClassDecl->getParent(); +if (!NsDecl || !isa(NsDecl)) + return false; + +auto ClsNameStr = safeGetName(ClassDecl); +auto NamespaceName = safeGetName(NsDecl); + +// FIXME: These should be implemented via attributes. +return NamespaceName == "JSC" && ClsNameStr == "VM"; + } + bool shouldSkipVarDecl(const VarDecl *V) const { assert(V); if (!V->isLocalVarDecl()) return true; +if (isVarIsAVMRefType(V)) + return true; + return false; } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][docs] Fix modernize-use-std-print docs (PR #91069)
https://github.com/mikecrowe created https://github.com/llvm/llvm-project/pull/91069 The set of functions for the PrintfLikeFunctions and FprintfLikeFunctions options replaces the default, so remove the word "extra" from the description which implies that they are in addition to the default. >From e892c7d27ec71442dd8c6ca30ae195be374cbc64 Mon Sep 17 00:00:00 2001 From: Mike Crowe Date: Sat, 4 May 2024 17:21:02 +0100 Subject: [PATCH] [clang-tidy][docs] Fix modernize-use-std-print docs The set of functions for the PrintfLikeFunctions and FprintfLikeFunctions options replaces the default, so remove the word "extra" from the description which implies that they are in addition to the default. --- .../docs/clang-tidy/checks/modernize/use-std-print.rst| 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst index 9bb691e9d9512e..79648a1104bca2 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst @@ -118,7 +118,7 @@ Options .. option:: PrintfLikeFunctions - A semicolon-separated list of (fully qualified) extra function names to + A semicolon-separated list of (fully qualified) function names to replace, with the requirement that the first parameter contains the printf-style format string and the arguments to be formatted follow immediately afterwards. If neither this option nor @@ -128,7 +128,7 @@ Options .. option:: FprintfLikeFunctions - A semicolon-separated list of (fully qualified) extra function names to + A semicolon-separated list of (fully qualified) function names to replace, with the requirement that the first parameter is retained, the second parameter contains the printf-style format string and the arguments to be formatted follow immediately afterwards. If neither this ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][docs] Fix modernize-use-std-print docs (PR #91069)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Mike Crowe (mikecrowe) Changes The set of functions for the PrintfLikeFunctions and FprintfLikeFunctions options replaces the default, so remove the word "extra" from the description which implies that they are in addition to the default. --- Full diff: https://github.com/llvm/llvm-project/pull/91069.diff 1 Files Affected: - (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst (+2-2) ``diff diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst index 9bb691e9d9512e..79648a1104bca2 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst @@ -118,7 +118,7 @@ Options .. option:: PrintfLikeFunctions - A semicolon-separated list of (fully qualified) extra function names to + A semicolon-separated list of (fully qualified) function names to replace, with the requirement that the first parameter contains the printf-style format string and the arguments to be formatted follow immediately afterwards. If neither this option nor @@ -128,7 +128,7 @@ Options .. option:: FprintfLikeFunctions - A semicolon-separated list of (fully qualified) extra function names to + A semicolon-separated list of (fully qualified) function names to replace, with the requirement that the first parameter is retained, the second parameter contains the printf-style format string and the arguments to be formatted follow immediately afterwards. If neither this `` https://github.com/llvm/llvm-project/pull/91069 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add modernize-use-std-format check (PR #90397)
@@ -0,0 +1,84 @@ +.. title:: clang-tidy - modernize-use-std-format + +modernize-use-std-format + + +Converts calls to ``absl::StrFormat``, or other functions via +configuration options, to C++20's ``std::format``, or another function +via a configuration option, modifying the format string appropriately and +removing now-unnecessary calls to ``std::string::c_str()`` and +``std::string::data()``. + +For example, it turns lines like + +.. code-block:: c++ + + return absl::StrFormat("The %s is %3d", description.c_str(), value); + +into: + +.. code-block:: c++ + + return std::format("The {} is {:3}", description, value); + +The check uses the same format-string-conversion algorithm as +`modernize-use-std-print <../modernize/use-std-print.html>`_ and its +shortcomings are described in the documentation for that check. + +Options +--- + +.. option:: StrictMode + + When `true`, the check will add casts when converting from variadic + functions and printing signed or unsigned integer types (including + fixed-width integer types from , ``ptrdiff_t``, ``size_t`` + and ``ssize_t``) as the opposite signedness to ensure that the output + would matches that of a simple wrapper for ``std::sprintf`` that + accepted a C-style variable argument list. For example, with + `StrictMode` enabled, + + .. code-block:: c++ + +extern std::string strprintf(const char *format, ...); +int i = -42; +unsigned int u = 0x; +return strprintf("%d %u\n", i, u); + + would be converted to + + .. code-block:: c++ + +return std::format("{} {}\n", static_cast(i), static_cast(u)); + + to ensure that the output will continue to be the unsigned representation + of -42 and the signed representation of 0x (often 4294967254 + and -1 respectively). When `false` (which is the default), these casts + will not be added which may cause a change in the output. Note that this + option makes no difference for the default value of + `StrFormatLikeFunctions` since ``absl::StrFormat`` takes a function + parameter pack and is not a variadic function. + +.. option:: StrFormatLikeFunctions + + A semicolon-separated list of (fully qualified) extra function names to mikecrowe wrote: The fix for use-std-print is in https://github.com/llvm/llvm-project/pull/91069 . https://github.com/llvm/llvm-project/pull/90397 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][docs] Fix modernize-use-std-print docs (PR #91069)
mikecrowe wrote: The equivalent mistake was spotted by @5chmidti in https://github.com/llvm/llvm-project/pull/90397/files/54c325d7a5e24441adbe8036800a2f50e2ff5fa0#r1589697782 in the new use-std-format check. https://github.com/llvm/llvm-project/pull/91069 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] No longer require complete types with __builtin_launder (PR #91070)
https://github.com/MitalAshok created https://github.com/llvm/llvm-project/pull/91070 Incomplete types are assumed to need the llvm.launder.invariant.group intrinsic Fixes #90949 >From 21d9f27692b2a2fa9ac99f4644109e62e3730133 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Sat, 4 May 2024 17:31:31 +0100 Subject: [PATCH] [Clang] No longer require complete types with __builtin_launder Incomplete types are assumed to need the llvm.launder.invariant.group intrinsic Fixes #90949 --- clang/docs/ReleaseNotes.rst | 2 + clang/lib/CodeGen/CGBuiltin.cpp | 5 +- clang/lib/Sema/SemaChecking.cpp | 20 +--- clang/test/CodeGenCXX/builtin-launder.cpp | 56 +++ clang/test/SemaCXX/builtins.cpp | 14 -- 5 files changed, 73 insertions(+), 24 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 54b58b1ae99fbd..e22a80a6f281c9 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -552,6 +552,8 @@ Bug Fixes in This Version - Clang will no longer emit a duplicate -Wunused-value warning for an expression `(A, B)` which evaluates to glvalue `B` that can be converted to non ODR-use. (#GH45783) +- `__builtin_launder` no longer requires a pointer to a complete type. (#GH90949) + Bug Fixes to Compiler Builtins ^^ diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 8e31652f4dabef..6a544f97cac5e2 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -2487,8 +2487,9 @@ TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty, if (!Seen.insert(Record).second) return false; - assert(Record->hasDefinition() && - "Incomplete types should already be diagnosed"); + // Assume incomplete types need to be laundered + if (!Record->hasDefinition()) +return true; if (Record->isDynamicClass()) return true; diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3179d542b1f926..c2eb5b51975c1a 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2164,15 +2164,7 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { // * The type of the argument if it's not an array or function type, // Otherwise, // * The decayed argument type. - QualType ParamTy = [&]() { -QualType ArgTy = TheCall->getArg(0)->getType(); -if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) - return S.Context.getPointerType(Ty->getElementType()); -if (ArgTy->isFunctionType()) { - return S.Context.getPointerType(ArgTy); -} -return ArgTy; - }(); + QualType ParamTy = S.Context.getAdjustedParameterType(TheCall->getArg(0)->getType()); TheCall->setType(ParamTy); @@ -2191,16 +2183,6 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { return ExprError(); } - // We either have an incomplete class type, or we have a class template - // whose instantiation has not been forced. Example: - // - // template struct Foo { T value; }; - // Foo *p = nullptr; - // auto *d = __builtin_launder(p); - if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), -diag::err_incomplete_type)) -return ExprError(); - assert(ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case"); diff --git a/clang/test/CodeGenCXX/builtin-launder.cpp b/clang/test/CodeGenCXX/builtin-launder.cpp index 06a93d1c441d29..8cfbc3101e30d3 100644 --- a/clang/test/CodeGenCXX/builtin-launder.cpp +++ b/clang/test/CodeGenCXX/builtin-launder.cpp @@ -53,10 +53,66 @@ extern "C" void test_builtin_launder_virtual_base(TestVirtualBase *p) { TestVirtualBase *d = __builtin_launder(p); } +struct IncompleteNeedsLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_needs_launder +extern "C" void test_builtin_launder_incomplete_later_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteNeedsLaunder { + virtual void foo() {} +}; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_completed_needs_launder +extern "C" void test_builtin_launder_completed_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteDoesntNeedLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_doesnt_needs_launder +extern "C" void test_builtin_launder_incomplete_later_doesnt_needs_launder(IncompleteDoesn
[clang] [Clang] No longer require complete types with __builtin_launder (PR #91070)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Mital Ashok (MitalAshok) Changes Incomplete types are assumed to need the llvm.launder.invariant.group intrinsic Fixes #90949 --- Full diff: https://github.com/llvm/llvm-project/pull/91070.diff 5 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+2) - (modified) clang/lib/CodeGen/CGBuiltin.cpp (+3-2) - (modified) clang/lib/Sema/SemaChecking.cpp (+1-19) - (modified) clang/test/CodeGenCXX/builtin-launder.cpp (+56) - (modified) clang/test/SemaCXX/builtins.cpp (+11-3) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 54b58b1ae99fbd..e22a80a6f281c9 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -552,6 +552,8 @@ Bug Fixes in This Version - Clang will no longer emit a duplicate -Wunused-value warning for an expression `(A, B)` which evaluates to glvalue `B` that can be converted to non ODR-use. (#GH45783) +- `__builtin_launder` no longer requires a pointer to a complete type. (#GH90949) + Bug Fixes to Compiler Builtins ^^ diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 8e31652f4dabef..6a544f97cac5e2 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -2487,8 +2487,9 @@ TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty, if (!Seen.insert(Record).second) return false; - assert(Record->hasDefinition() && - "Incomplete types should already be diagnosed"); + // Assume incomplete types need to be laundered + if (!Record->hasDefinition()) +return true; if (Record->isDynamicClass()) return true; diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3179d542b1f926..c2eb5b51975c1a 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2164,15 +2164,7 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { // * The type of the argument if it's not an array or function type, // Otherwise, // * The decayed argument type. - QualType ParamTy = [&]() { -QualType ArgTy = TheCall->getArg(0)->getType(); -if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) - return S.Context.getPointerType(Ty->getElementType()); -if (ArgTy->isFunctionType()) { - return S.Context.getPointerType(ArgTy); -} -return ArgTy; - }(); + QualType ParamTy = S.Context.getAdjustedParameterType(TheCall->getArg(0)->getType()); TheCall->setType(ParamTy); @@ -2191,16 +2183,6 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { return ExprError(); } - // We either have an incomplete class type, or we have a class template - // whose instantiation has not been forced. Example: - // - // template struct Foo { T value; }; - // Foo *p = nullptr; - // auto *d = __builtin_launder(p); - if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), -diag::err_incomplete_type)) -return ExprError(); - assert(ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case"); diff --git a/clang/test/CodeGenCXX/builtin-launder.cpp b/clang/test/CodeGenCXX/builtin-launder.cpp index 06a93d1c441d29..8cfbc3101e30d3 100644 --- a/clang/test/CodeGenCXX/builtin-launder.cpp +++ b/clang/test/CodeGenCXX/builtin-launder.cpp @@ -53,10 +53,66 @@ extern "C" void test_builtin_launder_virtual_base(TestVirtualBase *p) { TestVirtualBase *d = __builtin_launder(p); } +struct IncompleteNeedsLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_needs_launder +extern "C" void test_builtin_launder_incomplete_later_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteNeedsLaunder { + virtual void foo() {} +}; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_completed_needs_launder +extern "C" void test_builtin_launder_completed_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteDoesntNeedLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_doesnt_needs_launder +extern "C" void test_builtin_launder_incomplete_later_doesnt_needs_launder(IncompleteDoesntNeedLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteDoesntNeedLaunder *d = __builtin_launder(p); +} + //===
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
dougsonos wrote: > So seems like I was just premature, makes sense to break this in to pieces > :). Am I right to assume that these warnings will be back, just in PR 2? Yes, you can revert c18b77459fb34482f169323de9a81142a922b6a7 to bring the caller/callee diagnostics back. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] No longer require complete types with __builtin_launder (PR #91070)
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 028f1b078193b9120ddb441808521b6bd6eaed0e 21d9f27692b2a2fa9ac99f4644109e62e3730133 -- clang/lib/CodeGen/CGBuiltin.cpp clang/lib/Sema/SemaChecking.cpp clang/test/CodeGenCXX/builtin-launder.cpp clang/test/SemaCXX/builtins.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index c2eb5b5197..9ed404f9e7 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2164,7 +2164,8 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { // * The type of the argument if it's not an array or function type, // Otherwise, // * The decayed argument type. - QualType ParamTy = S.Context.getAdjustedParameterType(TheCall->getArg(0)->getType()); + QualType ParamTy = + S.Context.getAdjustedParameterType(TheCall->getArg(0)->getType()); TheCall->setType(ParamTy); `` https://github.com/llvm/llvm-project/pull/91070 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] No longer require complete types with __builtin_launder (PR #91070)
https://github.com/MitalAshok updated https://github.com/llvm/llvm-project/pull/91070 >From fe8c0dc5f7beacae7b1494a5987c3674dbd330d3 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Sat, 4 May 2024 17:31:31 +0100 Subject: [PATCH] [Clang] No longer require complete types with __builtin_launder Incomplete types are assumed to need the llvm.launder.invariant.group intrinsic Fixes #90949 --- clang/docs/ReleaseNotes.rst | 2 + clang/lib/CodeGen/CGBuiltin.cpp | 5 +- clang/lib/Sema/SemaChecking.cpp | 21 + clang/test/CodeGenCXX/builtin-launder.cpp | 56 +++ clang/test/SemaCXX/builtins.cpp | 14 -- 5 files changed, 74 insertions(+), 24 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 54b58b1ae99fbd..e22a80a6f281c9 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -552,6 +552,8 @@ Bug Fixes in This Version - Clang will no longer emit a duplicate -Wunused-value warning for an expression `(A, B)` which evaluates to glvalue `B` that can be converted to non ODR-use. (#GH45783) +- `__builtin_launder` no longer requires a pointer to a complete type. (#GH90949) + Bug Fixes to Compiler Builtins ^^ diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 8e31652f4dabef..6a544f97cac5e2 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -2487,8 +2487,9 @@ TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty, if (!Seen.insert(Record).second) return false; - assert(Record->hasDefinition() && - "Incomplete types should already be diagnosed"); + // Assume incomplete types need to be laundered + if (!Record->hasDefinition()) +return true; if (Record->isDynamicClass()) return true; diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 3179d542b1f926..9ed404f9e7c936 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -2164,15 +2164,8 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { // * The type of the argument if it's not an array or function type, // Otherwise, // * The decayed argument type. - QualType ParamTy = [&]() { -QualType ArgTy = TheCall->getArg(0)->getType(); -if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) - return S.Context.getPointerType(Ty->getElementType()); -if (ArgTy->isFunctionType()) { - return S.Context.getPointerType(ArgTy); -} -return ArgTy; - }(); + QualType ParamTy = + S.Context.getAdjustedParameterType(TheCall->getArg(0)->getType()); TheCall->setType(ParamTy); @@ -2191,16 +2184,6 @@ static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { return ExprError(); } - // We either have an incomplete class type, or we have a class template - // whose instantiation has not been forced. Example: - // - // template struct Foo { T value; }; - // Foo *p = nullptr; - // auto *d = __builtin_launder(p); - if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), -diag::err_incomplete_type)) -return ExprError(); - assert(ParamTy->getPointeeType()->isObjectType() && "Unhandled non-object pointer case"); diff --git a/clang/test/CodeGenCXX/builtin-launder.cpp b/clang/test/CodeGenCXX/builtin-launder.cpp index 06a93d1c441d29..8cfbc3101e30d3 100644 --- a/clang/test/CodeGenCXX/builtin-launder.cpp +++ b/clang/test/CodeGenCXX/builtin-launder.cpp @@ -53,10 +53,66 @@ extern "C" void test_builtin_launder_virtual_base(TestVirtualBase *p) { TestVirtualBase *d = __builtin_launder(p); } +struct IncompleteNeedsLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_needs_launder +extern "C" void test_builtin_launder_incomplete_later_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteNeedsLaunder { + virtual void foo() {} +}; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_completed_needs_launder +extern "C" void test_builtin_launder_completed_needs_launder(IncompleteNeedsLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.invariant.group + + // CHECK-NONSTRICT-NOT: @llvm.launder.invariant.group + + // CHECK: ret void + IncompleteNeedsLaunder *d = __builtin_launder(p); +} + +struct IncompleteDoesntNeedLaunder; + +// CHECK-LABEL: define{{.*}} void @test_builtin_launder_incomplete_later_doesnt_needs_launder +extern "C" void test_builtin_launder_incomplete_later_doesnt_needs_launder(IncompleteDoesntNeedLaunder *p) { + // CHECK-STRICT-NOT: ret void + // CHECK-STRICT: @llvm.launder.i
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
https://github.com/Sirraide edited https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -768,6 +776,18 @@ class Sema final : public SemaBase { /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); + // - function effects --- + + /// Warn when implicitly changing function effects. + void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, +SourceLocation Loc); + + /// Try to parse the conditional expression attached to an effect attribute + /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). If RequireConstexpr, + /// then this will fail if the expression is dependent. + ExprResult ActOnEffectExpression(Expr *CondExpr, FunctionEffectMode &Mode, + bool RequireConstexpr = false); Sirraide wrote: What is the `RequireConstexpr` parameter for? It’s always `false` from what I can tell. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -5028,3 +5050,376 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), getTypeConstraintConcept(), getTypeConstraintArguments()); } + +FunctionEffect::Kind FunctionEffect::oppositeKind() const { + switch (kind()) { + case Kind::NonBlocking: +return Kind::Blocking; + case Kind::Blocking: +return Kind::NonBlocking; + case Kind::NonAllocating: +return Kind::Allocating; + case Kind::Allocating: +return Kind::NonAllocating; + case Kind::None: +return Kind::None; + } + llvm_unreachable("unknown effect kind"); +} + +StringRef FunctionEffect::name() const { + switch (kind()) { + case Kind::NonBlocking: +return "nonblocking"; + case Kind::NonAllocating: +return "nonallocating"; + case Kind::Blocking: +return "blocking"; + case Kind::Allocating: +return "allocating"; + case Kind::None: +break; + } + llvm_unreachable("unknown effect kind"); +} + +bool FunctionEffectDiff::shouldDiagnoseConversion( +QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType, +const FunctionEffectsRef &DstFX) const { + + switch (EffectKind) { + case FunctionEffect::Kind::NonAllocating: +// nonallocating can't be added (spoofed) during a conversion, unless we +// have nonblocking +if (DiffKind == Kind::Added) { + for (const auto &CFE : SrcFX) { +if (CFE.Effect.kind() == FunctionEffect::Kind::NonBlocking) + return false; + } +} +[[fallthrough]]; + case FunctionEffect::Kind::NonBlocking: +// nonblocking can't be added (spoofed) during a conversion. +switch (DiffKind) { +case Kind::Added: + return true; +case Kind::Removed: + return false; +case Kind::ConditionMismatch: + return true; // TODO: ??? +} + case FunctionEffect::Kind::Blocking: + case FunctionEffect::Kind::Allocating: +return false; + case FunctionEffect::Kind::None: +break; + } + llvm_unreachable("unknown effect kind"); +} + +bool FunctionEffectDiff::shouldDiagnoseRedeclaration( +const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX, +const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const { + switch (EffectKind) { + case FunctionEffect::Kind::NonAllocating: + case FunctionEffect::Kind::NonBlocking: +// nonblocking/nonallocating can't be removed in a redeclaration +switch (DiffKind) { +case Kind::Added: + return false; // No diagnostic. +case Kind::Removed: + return true; // Issue diagnostic +case Kind::ConditionMismatch: + // All these forms of mismatches are diagnosed. + return true; +} + case FunctionEffect::Kind::Blocking: + case FunctionEffect::Kind::Allocating: +return false; + case FunctionEffect::Kind::None: +break; + } + llvm_unreachable("unknown effect kind"); +} + +FunctionEffectDiff::OverrideResult +FunctionEffectDiff::shouldDiagnoseMethodOverride( +const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, +const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const { + switch (EffectKind) { + case FunctionEffect::Kind::NonAllocating: + case FunctionEffect::Kind::NonBlocking: +switch (DiffKind) { + +// If added on an override, that's fine and not diagnosed. +case Kind::Added: + return OverrideResult::NoAction; + +// If missing from an override (removed), propagate from base to derived. +case Kind::Removed: + return OverrideResult::Merge; + +// If there's a mismatch involving the effect's polarity or condition, +// issue a warning. +case Kind::ConditionMismatch: + return OverrideResult::Warn; +} + + case FunctionEffect::Kind::Blocking: + case FunctionEffect::Kind::Allocating: +return OverrideResult::NoAction; + + case FunctionEffect::Kind::None: +break; + } + llvm_unreachable("unknown effect kind"); +} + +bool FunctionEffect::canInferOnFunction(const Decl &Callee) const { + switch (kind()) { + case Kind::NonAllocating: + case Kind::NonBlocking: { +FunctionEffectsRef CalleeFX; +if (auto *FD = Callee.getAsFunction()) + CalleeFX = FD->getFunctionEffects(); +else if (auto *BD = dyn_cast(&Callee)) + CalleeFX = BD->getFunctionEffects(); +else + return false; +for (const FunctionEffectWithCondition &CalleeEC : CalleeFX) { + // nonblocking/nonallocating cannot call allocating + if (CalleeEC.Effect.kind() == Kind::Allocating) +return false; + // nonblocking cannot call blocking + if (kind() == Kind::NonBlocking && + CalleeEC.Effect.kind() == Kind::Blocking) +return false; +} + } +return true; + + case Kind::Allocating: + case Kind::Blocking: +return false; + + case Kind::None: +break; + } + llvm_unreachable("unknown effect kind"); +} + +bool FunctionEffect::shouldDiagnoseFunctionCa
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -5119,6 +5448,62 @@ class FunctionProtoType final return false; } + unsigned getNumFunctionEffects() const { +return hasExtraBitfields() + ? getTrailingObjects() + ->NumFunctionEffects + : 0; + } + + // For serialization. + ArrayRef getFunctionEffectsOnly() const { Sirraide wrote: I’d call this `getFunctionEffectsWithoutConditions()` or something like that because ‘only’ is really confusing imo. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -3649,6 +3649,25 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef params, auto &EllipsisLoc = *getTrailingObjects(); EllipsisLoc = epi.EllipsisLoc; } + + if (!epi.FunctionEffects.empty()) { +auto &ExtraBits = *getTrailingObjects(); +// TODO: bitfield overflow? +ExtraBits.NumFunctionEffects = epi.FunctionEffects.size(); + +ArrayRef SrcFX = epi.FunctionEffects.effects(); +auto *DestFX = getTrailingObjects(); +std::copy(SrcFX.begin(), SrcFX.end(), DestFX); Sirraide wrote: ```suggestion std::uninitialized_copy(SrcFX.begin(), SrcFX.end(), DestFX); ``` I think you’re supposed to do this since this is copying into uninitialised memory; that’s at least how code using `TrailingObjects` typically does it. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -7963,6 +7967,148 @@ static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { llvm_unreachable("unexpected attribute kind!"); } +ExprResult Sema::ActOnEffectExpression(Expr *CondExpr, FunctionEffectMode &Mode, + bool RequireConstexpr) { + // see checkFunctionConditionAttr, Sema::CheckCXXBooleanCondition + if (RequireConstexpr || !CondExpr->isTypeDependent()) { +ExprResult E = PerformContextuallyConvertToBool(CondExpr); +if (E.isInvalid()) + return E; +CondExpr = E.get(); +if (RequireConstexpr || !CondExpr->isValueDependent()) { + llvm::APSInt CondInt; + E = VerifyIntegerConstantExpression( + E.get(), &CondInt, + // TODO: have our own diagnostic + diag::err_constexpr_if_condition_expression_is_not_constant); Sirraide wrote: This should probably be its own diagnostic (unless there already is one that just says ‘must be a boolean constant expression’ or something in that vein, in which case you can probably just use that one). Either way, we definitely can’t use this one here since it’s for `if constexpr`. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -352,6 +352,12 @@ let Class = FunctionProtoType in { def : Property<"AArch64SMEAttributes", UInt32> { let Read = [{ node->getAArch64SMEAttributes() }]; } + def : Property<"functionEffects", Array> { +let Read = [{ node->getFunctionEffectsOnly() }]; Sirraide wrote: See last comment. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
https://github.com/Sirraide requested changes to this pull request. Overall, it’s looking pretty good I’d say; there are some minor things here and there, but nothing major. Missing are also more tests that involve dependent expressions, especially tests that actually instantiate such templates. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)
@@ -3649,6 +3649,25 @@ FunctionProtoType::FunctionProtoType(QualType result, ArrayRef params, auto &EllipsisLoc = *getTrailingObjects(); EllipsisLoc = epi.EllipsisLoc; } + + if (!epi.FunctionEffects.empty()) { +auto &ExtraBits = *getTrailingObjects(); +// TODO: bitfield overflow? +ExtraBits.NumFunctionEffects = epi.FunctionEffects.size(); Sirraide wrote: Add an assertion for that please. https://github.com/llvm/llvm-project/pull/84983 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits