[clang] [clang][Sema] Improve error recovery for id-expressions referencing invalid decls (PR #81662)
https://github.com/HighCommander4 updated https://github.com/llvm/llvm-project/pull/81662 >From 120bade6c7077eb37222e125952befe53a9fb8cc Mon Sep 17 00:00:00 2001 From: Nathan Ridge Date: Tue, 13 Feb 2024 12:26:17 -0500 Subject: [PATCH] [clang][Sema] Improve error recovery for id-expressions referencing invalid decls Passing AcceptInvalidDecl=true to BuildDeclarationNameExpr() allows the RecoveryExpr that's constructed to retain a DeclRefExpr pointing to the invalid decl as a child, preserving information about the reference for use by tools such as clangd. Fixes https://github.com/clangd/clangd/issues/1820 --- clang/lib/Sema/SemaExpr.cpp | 6 +- clang/test/AST/ast-dump-recovery.cpp | 6 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 2a0e86c37f1bfc..0c42f568d6d444 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2928,7 +2928,7 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); } - return BuildDeclarationNameExpr(SS, R, ADL); + return BuildDeclarationNameExpr(SS, R, ADL, /*AcceptInvalidDecl=*/true); } /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified @@ -3453,6 +3453,10 @@ ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, NeedsADL, R.isOverloadedResult(), R.begin(), R.end()); + if (ULE && R.isSingleResult() && R.getFoundDecl()->isInvalidDecl()) { +return CreateRecoveryExpr(ULE->getBeginLoc(), ULE->getEndLoc(), {ULE}); + } + return ULE; } diff --git a/clang/test/AST/ast-dump-recovery.cpp b/clang/test/AST/ast-dump-recovery.cpp index cfb013585ad744..f628fa913da1e6 100644 --- a/clang/test/AST/ast-dump-recovery.cpp +++ b/clang/test/AST/ast-dump-recovery.cpp @@ -402,6 +402,7 @@ void returnInitListFromVoid() { // CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 8 } +void FuncTakingUnknown(Unknown); void RecoveryExprForInvalidDecls(Unknown InvalidDecl) { InvalidDecl + 1; // CHECK: BinaryOperator {{.*}} @@ -411,6 +412,11 @@ void RecoveryExprForInvalidDecls(Unknown InvalidDecl) { InvalidDecl(); // CHECK: CallExpr {{.*}} // CHECK-NEXT: `-RecoveryExpr {{.*}} '' + FuncTakingUnknown(InvalidDecl); + // CHECK: CallExpr {{.*}} '' + // CHECK-NEXT: |-UnresolvedLookupExpr {{.*}} '' + // CHECK-NEXT: `-RecoveryExpr {{.*}} '' + // CHECK-NEXT: `-DeclRefExpr {{.*}} 'InvalidDecl' 'int' } void RecoverToAnInvalidDecl() { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Diagnose apply AST consume actions on LLVM IR (PR #88602)
https://github.com/yronglin created https://github.com/llvm/llvm-project/pull/88602 Fixes https://github.com/llvm/llvm-project/issues/88522 This PR introduce a new diagnostic to report apply AST consume actions on LLVM IR. >From a180c067d36b731cbd075651ca4ecd903a643ffa Mon Sep 17 00:00:00 2001 From: yronglin Date: Sat, 13 Apr 2024 15:46:36 +0800 Subject: [PATCH] [Clang] Diagnose apply AST consume actions on LLVM IR Signed-off-by: yronglin --- .../clang/Basic/DiagnosticFrontendKinds.td| 3 ++ clang/lib/Frontend/FrontendAction.cpp | 7 +++-- clang/test/Frontend/ast-dump-on-llvm.ll | 29 +++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 clang/test/Frontend/ast-dump-on-llvm.ll diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 14b08d4927ec5e..2cf4ddfa4e805d 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -370,4 +370,7 @@ def warn_missing_symbol_graph_dir : Warning< "Missing symbol graph output directory, defaulting to working directory">, InGroup; +def err_ast_action_on_unparsable_source : Error< + "can not apply ast actions to LLVM IR file '%0'">, + DefaultFatal; } diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index b7c9967316f0b8..4d5a6aaf0b5f71 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -757,8 +757,11 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // IR files bypass the rest of initialization. if (Input.getKind().getLanguage() == Language::LLVM_IR) { -assert(hasIRSupport() && - "This action does not have IR file support!"); +if (!hasIRSupport()) { + CI.getDiagnostics().Report(diag::err_ast_action_on_unparsable_source) + << Input.getFile(); + return false; +} // Inform the diagnostic client we are processing a source file. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr); diff --git a/clang/test/Frontend/ast-dump-on-llvm.ll b/clang/test/Frontend/ast-dump-on-llvm.ll new file mode 100644 index 00..72aafc361cde84 --- /dev/null +++ b/clang/test/Frontend/ast-dump-on-llvm.ll @@ -0,0 +1,29 @@ +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=json %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-JSON +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=default %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-DEFAULT +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=json %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-JSON +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=default %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-DEFAULT + +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-print %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-PRINT +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-view %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-VIEW +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-list %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-LIST +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-lookups %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-LOOKUP +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-filter=FunctionDecl %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-FILTER-EQ +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-decl-types %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-DECL-TYPES +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-SYNTAX-ONLY + + +; CHECK-AST-DUMP: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-EQ-JSON: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-EQ-DEFAULT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL-EQ-JSON: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL-EQ-DEFAULT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-PRINT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-VIEW: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-LIST: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-LOOKUP: fatal error: can not apply ast
[clang] [Clang] Diagnose apply AST consume actions on LLVM IR (PR #88602)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (yronglin) Changes Fixes https://github.com/llvm/llvm-project/issues/88522 This PR introduce a new diagnostic to report apply AST consume actions on LLVM IR. --- Full diff: https://github.com/llvm/llvm-project/pull/88602.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticFrontendKinds.td (+3) - (modified) clang/lib/Frontend/FrontendAction.cpp (+5-2) - (added) clang/test/Frontend/ast-dump-on-llvm.ll (+29) ``diff diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td index 14b08d4927ec5e..2cf4ddfa4e805d 100644 --- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td @@ -370,4 +370,7 @@ def warn_missing_symbol_graph_dir : Warning< "Missing symbol graph output directory, defaulting to working directory">, InGroup; +def err_ast_action_on_unparsable_source : Error< + "can not apply ast actions to LLVM IR file '%0'">, + DefaultFatal; } diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index b7c9967316f0b8..4d5a6aaf0b5f71 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -757,8 +757,11 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // IR files bypass the rest of initialization. if (Input.getKind().getLanguage() == Language::LLVM_IR) { -assert(hasIRSupport() && - "This action does not have IR file support!"); +if (!hasIRSupport()) { + CI.getDiagnostics().Report(diag::err_ast_action_on_unparsable_source) + << Input.getFile(); + return false; +} // Inform the diagnostic client we are processing a source file. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr); diff --git a/clang/test/Frontend/ast-dump-on-llvm.ll b/clang/test/Frontend/ast-dump-on-llvm.ll new file mode 100644 index 00..72aafc361cde84 --- /dev/null +++ b/clang/test/Frontend/ast-dump-on-llvm.ll @@ -0,0 +1,29 @@ +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=json %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-JSON +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump=default %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-EQ-DEFAULT +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=json %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-JSON +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-all=default %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-ALL-EQ-DEFAULT + +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-print %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-PRINT +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-view %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-VIEW +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-list %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-LIST +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-lookups %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-LOOKUP +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-filter=FunctionDecl %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-FILTER-EQ +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -ast-dump-decl-types %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-AST-DUMP-DECL-TYPES +; RUN: not %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-SYNTAX-ONLY + + +; CHECK-AST-DUMP: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-EQ-JSON: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-EQ-DEFAULT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL-EQ-JSON: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-ALL-EQ-DEFAULT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-PRINT: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-VIEW: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-LIST: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-LOOKUP: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-FILTER-EQ: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-AST-DUMP-DECL-TYPES: fatal error: can not apply ast actions to LLVM IR file '{{.*}}' +; CHECK-S
[clang] Add new flag -Wpointer-integer-ordered-compare (PR #88489)
https://github.com/vincent-mailhol edited https://github.com/llvm/llvm-project/pull/88489 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add new flag -Wpointer-integer-ordered-compare (PR #88489)
@@ -0,0 +1,30 @@ +// RUN: %clang_cc1 -Wno-pointer-integer-compare -Wpointer-integer-ordered-compare -fsyntax-only -verify=pointer-integer-ordered %s +// RUN: %clang_cc1 -Wpointer-integer-compare -Wno-pointer-integer-ordered-compare -fsyntax-only -verify=pointer-integer %s + +void test1(int *a){ +int b = 1; +short c = 1; +if(c=0; // pointer-integer-ordered-warning{{ordered comparison between pointer and zero ('int *' and 'int') is an extension}} +} + +int test3(int *a){ +return a>=1; // pointer-integer-ordered-warning{{ordered comparison between pointer and integer ('int *' and 'int')}} +} + +int test4(int *a){ +return a>1; // pointer-integer-ordered-warning{{ordered comparison between pointer and integer ('int *' and 'int')}} +} +int test5(int *a){ vincent-mailhol wrote: Nitpick: add newline between functions ```suggestion } int test5(int *a){ ``` https://github.com/llvm/llvm-project/pull/88489 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add new flag -Wpointer-integer-ordered-compare (PR #88489)
https://github.com/vincent-mailhol commented: Thanks for taking care of the issue I created. For what it is worth, here is my review. I am not a contributor of the llvm project, so I only left superficial nitpicks. https://github.com/llvm/llvm-project/pull/88489 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add new flag -Wpointer-integer-ordered-compare (PR #88489)
@@ -714,10 +714,11 @@ def HeaderHygiene : DiagGroup<"header-hygiene">; def DuplicateDeclSpecifier : DiagGroup<"duplicate-decl-specifier">; def CompareDistinctPointerType : DiagGroup<"compare-distinct-pointer-types">; def GNUUnionCast : DiagGroup<"gnu-union-cast">; +def PointerIntegerOrderedCompare : DiagGroup<"pointer-integer-ordered-compare">; +def PointerIntegerCompare : DiagGroup<"pointer-integer-compare",[PointerIntegerOrderedCompare]>; def GNUVariableSizedTypeNotAtEnd : DiagGroup<"gnu-variable-sized-type-not-at-end">; def Varargs : DiagGroup<"varargs">; def XorUsedAsPow : DiagGroup<"xor-used-as-pow">; - vincent-mailhol wrote: Nitpick: this line removal is not related to the commit. ```suggestion ``` https://github.com/llvm/llvm-project/pull/88489 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add new flag -Wpointer-integer-ordered-compare (PR #88489)
@@ -245,6 +245,12 @@ Modified Compiler Flags f3 *c = (f3 *)x; } +- Added a new diagnostic flag ``-Wpointer-integer-ordered-compare`` which is + grouped under ``-Wpointer-integer-compare`` and moved previously + ungrouped diagnostics ``ext_typecheck_ordered_comparison_of_pointer_integer``, + ``ext_typecheck_ordered_comparison_of_pointer_and_zero`` under + ``-Wpointer-integer-ordered-compare``. Fixes #GH88090 vincent-mailhol wrote: Maybe add a sentence to say that this also resolves a false negative for comparison between pointers and literal zero. https://github.com/llvm/llvm-project/pull/88489 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C99] Claim conformance for _Complex support (PR #88161)
h-vetinari wrote: I'm surprised about the "compiler-rt is not supported on windows" comment - in our distribution, we've been building compiler-rt on windows for years, and I don't remember significant issues. It's true that `__divsc3` is not available _without_ compiler-rt (i.e. just relying on the msvc runtime libraries), but together with compiler-rt these things are generally possible? Not that a similar [situation](https://github.com/llvm/llvm-project/issues/54596) exists on `osx-arm` for example - in certain situations, linking `compiler-rt` is unavoidable. https://github.com/llvm/llvm-project/pull/88161 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: Thanks! Could you add this DeclPrinterTest unittest for regression? ``` TEST(DeclPrinter, TestTemplateFinal) { ASSERT_TRUE(PrintedDeclCXX11Matches( "template" "class FinalTemplate final {};", classTemplateDecl(hasName("FinalTemplate")).bind("id"), "template class FinalTemplate final {}")); } ``` This is my expectation for correct output, but the current branch seems to disagree -- now there's two spaces between `final` and `{}`. Not sure if that's a problem. IWYU has enough post-processing that it doesn't break us either way. https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll created https://github.com/llvm/llvm-project/pull/88611 This patch touches a number of tests that run in C++98 mode that have been using array size as a context that requires a constant expression, replacing it with a `static_assert` backported via a macro. This reduces noise in expected directives that comes from diagnostics around VLAs. This patch also showcases that DR tests would benefit from olding in constant expression in C++98 mode, but I'm not sure it's even on the table. If it is, I'd be happy to prepare a PR for that, and rebase this PR on top of it. CC @AaronBallman >From c436fe6b0883577f434ee456fdffb224191108e0 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Sat, 13 Apr 2024 12:46:32 +0300 Subject: [PATCH] [clang] Migrate DR tests to `static_assert` --- clang/test/CXX/drs/dr0xx.cpp | 12 clang/test/CXX/drs/dr16xx.cpp | 5 ++--- clang/test/CXX/drs/dr1xx.cpp | 19 --- clang/test/CXX/drs/dr2xx.cpp | 15 ++- clang/test/CXX/drs/dr3xx.cpp | 32 ++-- clang/test/CXX/drs/dr4xx.cpp | 22 -- 6 files changed, 62 insertions(+), 43 deletions(-) diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp index a304862885c640..c30d9710e8d00a 100644 --- a/clang/test/CXX/drs/dr0xx.cpp +++ b/clang/test/CXX/drs/dr0xx.cpp @@ -5,6 +5,11 @@ // RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple // RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + namespace cwg1 { // cwg1: no namespace X { extern "C" void cwg1_f(int a = 1); } namespace Y { extern "C" void cwg1_f(int a = 1); } @@ -1163,10 +1168,9 @@ namespace cwg75 { // cwg75: yes namespace cwg76 { // cwg76: yes const volatile int n = 1; - int arr[n]; // #cwg76-vla - // expected-error@#cwg76-vla {{variable length arrays in C++ are a Clang extension}} - // expected-note@#cwg76-vla {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} - // expected-error@#cwg76-vla {{variable length array declaration not allowed at file scope}} + static_assert(n, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} + // expected-note@-2 {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} } namespace cwg77 { // cwg77: yes diff --git a/clang/test/CXX/drs/dr16xx.cpp b/clang/test/CXX/drs/dr16xx.cpp index 6d7bb7619f8b8b..cf6b45ceabf2cc 100644 --- a/clang/test/CXX/drs/dr16xx.cpp +++ b/clang/test/CXX/drs/dr16xx.cpp @@ -153,10 +153,9 @@ namespace cwg1645 { // cwg1645: 3.9 namespace cwg1652 { // cwg1652: 3.6 int a, b; - int arr[&a + 1 == &b ? 1 : 2]; - // expected-error@-1 {{variable length arrays in C++ are a Clang extension}} + static_assert(&a + 1 == &b, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} // expected-note@-2 {{comparison against pointer '&a + 1' that points past the end of a complete object has unspecified value}} - // expected-error@-3 {{variable length array declaration not allowed at file scope}} } namespace cwg1653 { // cwg1653: 4 c++17 diff --git a/clang/test/CXX/drs/dr1xx.cpp b/clang/test/CXX/drs/dr1xx.cpp index 5b497dda047d6a..276ac0c11a0e77 100644 --- a/clang/test/CXX/drs/dr1xx.cpp +++ b/clang/test/CXX/drs/dr1xx.cpp @@ -5,6 +5,17 @@ // RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__builtin_constant_p(x) ? (x) : (x)) +#else +#define __enable_constant_folding +#endif + namespace cwg100 { // cwg100: yes template struct A {}; // #cwg100-A template struct B {}; // #cwg100-B @@ -745,13 +756,7 @@ namespace cwg148 { // cwg148: yes namespace cwg151 { // cwg151: 3.1 struct X {}; typedef int X::*p; -#if __cplusplus < 201103L -#define fold(x) (__builtin_constant_p(0) ? (x) : (x)) -#else -#define fold -#endif - int check[fold(p() == 0) ? 1 : -1]; -#undef fold + static_assert(__enable_constant_folding(p() == 0), ""); } namespace cwg152 { // cwg152: yes diff --git a/clang/test/CXX/drs/dr2xx.cpp b/clang/test/CXX/drs/dr2xx.cpp index e655
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Vlad Serebrennikov (Endilll) Changes This patch touches a number of tests that run in C++98 mode that have been using array size as a context that requires a constant expression, replacing it with a `static_assert` backported via a macro. This reduces noise in expected directives that comes from diagnostics around VLAs. This patch also showcases that DR tests would benefit from olding in constant expression in C++98 mode, but I'm not sure it's even on the table. If it is, I'd be happy to prepare a PR for that, and rebase this PR on top of it. CC @AaronBallman --- Full diff: https://github.com/llvm/llvm-project/pull/88611.diff 6 Files Affected: - (modified) clang/test/CXX/drs/dr0xx.cpp (+8-4) - (modified) clang/test/CXX/drs/dr16xx.cpp (+2-3) - (modified) clang/test/CXX/drs/dr1xx.cpp (+12-7) - (modified) clang/test/CXX/drs/dr2xx.cpp (+10-5) - (modified) clang/test/CXX/drs/dr3xx.cpp (+18-14) - (modified) clang/test/CXX/drs/dr4xx.cpp (+12-10) ``diff diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp index a304862885c640..c30d9710e8d00a 100644 --- a/clang/test/CXX/drs/dr0xx.cpp +++ b/clang/test/CXX/drs/dr0xx.cpp @@ -5,6 +5,11 @@ // RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple // RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + namespace cwg1 { // cwg1: no namespace X { extern "C" void cwg1_f(int a = 1); } namespace Y { extern "C" void cwg1_f(int a = 1); } @@ -1163,10 +1168,9 @@ namespace cwg75 { // cwg75: yes namespace cwg76 { // cwg76: yes const volatile int n = 1; - int arr[n]; // #cwg76-vla - // expected-error@#cwg76-vla {{variable length arrays in C++ are a Clang extension}} - // expected-note@#cwg76-vla {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} - // expected-error@#cwg76-vla {{variable length array declaration not allowed at file scope}} + static_assert(n, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} + // expected-note@-2 {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} } namespace cwg77 { // cwg77: yes diff --git a/clang/test/CXX/drs/dr16xx.cpp b/clang/test/CXX/drs/dr16xx.cpp index 6d7bb7619f8b8b..cf6b45ceabf2cc 100644 --- a/clang/test/CXX/drs/dr16xx.cpp +++ b/clang/test/CXX/drs/dr16xx.cpp @@ -153,10 +153,9 @@ namespace cwg1645 { // cwg1645: 3.9 namespace cwg1652 { // cwg1652: 3.6 int a, b; - int arr[&a + 1 == &b ? 1 : 2]; - // expected-error@-1 {{variable length arrays in C++ are a Clang extension}} + static_assert(&a + 1 == &b, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} // expected-note@-2 {{comparison against pointer '&a + 1' that points past the end of a complete object has unspecified value}} - // expected-error@-3 {{variable length array declaration not allowed at file scope}} } namespace cwg1653 { // cwg1653: 4 c++17 diff --git a/clang/test/CXX/drs/dr1xx.cpp b/clang/test/CXX/drs/dr1xx.cpp index 5b497dda047d6a..276ac0c11a0e77 100644 --- a/clang/test/CXX/drs/dr1xx.cpp +++ b/clang/test/CXX/drs/dr1xx.cpp @@ -5,6 +5,17 @@ // RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__builtin_constant_p(x) ? (x) : (x)) +#else +#define __enable_constant_folding +#endif + namespace cwg100 { // cwg100: yes template struct A {}; // #cwg100-A template struct B {}; // #cwg100-B @@ -745,13 +756,7 @@ namespace cwg148 { // cwg148: yes namespace cwg151 { // cwg151: 3.1 struct X {}; typedef int X::*p; -#if __cplusplus < 201103L -#define fold(x) (__builtin_constant_p(0) ? (x) : (x)) -#else -#define fold -#endif - int check[fold(p() == 0) ? 1 : -1]; -#undef fold + static_assert(__enable_constant_folding(p() == 0), ""); } namespace cwg152 { // cwg152: yes diff --git a/clang/test/CXX/drs/dr2xx.cpp b/clang/test/CXX/drs/dr2xx.cpp index e655e7226d51d6..2f1d18008d04db 100644 --- a/clang/test/CXX/drs/dr2xx.cpp +++ b/clang/test/CXX/drs/dr2xx.cpp @@ -10,10 +10,15 @@ typedef __SIZE_TYPE__ size_t; //
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
Endilll wrote: This PR removes a FIXME since it doesn't make sense anymore in that particular context. I created issue #88608 out of it to make sure we don't lose track of it. https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [llvm] Add triples for managarm (PR #87845)
no92 wrote: Ping https://github.com/llvm/llvm-project/pull/87845 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Sirraide edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Sirraide commented: I remember thinking that using array sizes for this was a bit outdated the last time I saw a test that did this, so it’s nice to see them refactored. https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
@@ -5,6 +5,17 @@ // RUN: %clang_cc1 -std=c++11 -verify=expected,cxx98-14,cxx98-17,cxx98-20,cxx11-14,since-cxx11 -triple %itanium_abi_triple %s -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++98 -verify=expected,cxx98-14,cxx98-17,cxx98-20,cxx98 -triple %itanium_abi_triple %s -fexceptions -fcxx-exceptions -pedantic-errors +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__builtin_constant_p(x) ? (x) : (x)) +#else +#define __enable_constant_folding +#endif Sirraide wrote: I don’t think we normally do that too often for tests, but this is the third file or so that I’ve seen so far that uses these macros, so I’d maybe suggest moving them into a header that the tests can include (especially considering you said you’re going to refactor more tests than just these) if that doesn’t cause any problems. https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 0412a86 - [clang] Add missing documentation entry for `__is_pointer_interconvertible_base_of()`
Author: Vlad Serebrennikov Date: 2024-04-13T13:10:42+03:00 New Revision: 0412a8651aa6cbdd697e904a758e0f95e6635cee URL: https://github.com/llvm/llvm-project/commit/0412a8651aa6cbdd697e904a758e0f95e6635cee DIFF: https://github.com/llvm/llvm-project/commit/0412a8651aa6cbdd697e904a758e0f95e6635cee.diff LOG: [clang] Add missing documentation entry for `__is_pointer_interconvertible_base_of()` Added: Modified: clang/docs/LanguageExtensions.rst Removed: diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst index 7b23e4d1c2f30c..96691b45d63a37 100644 --- a/clang/docs/LanguageExtensions.rst +++ b/clang/docs/LanguageExtensions.rst @@ -1610,6 +1610,7 @@ The following type trait primitives are supported by Clang. Those traits marked * ``__is_pod`` (C++, GNU, Microsoft, Embarcadero): Note, the corresponding standard trait was deprecated in C++20. * ``__is_pointer`` (C++, Embarcadero) +* ``__is_pointer_interconvertible_base_of`` (C++, GNU, Microsoft) * ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero) * ``__is_reference`` (C++, Embarcadero) * ``__is_referenceable`` (C++, GNU, Microsoft, Embarcadero): ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
@@ -5,6 +5,17 @@ // RUN: %clang_cc1 -std=c++11 -verify=expected,cxx98-14,cxx98-17,cxx98-20,cxx11-14,since-cxx11 -triple %itanium_abi_triple %s -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++98 -verify=expected,cxx98-14,cxx98-17,cxx98-20,cxx98 -triple %itanium_abi_triple %s -fexceptions -fcxx-exceptions -pedantic-errors +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__builtin_constant_p(x) ? (x) : (x)) +#else +#define __enable_constant_folding +#endif Endilll wrote: You're correct that having a very thin standard/backporting library would be beneficial. There have been efforts last year to improve testing infrastructure, and this particular detail was a part of the plan, but those efforts have been stalled for months. I'd keep things as-is until the time comes. I've put up an RFC a year ago if you're interested in a context: https://discourse.llvm.org/t/rfc-opt-in-way-to-make-verifydiagnosticconsumer-slightly-less-strict/70747 https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -2193,6 +2193,41 @@ struct FormatStyle { /// \version 3.7 bool BreakBeforeTernaryOperators; + /// Different ways to Break Between Chevrons. + enum BreakChevronOperatorStyle : int8_t { +/// Break using ColumnLimit rules. +/// \code +/// os << "a" << "b" << "\n"; +/// \endcode +BCOS_Never, +/// Break between adjacent strings. +/// \code +/// os << "a" +/// << "b" +/// << "\n"; +/// \endcode +BCOS_BetweenStrings, +/// Break between adjacent strings that end with \n. +/// \code +/// os << "a\n" +/// << "b" << "c\n" +/// << "\n"; +/// \endcode +BCOS_BetweenNewlineStrings, +/// Break between adjacent chevrons. +/// \code +/// os << "a\n" +/// << "b" +/// << "c\n" +/// << "\n"; +/// \endcode +BCOS_Always + }; + + /// Break Between Chevron Operators + /// \version 19 + BreakChevronOperatorStyle BreakChevronOperator; mydeveloperday wrote: So later commit in the PR do >> as well as << so maybe just BreakStreamOperator? WDYT https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -5598,10 +5598,34 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // FIXME: Breaking after newlines seems useful in general. Turn this into an // option and recognize more cases like endl etc, and break independent of // what comes after operator lessless. - if (Right.is(tok::lessless) && Right.Next && - Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && - Left.TokenText.ends_with("\\n\"")) { -return true; + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenStrings) { +if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && +Right.Next->is(tok::string_literal)) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenNewlineStrings) { +if (Right.is(tok::lessless) && Right.Next && +Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && +Left.TokenText.ends_with("\\n\"")) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_Always) { +// can be std::os or os +auto *FirstChevron = Right.Previous; +while (FirstChevron) { mydeveloperday wrote: yes anything with std::os in https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
https://github.com/mydeveloperday updated https://github.com/llvm/llvm-project/pull/88490 >From 1c11c3edd0005a729561d84b9a815279b356e8db Mon Sep 17 00:00:00 2001 From: mydeveloperday Date: Fri, 12 Apr 2024 10:32:19 +0100 Subject: [PATCH 1/7] [clang-format] revery to string << string handling back to previous default Fixes 88433 A change made to the handling of chevron operators causes a large amount of flux in code bases that were previously using clang-format, this fix reverts that change to the default behaviour but adds that new behaviour behind a new option. --- clang/docs/ClangFormatStyleOptions.rst | 34 ++ clang/docs/ReleaseNotes.rst| 2 ++ clang/include/clang/Format/Format.h| 28 +++ clang/lib/Format/Format.cpp| 13 +++ clang/lib/Format/TokenAnnotator.cpp| 16 ++--- clang/unittests/Format/ConfigParseTest.cpp | 8 + clang/unittests/Format/FormatTest.cpp | 42 -- 7 files changed, 136 insertions(+), 7 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 39f7cded36edbf..a40a940f39d860 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -3258,6 +3258,40 @@ the configuration (without a prefix: ``Auto``). firstValue : SecondValueVeryVeryVeryVeryLong; +.. _BreakChevronOperator: + +**BreakChevronOperator** (``BreakChevronOperatorStyle``) :versionbadge:`clang-format 19` :ref:`¶ ` + Break Between Chevron Operators + + Possible values: + + * ``BCOS_Never`` (in configuration: ``Never``) +Break using ColumnLimit rules. + +.. code-block:: c++ + + os << "a" << "b" << "\n"; + + * ``BCOS_BetweenStrings`` (in configuration: ``BetweenStrings``) +Break between adjacent strings. + +.. code-block:: c++ + + os << "a" + << "b" + << "\n"; + + * ``BCOS_BetweenNewlineStrings`` (in configuration: ``BetweenNewlineStrings``) +Break between adjacent strings that end with \n. + +.. code-block:: c++ + + os << "a\n" + << "b" << "c\n" + << "\n"; + + + .. _BreakConstructorInitializers: **BreakConstructorInitializers** (``BreakConstructorInitializersStyle``) :versionbadge:`clang-format 5` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 45a9a79739a4eb..01838b0ccd653d 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -671,6 +671,8 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- ``BreakChevronOperator`` Style is added and the previous default + of breaking between strings is reverted. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 48f5fb44157570..205c597af8fb0f 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -2193,6 +2193,33 @@ struct FormatStyle { /// \version 3.7 bool BreakBeforeTernaryOperators; + /// Different ways to Break Between Chevrons + enum BreakChevronOperatorStyle : int8_t { +/// Break using ColumnLimit rules. +/// \code +/// os << "a" << "b" << "\n"; +/// \endcode +BCOS_Never, +/// Break between adjacent strings. +/// \code +/// os << "a" +/// << "b" +/// << "\n"; +/// \endcode +BCOS_BetweenStrings, +/// Break between adjacent strings that end with \n. +/// \code +/// os << "a\n" +/// << "b" << "c\n" +/// << "\n"; +/// \endcode +BCOS_BetweenNewlineStrings + }; + + /// Break Between Chevron Operators + /// \version 19 + BreakChevronOperatorStyle BreakChevronOperator; + /// Different ways to break initializers. enum BreakConstructorInitializersStyle : int8_t { /// Break constructor initializers before the colon and after the commas. @@ -4951,6 +4978,7 @@ struct FormatStyle { BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations && BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon && BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators && + BreakChevronOperator == R.BreakChevronOperator && BreakConstructorInitializers == R.BreakConstructorInitializers && BreakFunctionDefinitionParameters == R.BreakFunctionDefinitionParameters && diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 89e6c19b0af45c..b781a7e161db78 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -243,6 +243,17 @@ struct ScalarEnumerationTraits { } }; +template <> +struct ScalarEnumerationTraits { + static void enumeration(IO &IO, + FormatStyle::BreakChevronOperatorStyle &Value)
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
https://github.com/mydeveloperday updated https://github.com/llvm/llvm-project/pull/88490 >From 1c11c3edd0005a729561d84b9a815279b356e8db Mon Sep 17 00:00:00 2001 From: mydeveloperday Date: Fri, 12 Apr 2024 10:32:19 +0100 Subject: [PATCH 1/8] [clang-format] revery to string << string handling back to previous default Fixes 88433 A change made to the handling of chevron operators causes a large amount of flux in code bases that were previously using clang-format, this fix reverts that change to the default behaviour but adds that new behaviour behind a new option. --- clang/docs/ClangFormatStyleOptions.rst | 34 ++ clang/docs/ReleaseNotes.rst| 2 ++ clang/include/clang/Format/Format.h| 28 +++ clang/lib/Format/Format.cpp| 13 +++ clang/lib/Format/TokenAnnotator.cpp| 16 ++--- clang/unittests/Format/ConfigParseTest.cpp | 8 + clang/unittests/Format/FormatTest.cpp | 42 -- 7 files changed, 136 insertions(+), 7 deletions(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index 39f7cded36edbf..a40a940f39d860 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -3258,6 +3258,40 @@ the configuration (without a prefix: ``Auto``). firstValue : SecondValueVeryVeryVeryVeryLong; +.. _BreakChevronOperator: + +**BreakChevronOperator** (``BreakChevronOperatorStyle``) :versionbadge:`clang-format 19` :ref:`¶ ` + Break Between Chevron Operators + + Possible values: + + * ``BCOS_Never`` (in configuration: ``Never``) +Break using ColumnLimit rules. + +.. code-block:: c++ + + os << "a" << "b" << "\n"; + + * ``BCOS_BetweenStrings`` (in configuration: ``BetweenStrings``) +Break between adjacent strings. + +.. code-block:: c++ + + os << "a" + << "b" + << "\n"; + + * ``BCOS_BetweenNewlineStrings`` (in configuration: ``BetweenNewlineStrings``) +Break between adjacent strings that end with \n. + +.. code-block:: c++ + + os << "a\n" + << "b" << "c\n" + << "\n"; + + + .. _BreakConstructorInitializers: **BreakConstructorInitializers** (``BreakConstructorInitializersStyle``) :versionbadge:`clang-format 5` :ref:`¶ ` diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 45a9a79739a4eb..01838b0ccd653d 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -671,6 +671,8 @@ clang-format ``BreakTemplateDeclarations``. - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to ``BreakAfterReturnType``. +- ``BreakChevronOperator`` Style is added and the previous default + of breaking between strings is reverted. libclang diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index 48f5fb44157570..205c597af8fb0f 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -2193,6 +2193,33 @@ struct FormatStyle { /// \version 3.7 bool BreakBeforeTernaryOperators; + /// Different ways to Break Between Chevrons + enum BreakChevronOperatorStyle : int8_t { +/// Break using ColumnLimit rules. +/// \code +/// os << "a" << "b" << "\n"; +/// \endcode +BCOS_Never, +/// Break between adjacent strings. +/// \code +/// os << "a" +/// << "b" +/// << "\n"; +/// \endcode +BCOS_BetweenStrings, +/// Break between adjacent strings that end with \n. +/// \code +/// os << "a\n" +/// << "b" << "c\n" +/// << "\n"; +/// \endcode +BCOS_BetweenNewlineStrings + }; + + /// Break Between Chevron Operators + /// \version 19 + BreakChevronOperatorStyle BreakChevronOperator; + /// Different ways to break initializers. enum BreakConstructorInitializersStyle : int8_t { /// Break constructor initializers before the colon and after the commas. @@ -4951,6 +4978,7 @@ struct FormatStyle { BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations && BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon && BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators && + BreakChevronOperator == R.BreakChevronOperator && BreakConstructorInitializers == R.BreakConstructorInitializers && BreakFunctionDefinitionParameters == R.BreakFunctionDefinitionParameters && diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index 89e6c19b0af45c..b781a7e161db78 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -243,6 +243,17 @@ struct ScalarEnumerationTraits { } }; +template <> +struct ScalarEnumerationTraits { + static void enumeration(IO &IO, + FormatStyle::BreakChevronOperatorStyle &Value)
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -5598,10 +5598,34 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // FIXME: Breaking after newlines seems useful in general. Turn this into an // option and recognize more cases like endl etc, and break independent of // what comes after operator lessless. - if (Right.is(tok::lessless) && Right.Next && - Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && - Left.TokenText.ends_with("\\n\"")) { -return true; + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenStrings) { +if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && +Right.Next->is(tok::string_literal)) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenNewlineStrings) { +if (Right.is(tok::lessless) && Right.Next && +Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && +Left.TokenText.ends_with("\\n\"")) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_Always) { +// can be std::os or os mydeveloperday wrote: when you have os << "A" << "B" you don't want to break between os and << so the loop tracks back to determine if this is the first << in the line, this must also handle std::os << and a::b::os etc.. whats its really saying is don't break before the first <<. https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll updated https://github.com/llvm/llvm-project/pull/88611 >From c436fe6b0883577f434ee456fdffb224191108e0 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Sat, 13 Apr 2024 12:46:32 +0300 Subject: [PATCH 1/4] [clang] Migrate DR tests to `static_assert` --- clang/test/CXX/drs/dr0xx.cpp | 12 clang/test/CXX/drs/dr16xx.cpp | 5 ++--- clang/test/CXX/drs/dr1xx.cpp | 19 --- clang/test/CXX/drs/dr2xx.cpp | 15 ++- clang/test/CXX/drs/dr3xx.cpp | 32 ++-- clang/test/CXX/drs/dr4xx.cpp | 22 -- 6 files changed, 62 insertions(+), 43 deletions(-) diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp index a304862885c640..c30d9710e8d00a 100644 --- a/clang/test/CXX/drs/dr0xx.cpp +++ b/clang/test/CXX/drs/dr0xx.cpp @@ -5,6 +5,11 @@ // RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple // RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + namespace cwg1 { // cwg1: no namespace X { extern "C" void cwg1_f(int a = 1); } namespace Y { extern "C" void cwg1_f(int a = 1); } @@ -1163,10 +1168,9 @@ namespace cwg75 { // cwg75: yes namespace cwg76 { // cwg76: yes const volatile int n = 1; - int arr[n]; // #cwg76-vla - // expected-error@#cwg76-vla {{variable length arrays in C++ are a Clang extension}} - // expected-note@#cwg76-vla {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} - // expected-error@#cwg76-vla {{variable length array declaration not allowed at file scope}} + static_assert(n, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} + // expected-note@-2 {{read of volatile-qualified type 'const volatile int' is not allowed in a constant expression}} } namespace cwg77 { // cwg77: yes diff --git a/clang/test/CXX/drs/dr16xx.cpp b/clang/test/CXX/drs/dr16xx.cpp index 6d7bb7619f8b8b..cf6b45ceabf2cc 100644 --- a/clang/test/CXX/drs/dr16xx.cpp +++ b/clang/test/CXX/drs/dr16xx.cpp @@ -153,10 +153,9 @@ namespace cwg1645 { // cwg1645: 3.9 namespace cwg1652 { // cwg1652: 3.6 int a, b; - int arr[&a + 1 == &b ? 1 : 2]; - // expected-error@-1 {{variable length arrays in C++ are a Clang extension}} + static_assert(&a + 1 == &b, ""); + // expected-error@-1 {{static assertion expression is not an integral constant expression}} // expected-note@-2 {{comparison against pointer '&a + 1' that points past the end of a complete object has unspecified value}} - // expected-error@-3 {{variable length array declaration not allowed at file scope}} } namespace cwg1653 { // cwg1653: 4 c++17 diff --git a/clang/test/CXX/drs/dr1xx.cpp b/clang/test/CXX/drs/dr1xx.cpp index 5b497dda047d6a..276ac0c11a0e77 100644 --- a/clang/test/CXX/drs/dr1xx.cpp +++ b/clang/test/CXX/drs/dr1xx.cpp @@ -5,6 +5,17 @@ // RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++23 -triple x86_64-unknown-unknown %s -verify=expected,since-cxx11,since-cxx17 -fexceptions -fcxx-exceptions -pedantic-errors +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__builtin_constant_p(x) ? (x) : (x)) +#else +#define __enable_constant_folding +#endif + namespace cwg100 { // cwg100: yes template struct A {}; // #cwg100-A template struct B {}; // #cwg100-B @@ -745,13 +756,7 @@ namespace cwg148 { // cwg148: yes namespace cwg151 { // cwg151: 3.1 struct X {}; typedef int X::*p; -#if __cplusplus < 201103L -#define fold(x) (__builtin_constant_p(0) ? (x) : (x)) -#else -#define fold -#endif - int check[fold(p() == 0) ? 1 : -1]; -#undef fold + static_assert(__enable_constant_folding(p() == 0), ""); } namespace cwg152 { // cwg152: yes diff --git a/clang/test/CXX/drs/dr2xx.cpp b/clang/test/CXX/drs/dr2xx.cpp index e655e7226d51d6..2f1d18008d04db 100644 --- a/clang/test/CXX/drs/dr2xx.cpp +++ b/clang/test/CXX/drs/dr2xx.cpp @@ -10,10 +10,15 @@ typedef __SIZE_TYPE__ size_t; // cxx98-error@-1 0-1 {{'long long' is a C++11 extension}} -#if __cplusplus < 201103L -#define fold(x) (__builtin_constant_p(x) ? (x) : (x)) +#if __cplusplus == 199711L +#define static_assert(...) __extension__ _Static_assert(__VA_ARGS__) +// cxx98-error@-1 {{variadic macros are a C99 feature}} +#endif + +#if __cplusplus == 199711L +#define __enable_constant_folding(x) (__
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: > With .PolishForDeclaration=true, there are NO final specifiers (which is what > we want to produce forward decls in IWYU) This is actually a regression in this PR, and it breaks the clangd test added here: https://github.com/llvm/llvm-project/commit/9f57b65a272817752aa00e2fb94154e6eed1d0ec (the patch that originally led to double `final`s). https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] cbfcfdf - [clang][NFC] Add a test for CWG2254 to `is_pointer_interconvertible_base_of` tests
Author: Vlad Serebrennikov Date: 2024-04-13T15:17:04+03:00 New Revision: cbfcfdf75e9939bc47ac7a7c11d2122a6ad426ed URL: https://github.com/llvm/llvm-project/commit/cbfcfdf75e9939bc47ac7a7c11d2122a6ad426ed DIFF: https://github.com/llvm/llvm-project/commit/cbfcfdf75e9939bc47ac7a7c11d2122a6ad426ed.diff LOG: [clang][NFC] Add a test for CWG2254 to `is_pointer_interconvertible_base_of` tests Resolution of that issue makes _any_ base class subobject interconvertible with the containing object, not just the first one. Added: Modified: clang/test/SemaCXX/type-traits.cpp Removed: diff --git a/clang/test/SemaCXX/type-traits.cpp b/clang/test/SemaCXX/type-traits.cpp index d43701c3d976e0..dee4a29bd2bffe 100644 --- a/clang/test/SemaCXX/type-traits.cpp +++ b/clang/test/SemaCXX/type-traits.cpp @@ -1864,6 +1864,7 @@ void is_pointer_interconvertible_base_of(int n) static_assert(!__is_pointer_interconvertible_base_of(Base2, Derived)); static_assert(__is_pointer_interconvertible_base_of(Base, DerivedIndirect)); static_assert(__is_pointer_interconvertible_base_of(Base, DerivedMultiple)); + static_assert(__is_pointer_interconvertible_base_of(Base2, DerivedMultiple)); static_assert(!__is_pointer_interconvertible_base_of(Base3, DerivedMultiple)); static_assert(!__is_pointer_interconvertible_base_of(Base, DerivedAmbiguous)); static_assert(__is_pointer_interconvertible_base_of(Base, DerivedPrivate)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Migrate DR tests to `static_assert` (PR #88611)
Endilll wrote: > (especially considering you said you’re going to refactor more tests than > just these) @Sirraide I didn't say that originally, but you reminded me that I indeed forgot about all the uses of arrays that don't trigger diagnostics. I went over all of them, and decided to include them in this patch instead of doing a follow-up NFC commit, since it's not too much of them actually. https://github.com/llvm/llvm-project/pull/88611 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Sema] Fix issue on requires expression with templated base class member function (PR #85198)
@@ -7735,7 +7735,8 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, } if (CXXMethodDecl *Method = dyn_cast_or_null(FDecl)) -if (Method->isImplicitObjectMemberFunction()) +if (!isa(CurContext) && jcsxky wrote: Do you mean that checking whether `Method` is an implicit object function is redundant? After I removed https://github.com/llvm/llvm-project/blob/844b532713986999aa1ffed0883eff2d1339ec7a/clang/lib/Sema/SemaExpr.cpp#L7723-L7726 These testcase failed https://github.com/llvm/llvm-project/blob/844b532713986999aa1ffed0883eff2d1339ec7a/clang/test/CXX/drs/dr3xx.cpp#L1084-L1095 https://github.com/llvm/llvm-project/blob/844b532713986999aa1ffed0883eff2d1339ec7a/clang/test/SemaTemplate/instantiate-using-decl.cpp#L150-L168 with no diagnose. Or the checking shouldn't be placed at current position? https://github.com/llvm/llvm-project/pull/85198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/88600 >From bcd04db735a78b4d7df93e88229ea4e2491fc09e Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 13 Apr 2024 06:39:34 + Subject: [PATCH] Fix the double space and double attribute printing of the final keyword. Fixes #56517. --- clang/lib/AST/DeclPrinter.cpp | 31 - clang/test/SemaCXX/cxx11-attr-print.cpp | 5 clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl | 4 +-- clang/unittests/AST/DeclPrinterTest.cpp | 8 ++ clang/utils/TableGen/ClangAttrEmitter.cpp | 2 +- 5 files changed, 34 insertions(+), 16 deletions(-) diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp index 6afdb6cfccb142..c82d18be7741e5 100644 --- a/clang/lib/AST/DeclPrinter.cpp +++ b/clang/lib/AST/DeclPrinter.cpp @@ -119,7 +119,7 @@ namespace { void printTemplateArguments(llvm::ArrayRef Args, const TemplateParameterList *Params); enum class AttrPosAsWritten { Default = 0, Left, Right }; -void +bool prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos = AttrPosAsWritten::Default); void prettyPrintPragmas(Decl *D); @@ -252,10 +252,12 @@ static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, return DeclPrinter::AttrPosAsWritten::Right; } -void DeclPrinter::prettyPrintAttributes(const Decl *D, +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos /*=Default*/) { + bool hasPrinted = false; if (Policy.PolishForDeclaration) -return; +return hasPrinted; if (D->hasAttrs()) { const AttrVec &Attrs = D->getAttrs(); @@ -275,6 +277,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, if (Pos != AttrPosAsWritten::Left) Out << ' '; A->printPretty(Out, Policy); + hasPrinted = true; if (Pos == AttrPosAsWritten::Left) Out << ' '; } @@ -282,6 +285,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, } } } + return hasPrinted; } void DeclPrinter::prettyPrintPragmas(Decl *D) { @@ -1060,12 +1064,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { // FIXME: add printing of pragma attributes if required. if (!Policy.SuppressSpecifiers && D->isModulePrivate()) Out << "__module_private__ "; - Out << D->getKindName(); - prettyPrintAttributes(D); + Out << D->getKindName() << ' '; - if (D->getIdentifier()) { + // FIXME: Move before printing the decl kind to match the behavior of the + // attribute printing for variables and function where they are printed first. + if (prettyPrintAttributes(D, AttrPosAsWritten::Left)) Out << ' '; + + if (D->getIdentifier()) { if (auto *NNS = D->getQualifier()) NNS->print(Out, Policy); Out << *D; @@ -1082,13 +1089,10 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { } } - if (D->hasDefinition()) { -if (D->hasAttr()) { - Out << " final"; -} - } + prettyPrintAttributes(D, AttrPosAsWritten::Right); if (D->isCompleteDefinition()) { +Out << ' '; // Print the base classes if (D->getNumBases()) { Out << " : "; @@ -1109,15 +1113,16 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { if (Base->isPackExpansion()) Out << "..."; +Out << ' '; } } // Print the class definition // FIXME: Doesn't print access specifiers, e.g., "public:" if (Policy.TerseOutput) { - Out << " {}"; + Out << "{}"; } else { - Out << " {\n"; + Out << "{\n"; VisitDeclContext(D); Indent() << "}"; } diff --git a/clang/test/SemaCXX/cxx11-attr-print.cpp b/clang/test/SemaCXX/cxx11-attr-print.cpp index a169d1b4409b4d..2b084018bc0662 100644 --- a/clang/test/SemaCXX/cxx11-attr-print.cpp +++ b/clang/test/SemaCXX/cxx11-attr-print.cpp @@ -87,3 +87,8 @@ template struct S; // CHECK: using Small2 {{\[}}[gnu::mode(byte)]] = int; using Small2 [[gnu::mode(byte)]] = int; + +class FinalNonTemplate final {}; +// CHECK: class FinalNonTemplate final { +template class FinalTemplate final {}; +// CHECK: template class FinalTemplate final { diff --git a/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl b/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl index 7e79ae3bf005fc..b1a15c43191829 100644 --- a/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl +++ b/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl @@ -6,11 +6,11 @@ typedef vector float3; RWBuffer Buffer; // expected-error@+2 {{class template 'RWBuffer' requires template arguments}} -// expected-note@*:* {{template declaration from hidden source: template class RWBuffer final}} +// expected-note@*:* {{template declaration from hidden source: template class RWBuffer}} RWBuffer BufferErr1; // expected
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
vgvassilev wrote: > > With .PolishForDeclaration=true, there are NO final specifiers (which is > > what we want to produce forward decls in IWYU) > > This is actually a regression in this PR, and it breaks the clangd test added > here: > [9f57b65](https://github.com/llvm/llvm-project/commit/9f57b65a272817752aa00e2fb94154e6eed1d0ec) > (the patch that originally led to double `final`s). > > EDIT: It looks like `prettyPrintAttributes` is only intended for semantic > attributes, whereas clangd wanted to preserve as-written `final` keyword. So > I wonder if this change needs to be tweaked a little: > https://github.com/llvm/llvm-project/pull/88600/files#diff-81d69bc555945d6582a758e0c094ff870cbc38697501ad7415694ee30c567dbfL1085 I've added a fix for your example. Can you provide a test case for the clangd use-case? https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: Thank you. I believe this should cover both cases, added some attempt at rationale in comments: ```diff diff --git a/clang/unittests/AST/DeclPrinterTest.cpp b/clang/unittests/AST/DeclPrinterTest.cpp index f2b027a25621..8691a6c38f16 100644 --- a/clang/unittests/AST/DeclPrinterTest.cpp +++ b/clang/unittests/AST/DeclPrinterTest.cpp @@ -86,16 +86,13 @@ PrintedDeclCXX98Matches(StringRef Code, const DeclarationMatcher &NodeMatch, ExpectedPrinted, "input.cc"); } -::testing::AssertionResult PrintedDeclCXX11Matches( - StringRef Code, - const DeclarationMatcher &NodeMatch, - StringRef ExpectedPrinted) { +::testing::AssertionResult +PrintedDeclCXX11Matches(StringRef Code, const DeclarationMatcher &NodeMatch, +StringRef ExpectedPrinted, +PrintingPolicyAdjuster PolicyModifier = nullptr) { std::vector Args(1, "-std=c++11"); - return PrintedDeclMatches(Code, -Args, -NodeMatch, -ExpectedPrinted, -"input.cc"); + return PrintedDeclMatches(Code, Args, NodeMatch, ExpectedPrinted, "input.cc", +PolicyModifier); } ::testing::AssertionResult PrintedDeclCXX11nonMSCMatches( @@ -1556,3 +1553,25 @@ TEST(DeclPrinter, VarDeclWithInitializer) { PrintedDeclCXX17Matches("void foo() {int arr[42]; for(int a : arr);}", namedDecl(hasName("a")).bind("id"), "int a")); } + +TEST(DeclPrinter, TestTemplateFinal) { + // By default we should print 'final' keyword whether class is implicitly or + // explicitly marked final. + ASSERT_TRUE(PrintedDeclCXX11Matches( + "template\n" + "class FinalTemplate final {};", + classTemplateDecl(hasName("FinalTemplate")).bind("id"), + "template class FinalTemplate final {}")); +} + +TEST(DeclPrinter, TestTemplateFinalWithPolishForDecl) { + // clangd relies on the 'final' keyword being printed when + // PolishForDeclaration is enabled, so make sure it is even if implicit attrs + // are disabled. + ASSERT_TRUE(PrintedDeclCXX11Matches( + "template\n" + "class FinalTemplate final {};", + classTemplateDecl(hasName("FinalTemplate")).bind("id"), + "template class FinalTemplate final {}", + [](PrintingPolicy &Policy) { Policy.PolishForDeclaration = true; })); +} ``` https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
vgvassilev wrote: IIUC, the PolishForDeclaration option is supposed to `When true, do certain refinement needed for producing proper declaration tag; such as, do not print attributes attached to the declaration. `. If the intent is to produce a forward declaration the `final` keyword cannot be attached to a forward declaration. So I am not sure what's the "right" fix here... https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][modules] Headers meant to be included multiple times can be completely invisible in clang module builds (PR #83660)
jyknight wrote: To get back to my previous point about the semantics implemented by this patch being unfortunate -- the upshot is that, now: ``` #include #define NDEBUG #import ``` will include assert.h twice (even though the latter is an "import") _only_ if modules are enabled. If modules are disabled, import keeps the original behavior of suppressing multiple inclusion. This doesn't make sense: with modules disabled, everything is textual -- to say that "textual header" in a modulemap should make a header somehow "more" textual than the default non-modular behavior is weird. That is what I meant by my previous comment that this change has tied together features which should not be related -- and that's the main reason why I believe this PR should be reverted. If we _do_ need to implement a behavior of suppressing `#import`'s include-once behavior for certain headers, it should be based on something within the header being included. E.g. could create a new`#pragma multiply_include_even_with_import` and add it to assert.h -- this would be effectively the reverse of `#pragma once`. I do not believe it's really needed (once the "header is hidden entirely" bug is fixed), but it would be consistent and not produce broken/surprising semantics. https://github.com/llvm/llvm-project/pull/83660 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/88600 >From c68344d2d2f22f88ef386f655cc7698759fb551c Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 13 Apr 2024 06:39:34 + Subject: [PATCH] Fix the double space and double attribute printing of the final keyword. Fixes #56517. --- clang/lib/AST/DeclPrinter.cpp | 36 +++- clang/test/SemaCXX/cxx11-attr-print.cpp | 5 +++ clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl | 4 +-- clang/unittests/AST/DeclPrinterTest.cpp | 37 - clang/utils/TableGen/ClangAttrEmitter.cpp | 2 +- 5 files changed, 57 insertions(+), 27 deletions(-) diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp index 6afdb6cfccb142..5d15541a6d54c5 100644 --- a/clang/lib/AST/DeclPrinter.cpp +++ b/clang/lib/AST/DeclPrinter.cpp @@ -119,7 +119,7 @@ namespace { void printTemplateArguments(llvm::ArrayRef Args, const TemplateParameterList *Params); enum class AttrPosAsWritten { Default = 0, Left, Right }; -void +bool prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos = AttrPosAsWritten::Default); void prettyPrintPragmas(Decl *D); @@ -252,16 +252,19 @@ static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, return DeclPrinter::AttrPosAsWritten::Right; } -void DeclPrinter::prettyPrintAttributes(const Decl *D, +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos /*=Default*/) { - if (Policy.PolishForDeclaration) -return; + bool hasPrinted = false; if (D->hasAttrs()) { const AttrVec &Attrs = D->getAttrs(); for (auto *A : Attrs) { if (A->isInherited() || A->isImplicit()) continue; + if (Policy.PolishForDeclaration && + A->getSyntax() != AttributeCommonInfo::AS_Keyword) +continue; switch (A->getKind()) { #define ATTR(X) #define PRAGMA_SPELLING_ATTR(X) case attr::X: @@ -275,6 +278,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, if (Pos != AttrPosAsWritten::Left) Out << ' '; A->printPretty(Out, Policy); + hasPrinted = true; if (Pos == AttrPosAsWritten::Left) Out << ' '; } @@ -282,6 +286,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, } } } + return hasPrinted; } void DeclPrinter::prettyPrintPragmas(Decl *D) { @@ -1060,12 +1065,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { // FIXME: add printing of pragma attributes if required. if (!Policy.SuppressSpecifiers && D->isModulePrivate()) Out << "__module_private__ "; - Out << D->getKindName(); - prettyPrintAttributes(D); + Out << D->getKindName() << ' '; - if (D->getIdentifier()) { + // FIXME: Move before printing the decl kind to match the behavior of the + // attribute printing for variables and function where they are printed first. + if (prettyPrintAttributes(D, AttrPosAsWritten::Left)) Out << ' '; + + if (D->getIdentifier()) { if (auto *NNS = D->getQualifier()) NNS->print(Out, Policy); Out << *D; @@ -1082,16 +1090,13 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { } } - if (D->hasDefinition()) { -if (D->hasAttr()) { - Out << " final"; -} - } + prettyPrintAttributes(D, AttrPosAsWritten::Right); if (D->isCompleteDefinition()) { +Out << ' '; // Print the base classes if (D->getNumBases()) { - Out << " : "; + Out << ": "; for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { if (Base != D->bases_begin()) @@ -1110,14 +1115,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { if (Base->isPackExpansion()) Out << "..."; } + Out << ' '; } // Print the class definition // FIXME: Doesn't print access specifiers, e.g., "public:" if (Policy.TerseOutput) { - Out << " {}"; + Out << "{}"; } else { - Out << " {\n"; + Out << "{\n"; VisitDeclContext(D); Indent() << "}"; } diff --git a/clang/test/SemaCXX/cxx11-attr-print.cpp b/clang/test/SemaCXX/cxx11-attr-print.cpp index a169d1b4409b4d..2b084018bc0662 100644 --- a/clang/test/SemaCXX/cxx11-attr-print.cpp +++ b/clang/test/SemaCXX/cxx11-attr-print.cpp @@ -87,3 +87,8 @@ template struct S; // CHECK: using Small2 {{\[}}[gnu::mode(byte)]] = int; using Small2 [[gnu::mode(byte)]] = int; + +class FinalNonTemplate final {}; +// CHECK: class FinalNonTemplate final { +template class FinalTemplate final {}; +// CHECK: template class FinalTemplate final { diff --git a/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl b/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl index 7e79ae3bf0
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
vgvassilev wrote: I've put a fix that fixes the cases that you mentioned... https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/88600 >From cb3da95dd80c5ed991c5342e655e0f170eab16eb Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 13 Apr 2024 06:39:34 + Subject: [PATCH] Fix the double space and double attribute printing of the final keyword. Fixes #56517. --- clang/lib/AST/DeclPrinter.cpp | 36 +++- clang/test/SemaCXX/cxx11-attr-print.cpp | 5 +++ clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl | 4 +-- clang/unittests/AST/DeclPrinterTest.cpp | 37 - clang/utils/TableGen/ClangAttrEmitter.cpp | 2 +- 5 files changed, 57 insertions(+), 27 deletions(-) diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp index 6afdb6cfccb142..f5ae5d5b36449a 100644 --- a/clang/lib/AST/DeclPrinter.cpp +++ b/clang/lib/AST/DeclPrinter.cpp @@ -119,7 +119,7 @@ namespace { void printTemplateArguments(llvm::ArrayRef Args, const TemplateParameterList *Params); enum class AttrPosAsWritten { Default = 0, Left, Right }; -void +bool prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos = AttrPosAsWritten::Default); void prettyPrintPragmas(Decl *D); @@ -252,16 +252,19 @@ static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, return DeclPrinter::AttrPosAsWritten::Right; } -void DeclPrinter::prettyPrintAttributes(const Decl *D, +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos /*=Default*/) { - if (Policy.PolishForDeclaration) -return; + bool hasPrinted = false; if (D->hasAttrs()) { const AttrVec &Attrs = D->getAttrs(); for (auto *A : Attrs) { if (A->isInherited() || A->isImplicit()) continue; + // Don't strip out the keyword attributes, they aren't regular attributes. + if (Policy.PolishForDeclaration && A->isKeywordAttribute()) +continue; switch (A->getKind()) { #define ATTR(X) #define PRAGMA_SPELLING_ATTR(X) case attr::X: @@ -275,6 +278,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, if (Pos != AttrPosAsWritten::Left) Out << ' '; A->printPretty(Out, Policy); + hasPrinted = true; if (Pos == AttrPosAsWritten::Left) Out << ' '; } @@ -282,6 +286,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, } } } + return hasPrinted; } void DeclPrinter::prettyPrintPragmas(Decl *D) { @@ -1060,12 +1065,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { // FIXME: add printing of pragma attributes if required. if (!Policy.SuppressSpecifiers && D->isModulePrivate()) Out << "__module_private__ "; - Out << D->getKindName(); - prettyPrintAttributes(D); + Out << D->getKindName() << ' '; - if (D->getIdentifier()) { + // FIXME: Move before printing the decl kind to match the behavior of the + // attribute printing for variables and function where they are printed first. + if (prettyPrintAttributes(D, AttrPosAsWritten::Left)) Out << ' '; + + if (D->getIdentifier()) { if (auto *NNS = D->getQualifier()) NNS->print(Out, Policy); Out << *D; @@ -1082,16 +1090,13 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { } } - if (D->hasDefinition()) { -if (D->hasAttr()) { - Out << " final"; -} - } + prettyPrintAttributes(D, AttrPosAsWritten::Right); if (D->isCompleteDefinition()) { +Out << ' '; // Print the base classes if (D->getNumBases()) { - Out << " : "; + Out << ": "; for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { if (Base != D->bases_begin()) @@ -1110,14 +1115,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { if (Base->isPackExpansion()) Out << "..."; } + Out << ' '; } // Print the class definition // FIXME: Doesn't print access specifiers, e.g., "public:" if (Policy.TerseOutput) { - Out << " {}"; + Out << "{}"; } else { - Out << " {\n"; + Out << "{\n"; VisitDeclContext(D); Indent() << "}"; } diff --git a/clang/test/SemaCXX/cxx11-attr-print.cpp b/clang/test/SemaCXX/cxx11-attr-print.cpp index a169d1b4409b4d..2b084018bc0662 100644 --- a/clang/test/SemaCXX/cxx11-attr-print.cpp +++ b/clang/test/SemaCXX/cxx11-attr-print.cpp @@ -87,3 +87,8 @@ template struct S; // CHECK: using Small2 {{\[}}[gnu::mode(byte)]] = int; using Small2 [[gnu::mode(byte)]] = int; + +class FinalNonTemplate final {}; +// CHECK: class FinalNonTemplate final { +template class FinalTemplate final {}; +// CHECK: template class FinalTemplate final { diff --git a/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl b/clang/test/Sem
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/88600 >From 9b2bb9068cbefcfffd0931fbbee46b1a0f536a4f Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 13 Apr 2024 06:39:34 + Subject: [PATCH] Fix the double space and double attribute printing of the final keyword. Fixes #56517. --- clang/lib/AST/DeclPrinter.cpp | 36 +++- clang/test/SemaCXX/cxx11-attr-print.cpp | 5 +++ clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl | 4 +-- clang/unittests/AST/DeclPrinterTest.cpp | 37 - clang/utils/TableGen/ClangAttrEmitter.cpp | 2 +- 5 files changed, 57 insertions(+), 27 deletions(-) diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp index 6afdb6cfccb142..444780947f2075 100644 --- a/clang/lib/AST/DeclPrinter.cpp +++ b/clang/lib/AST/DeclPrinter.cpp @@ -119,7 +119,7 @@ namespace { void printTemplateArguments(llvm::ArrayRef Args, const TemplateParameterList *Params); enum class AttrPosAsWritten { Default = 0, Left, Right }; -void +bool prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos = AttrPosAsWritten::Default); void prettyPrintPragmas(Decl *D); @@ -252,16 +252,19 @@ static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, return DeclPrinter::AttrPosAsWritten::Right; } -void DeclPrinter::prettyPrintAttributes(const Decl *D, +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos /*=Default*/) { - if (Policy.PolishForDeclaration) -return; + bool hasPrinted = false; if (D->hasAttrs()) { const AttrVec &Attrs = D->getAttrs(); for (auto *A : Attrs) { if (A->isInherited() || A->isImplicit()) continue; + // Don't strip out the keyword attributes, they aren't regular attributes. + if (Policy.PolishForDeclaration && !A->isKeywordAttribute()) +continue; switch (A->getKind()) { #define ATTR(X) #define PRAGMA_SPELLING_ATTR(X) case attr::X: @@ -275,6 +278,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, if (Pos != AttrPosAsWritten::Left) Out << ' '; A->printPretty(Out, Policy); + hasPrinted = true; if (Pos == AttrPosAsWritten::Left) Out << ' '; } @@ -282,6 +286,7 @@ void DeclPrinter::prettyPrintAttributes(const Decl *D, } } } + return hasPrinted; } void DeclPrinter::prettyPrintPragmas(Decl *D) { @@ -1060,12 +1065,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { // FIXME: add printing of pragma attributes if required. if (!Policy.SuppressSpecifiers && D->isModulePrivate()) Out << "__module_private__ "; - Out << D->getKindName(); - prettyPrintAttributes(D); + Out << D->getKindName() << ' '; - if (D->getIdentifier()) { + // FIXME: Move before printing the decl kind to match the behavior of the + // attribute printing for variables and function where they are printed first. + if (prettyPrintAttributes(D, AttrPosAsWritten::Left)) Out << ' '; + + if (D->getIdentifier()) { if (auto *NNS = D->getQualifier()) NNS->print(Out, Policy); Out << *D; @@ -1082,16 +1090,13 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { } } - if (D->hasDefinition()) { -if (D->hasAttr()) { - Out << " final"; -} - } + prettyPrintAttributes(D, AttrPosAsWritten::Right); if (D->isCompleteDefinition()) { +Out << ' '; // Print the base classes if (D->getNumBases()) { - Out << " : "; + Out << ": "; for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { if (Base != D->bases_begin()) @@ -1110,14 +1115,15 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { if (Base->isPackExpansion()) Out << "..."; } + Out << ' '; } // Print the class definition // FIXME: Doesn't print access specifiers, e.g., "public:" if (Policy.TerseOutput) { - Out << " {}"; + Out << "{}"; } else { - Out << " {\n"; + Out << "{\n"; VisitDeclContext(D); Indent() << "}"; } diff --git a/clang/test/SemaCXX/cxx11-attr-print.cpp b/clang/test/SemaCXX/cxx11-attr-print.cpp index a169d1b4409b4d..2b084018bc0662 100644 --- a/clang/test/SemaCXX/cxx11-attr-print.cpp +++ b/clang/test/SemaCXX/cxx11-attr-print.cpp @@ -87,3 +87,8 @@ template struct S; // CHECK: using Small2 {{\[}}[gnu::mode(byte)]] = int; using Small2 [[gnu::mode(byte)]] = int; + +class FinalNonTemplate final {}; +// CHECK: class FinalNonTemplate final { +template class FinalTemplate final {}; +// CHECK: template class FinalTemplate final { diff --git a/clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl b/clang/test/Se
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: > If the intent is to produce a forward declaration the final keyword cannot be > attached to a forward declaration. So I am not sure what's the "right" fix > here... I don't believe that's the intent of `DeclPrinter` or `PolishForDeclaration` -- * Clangd uses `PolishForDeclaration` to print an informational "hover text" for the declaration (and I guess that's why they want to include `final` -- it's something that's good for an interactive user to know about the decl) * IWYU uses `PolishForDeclaration` to get a valid _declaration_, and then does [some very hacky heuristic post-processing](https://github.com/include-what-you-use/include-what-you-use/blob/125341c412ceee9233ece8973848b49e770a9b82/iwyu_output.cc#L469) to turn it into a forward-decl. Sorry for stirring confusion into this, my primary focus is IWYU, but I remember that the original double-final came from a change intended for Clangd. Hopefully this helps clarify. https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
@@ -252,16 +252,19 @@ static DeclPrinter::AttrPosAsWritten getPosAsWritten(const Attr *A, return DeclPrinter::AttrPosAsWritten::Right; } -void DeclPrinter::prettyPrintAttributes(const Decl *D, +// returns true if an attribute was printed. +bool DeclPrinter::prettyPrintAttributes(const Decl *D, AttrPosAsWritten Pos /*=Default*/) { - if (Policy.PolishForDeclaration) -return; + bool hasPrinted = false; if (D->hasAttrs()) { const AttrVec &Attrs = D->getAttrs(); for (auto *A : Attrs) { if (A->isInherited() || A->isImplicit()) continue; + // Don't strip out the keyword attributes, they aren't regular attributes. + if (Policy.PolishForDeclaration && !A->isKeywordAttribute()) kimgr wrote: Nice, I was about to suggest something like this, but didn't know `isKeywordAttribute` existed. https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
vgvassilev wrote: > * IWYU uses `PolishForDeclaration` to get a valid _declaration_, and then > does [some very hacky heuristic > post-processing](https://github.com/include-what-you-use/include-what-you-use/blob/125341c412ceee9233ece8973848b49e770a9b82/iwyu_output.cc#L469) > to turn it into a forward-decl. The [ROOT](http://root.cern) usecase of the Cling interpreter has similar infrastructure and it works at scale couple of million lines of scientific codes: https://github.com/root-project/root/blob/master/interpreter/cling/lib/Interpreter/ForwardDeclPrinter.cpp. There are some tests that one can look at: https://github.com/root-project/root/tree/master/interpreter/cling/test/Autoloading I am wondering if that'd be interesting and if so, maybe we can share it between both projects via upstreaming to Clang... https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: Current PR passes all my tests, both Clang (`ninja ASTTests`), Clangd (`ninja ClangdTests`) and IWYU end-to-end tests -- thanks! https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Update FormatTest.cpp (PR #88628)
https://github.com/edwardbottom created https://github.com/llvm/llvm-project/pull/88628 None >From 22ae52878602dfc79ab90bbc6e9dea508c3762e2 Mon Sep 17 00:00:00 2001 From: Edward Bottom <31777866+edwardbot...@users.noreply.github.com> Date: Sat, 13 Apr 2024 08:49:47 -0700 Subject: [PATCH] Update FormatTest.cpp --- clang/unittests/Format/FormatTest.cpp | 8 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 4906b3350b5b22..91dfa5a4b61d7f 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -5434,7 +5434,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { "C();\n" "#endif", style); - verifyFormat("if (emacs) {\n" + verifyFormat("if (vim) {\n" "#ifdef is\n" "#define lit \\\n" "if (af) { \\\n" @@ -5457,7 +5457,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style); verifyFormat("#ifndef foo\n" "#define foo\n" - "if (emacs) {\n" + "if (vim) {\n" "#ifdef is\n" "#define lit \\\n" "if (af) { \\\n" @@ -5543,7 +5543,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style); verifyFormat("#ifndef foo\n" "#define foo\n" - "if (emacs) {\n" + "if (vim) {\n" "#ifdef is\n" "# define lit \\\n" " if (af) { \\\n" @@ -5583,7 +5583,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style.IndentWidth = 4; style.PPIndentWidth = 1; style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; - verifyFormat("if (emacs) {\n" + verifyFormat("if (vim) {\n" "#ifdef is\n" " #define lit \\\n" " if (af) { \\\n" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Update FormatTest.cpp (PR #88628)
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/88628 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Update FormatTest.cpp (PR #88628)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Edward Bottom (edwardbottom) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/88628.diff 1 Files Affected: - (modified) clang/unittests/Format/FormatTest.cpp (+4-4) ``diff diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 4906b3350b5b22..91dfa5a4b61d7f 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -5434,7 +5434,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { "C();\n" "#endif", style); - verifyFormat("if (emacs) {\n" + verifyFormat("if (vim) {\n" "#ifdef is\n" "#define lit \\\n" "if (af) { \\\n" @@ -5457,7 +5457,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style); verifyFormat("#ifndef foo\n" "#define foo\n" - "if (emacs) {\n" + "if (vim) {\n" "#ifdef is\n" "#define lit \\\n" "if (af) { \\\n" @@ -5543,7 +5543,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style); verifyFormat("#ifndef foo\n" "#define foo\n" - "if (emacs) {\n" + "if (vim) {\n" "#ifdef is\n" "# define lit \\\n" " if (af) { \\\n" @@ -5583,7 +5583,7 @@ TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { style.IndentWidth = 4; style.PPIndentWidth = 1; style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; - verifyFormat("if (emacs) {\n" + verifyFormat("if (vim) {\n" "#ifdef is\n" " #define lit \\\n" " if (af) { \\\n" `` https://github.com/llvm/llvm-project/pull/88628 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang Format] Fixing erroneous statements in tests; nsc (PR #88628)
https://github.com/edwardbottom edited https://github.com/llvm/llvm-project/pull/88628 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix the double space and double attribute printing of the final keyword. (PR #88600)
kimgr wrote: > I am wondering if that'd be interesting and if so, maybe we can share it > between both projects via upstreaming to Clang... That sounds fantastic, but mostly because I don't have anything to offer, and everything to benefit :) I was just thinking about adding a `.ForwardDeclaration` policy to `DeclPrinter` this morning -- the current `PolishForDeclaration` output is _so_ close. But it seemed weird to add a mode for which IWYU (a non-LLVM project) was the only user. I suspect your `ForwardDeclarePrinter` is more principled. I guess it might be hard to coordinate forward-decl style between users, but ultimately that's just printing policy (or chaining libFormat, or something). Let's maybe continue this discussion somewhere else? https://github.com/llvm/llvm-project/pull/88600 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Reduce the size of Decl and classes derived from it (PR #87361)
https://github.com/philnik777 updated https://github.com/llvm/llvm-project/pull/87361 >From b8a626116b0719c1acf75e9e7300df8e2bf82f99 Mon Sep 17 00:00:00 2001 From: Nikolas Klauser Date: Tue, 2 Apr 2024 18:00:05 +0200 Subject: [PATCH 1/3] [Clang] Reduce the size of Decl and classes derived from it --- clang/include/clang/AST/DeclBase.h| 66 ++- clang/lib/AST/DeclBase.cpp| 29 ++ clang/lib/Serialization/ASTReaderDecl.cpp | 2 +- 3 files changed, 62 insertions(+), 35 deletions(-) diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h index 47ed6d0d1db0df..172bd581b527c8 100644 --- a/clang/include/clang/AST/DeclBase.h +++ b/clang/include/clang/AST/DeclBase.h @@ -268,17 +268,34 @@ class alignas(8) Decl { /// } /// void A::f(); // SemanticDC == namespace 'A' ///// LexicalDC == global namespace - llvm::PointerUnion DeclCtx; + llvm::PointerIntPair< + llvm::PointerIntPair, 1, + bool>, + 1, bool> + DeclCtxWithInvalidDeclAndHasAttrs; - bool isInSemaDC() const { return DeclCtx.is(); } - bool isOutOfSemaDC() const { return DeclCtx.is(); } + bool isInSemaDC() const { +return DeclCtxWithInvalidDeclAndHasAttrs.getPointer() +.getPointer() +.is(); + } + + bool isOutOfSemaDC() const { +return DeclCtxWithInvalidDeclAndHasAttrs.getPointer() +.getPointer() +.is(); + } MultipleDC *getMultipleDC() const { -return DeclCtx.get(); +return DeclCtxWithInvalidDeclAndHasAttrs.getPointer() +.getPointer() +.get(); } DeclContext *getSemanticDC() const { -return DeclCtx.get(); +return DeclCtxWithInvalidDeclAndHasAttrs.getPointer() +.getPointer() +.get(); } /// Loc - The location of this decl. @@ -288,14 +305,6 @@ class alignas(8) Decl { LLVM_PREFERRED_TYPE(Kind) unsigned DeclKind : 7; - /// InvalidDecl - This indicates a semantic error occurred. - LLVM_PREFERRED_TYPE(bool) - unsigned InvalidDecl : 1; - - /// HasAttrs - This indicates whether the decl has attributes or not. - LLVM_PREFERRED_TYPE(bool) - unsigned HasAttrs : 1; - /// Implicit - Whether this declaration was implicitly generated by /// the implementation rather than explicitly written by the user. LLVM_PREFERRED_TYPE(bool) @@ -393,21 +402,22 @@ class alignas(8) Decl { protected: Decl(Kind DK, DeclContext *DC, SourceLocation L) : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)), -DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false), -Implicit(false), Used(false), Referenced(false), +DeclCtxWithInvalidDeclAndHasAttrs({DC, false}, false), Loc(L), +DeclKind(DK), Implicit(false), Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), IdentifierNamespace(getIdentifierNamespaceForKind(DK)), CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) { -if (StatisticsEnabled) add(DK); +if (StatisticsEnabled) + add(DK); } Decl(Kind DK, EmptyShell Empty) - : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false), -Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), -Access(AS_none), FromASTFile(0), + : DeclKind(DK), Implicit(false), Used(false), Referenced(false), +TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), IdentifierNamespace(getIdentifierNamespaceForKind(DK)), CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) { -if (StatisticsEnabled) add(DK); +if (StatisticsEnabled) + add(DK); } virtual ~Decl(); @@ -520,7 +530,7 @@ class alignas(8) Decl { return AccessSpecifier(Access); } - bool hasAttrs() const { return HasAttrs; } + bool hasAttrs() const { return DeclCtxWithInvalidDeclAndHasAttrs.getPointer().getInt(); } void setAttrs(const AttrVec& Attrs) { return setAttrsImpl(Attrs, getASTContext()); @@ -549,13 +559,16 @@ class alignas(8) Decl { } template void dropAttrs() { -if (!HasAttrs) return; +if (!hasAttrs()) return; AttrVec &Vec = getAttrs(); llvm::erase_if(Vec, [](Attr *A) { return isa(A); }); -if (Vec.empty()) - HasAttrs = false; +if (Vec.empty()) { + auto InnerPtr = DeclCtxWithInvalidDeclAndHasAttrs.getPointer(); + InnerPtr.setInt(false); + DeclCtxWithInvalidDeclAndHasAttrs.setPointer(InnerPtr); +} } template void dropAttr() { dropAttrs(); } @@ -590,7 +603,10 @@ class alignas(8) Decl { /// setInvalidDecl - Indicates the Decl had a semantic error. This /// allows for graceful error recovery. void setInvalidDecl(bool Invalid = true); - bool isInvalidDecl() const { return (bool) InvalidDecl; } + + bool isInvalidDecl() const { +return DeclCtxWithInvalidDeclAndHasAttrs.getInt(); +
[clang] [clang-scan-deps] Fix contention when updating `TrackingStatistic`s in hot code paths in `FileManager`. (PR #88427)
aganea wrote: I think in the short term @jansvoboda11's suggestion should be good enough. Bit if we want `Statistics` to be always cheap, we should make them `thread_local` instead, not atomic. `getValue()` could do the "collection" of data over all active, or past threads. It would also need a mechanism for collecting data when a thread ends through `pthread_key_create/FlsCallback`s. It would be a bit more involved than what's there currently, but that should fix the issue I'm seeing (and maybe others). https://github.com/llvm/llvm-project/pull/88427 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Support wasm execution (PR #86402)
https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/86402 >From 4434ceeef152b95998ebd0a3b09a56d105490c4d Mon Sep 17 00:00:00 2001 From: Anubhab Ghosh Date: Sat, 23 Mar 2024 15:13:57 + Subject: [PATCH 1/2] [clang-repl] Support wasm execution. This commit introduces support for running clang-repl and executing C++ code interactively inside a Javascript engine using WebAssembly when built with Emscripten. This is achieved by producing WASM "shared libraries" that can be loaded by the Emscripten runtime using dlopen() More discussion is available in https://reviews.llvm.org/D158140 --- clang/lib/Interpreter/CMakeLists.txt | 1 + clang/lib/Interpreter/IncrementalExecutor.cpp | 2 + clang/lib/Interpreter/IncrementalExecutor.h | 11 +- clang/lib/Interpreter/Interpreter.cpp | 11 ++ clang/lib/Interpreter/WASM.cpp| 107 ++ clang/lib/Interpreter/WASM.h | 33 ++ 6 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 clang/lib/Interpreter/WASM.cpp create mode 100644 clang/lib/Interpreter/WASM.h diff --git a/clang/lib/Interpreter/CMakeLists.txt b/clang/lib/Interpreter/CMakeLists.txt index 9065f998f73c47..a8a287edf5b049 100644 --- a/clang/lib/Interpreter/CMakeLists.txt +++ b/clang/lib/Interpreter/CMakeLists.txt @@ -20,6 +20,7 @@ add_clang_library(clangInterpreter Interpreter.cpp InterpreterUtils.cpp Value.cpp + WASM.cpp DEPENDS intrinsics_gen diff --git a/clang/lib/Interpreter/IncrementalExecutor.cpp b/clang/lib/Interpreter/IncrementalExecutor.cpp index 6f036107c14a9c..1824a5b4570a93 100644 --- a/clang/lib/Interpreter/IncrementalExecutor.cpp +++ b/clang/lib/Interpreter/IncrementalExecutor.cpp @@ -36,6 +36,8 @@ LLVM_ATTRIBUTE_USED void linkComponents() { } namespace clang { +IncrementalExecutor::IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC) +: TSCtx(TSC) {} llvm::Expected> IncrementalExecutor::createDefaultJITBuilder( diff --git a/clang/lib/Interpreter/IncrementalExecutor.h b/clang/lib/Interpreter/IncrementalExecutor.h index b4347209e14fe3..7954cde36588bd 100644 --- a/clang/lib/Interpreter/IncrementalExecutor.h +++ b/clang/lib/Interpreter/IncrementalExecutor.h @@ -43,16 +43,19 @@ class IncrementalExecutor { llvm::DenseMap ResourceTrackers; +protected: + IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC); + public: enum SymbolNameKind { IRName, LinkerName }; IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC, llvm::orc::LLJITBuilder &JITBuilder, llvm::Error &Err); - ~IncrementalExecutor(); + virtual ~IncrementalExecutor(); - llvm::Error addModule(PartialTranslationUnit &PTU); - llvm::Error removeModule(PartialTranslationUnit &PTU); - llvm::Error runCtors() const; + virtual llvm::Error addModule(PartialTranslationUnit &PTU); + virtual llvm::Error removeModule(PartialTranslationUnit &PTU); + virtual llvm::Error runCtors() const; llvm::Error cleanUp(); llvm::Expected getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const; diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index cf31456b6950ac..7d572b20cd8281 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -15,6 +15,7 @@ #include "IncrementalExecutor.h" #include "IncrementalParser.h" #include "InterpreterUtils.h" +#include "WASM.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Mangle.h" @@ -183,6 +184,12 @@ IncrementalCompilerBuilder::CreateCpp() { std::vector Argv; Argv.reserve(5 + 1 + UserArgs.size()); Argv.push_back("-xc++"); +#ifdef __EMSCRIPTEN__ + Argv.push_back("-target"); + Argv.push_back("wasm32-unknown-emscripten"); + Argv.push_back("-pie"); + Argv.push_back("-shared"); +#endif Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); @@ -400,7 +407,11 @@ llvm::Error Interpreter::CreateExecutor() { if (!JB) return JB.takeError(); llvm::Error Err = llvm::Error::success(); +#ifdef __EMSCRIPTEN__ + auto Executor = std::make_unique(*TSCtx, **JB, Err); +#else auto Executor = std::make_unique(*TSCtx, **JB, Err); +#endif if (!Err) IncrExecutor = std::move(Executor); diff --git a/clang/lib/Interpreter/WASM.cpp b/clang/lib/Interpreter/WASM.cpp new file mode 100644 index 00..d21d0ada1eafac --- /dev/null +++ b/clang/lib/Interpreter/WASM.cpp @@ -0,0 +1,107 @@ +//===- WASM.cpp - WASM Interpreter --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// +// +// This file implements interpreter support
[clang] [analyzer] Harden security.cert.env.InvalidPtr checker fn matching (PR #88536)
https://github.com/steakhal updated https://github.com/llvm/llvm-project/pull/88536 >From 915ab37028067fb38ffa69ae5c9726bb8c971436 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Fri, 12 Apr 2024 19:07:49 +0200 Subject: [PATCH 1/2] [analyzer] Harden security.cert.env.InvalidPtr checker fn matching Fixes #88181 I'm also hardening an llvm::cast along the way. --- .../Checkers/cert/InvalidPtrChecker.cpp | 31 --- clang/test/Analysis/invalid-ptr-checker.cpp | 10 ++ 2 files changed, 30 insertions(+), 11 deletions(-) create mode 100644 clang/test/Analysis/invalid-ptr-checker.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp index e5dd907c660d8e..fefe846b6911f7 100644 --- a/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/cert/InvalidPtrChecker.cpp @@ -48,14 +48,19 @@ class InvalidPtrChecker bool InvalidatingGetEnv = false; // GetEnv can be treated invalidating and non-invalidating as well. - const CallDescription GetEnvCall{{"getenv"}, 1}; + const CallDescription GetEnvCall{CDM::CLibrary, {"getenv"}, 1}; const CallDescriptionMap EnvpInvalidatingFunctions = { - {{{"setenv"}, 3}, &InvalidPtrChecker::EnvpInvalidatingCall}, - {{{"unsetenv"}, 1}, &InvalidPtrChecker::EnvpInvalidatingCall}, - {{{"putenv"}, 1}, &InvalidPtrChecker::EnvpInvalidatingCall}, - {{{"_putenv_s"}, 2}, &InvalidPtrChecker::EnvpInvalidatingCall}, - {{{"_wputenv_s"}, 2}, &InvalidPtrChecker::EnvpInvalidatingCall}, + {{CDM::CLibrary, {"setenv"}, 3}, + &InvalidPtrChecker::EnvpInvalidatingCall}, + {{CDM::CLibrary, {"unsetenv"}, 1}, + &InvalidPtrChecker::EnvpInvalidatingCall}, + {{CDM::CLibrary, {"putenv"}, 1}, + &InvalidPtrChecker::EnvpInvalidatingCall}, + {{CDM::CLibrary, {"_putenv_s"}, 2}, + &InvalidPtrChecker::EnvpInvalidatingCall}, + {{CDM::CLibrary, {"_wputenv_s"}, 2}, + &InvalidPtrChecker::EnvpInvalidatingCall}, }; void postPreviousReturnInvalidatingCall(const CallEvent &Call, @@ -63,13 +68,13 @@ class InvalidPtrChecker // SEI CERT ENV34-C const CallDescriptionMap PreviousCallInvalidatingFunctions = { - {{{"setlocale"}, 2}, + {{CDM::CLibrary, {"setlocale"}, 2}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall}, - {{{"strerror"}, 1}, + {{CDM::CLibrary, {"strerror"}, 1}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall}, - {{{"localeconv"}, 0}, + {{CDM::CLibrary, {"localeconv"}, 0}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall}, - {{{"asctime"}, 1}, + {{CDM::CLibrary, {"asctime"}, 1}, &InvalidPtrChecker::postPreviousReturnInvalidatingCall}, }; @@ -205,8 +210,12 @@ void InvalidPtrChecker::postPreviousReturnInvalidatingCall( CE, LCtx, CE->getType(), C.blockCount()); State = State->BindExpr(CE, LCtx, RetVal); + const auto *SymRegOfRetVal = + dyn_cast_or_null(RetVal.getAsRegion()); + if (!SymRegOfRetVal) +return; + // Remember to this region. - const auto *SymRegOfRetVal = cast(RetVal.getAsRegion()); const MemRegion *MR = SymRegOfRetVal->getBaseRegion(); State = State->set(FD, MR); diff --git a/clang/test/Analysis/invalid-ptr-checker.cpp b/clang/test/Analysis/invalid-ptr-checker.cpp new file mode 100644 index 00..58bb45e0fb8421 --- /dev/null +++ b/clang/test/Analysis/invalid-ptr-checker.cpp @@ -0,0 +1,10 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=core,security.cert.env.InvalidPtr -verify %s + +// expected-no-diagnostics + +namespace other { +int strerror(int errnum); // custom strerror +void no_crash_on_custom_strerror() { + (void)strerror(0); // no-crash +} +} // namespace other >From 06d0056efd9616f76680ec7d923ed2bc76f2ab25 Mon Sep 17 00:00:00 2001 From: Balazs Benics Date: Sat, 13 Apr 2024 20:44:47 +0200 Subject: [PATCH 2/2] [docs] Add release notes for the crash fix --- clang/docs/ReleaseNotes.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 232de0d7d8bb73..7cb550cef62e64 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -600,6 +600,8 @@ Static Analyzer but not under any case blocks if ``unroll-loops=true`` analyzer config is set. (#GH68819) - Support C++23 static operator calls. (#GH84972) +- Fixed a crash in ``security.cert.env.InvalidPtr`` checker when accidentally + matched user-defined ``strerror`` and similar library functions. (GH#88181) New features ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
https://github.com/chrisnc created https://github.com/llvm/llvm-project/pull/88631 None >From 40d774ab8c598f0dfb76dcd087f1af17c7fdd01d Mon Sep 17 00:00:00 2001 From: Chris Copeland Date: Fri, 12 Apr 2024 23:42:32 -0700 Subject: [PATCH] [clang][docs] fix whitespace in AttrDocs.td --- clang/include/clang/Basic/AttrDocs.td | 32 +-- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td index 8687c4f57d3f83..a0bbe5861c5722 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -1604,39 +1604,39 @@ specifies availability for the current target platform, the availability attributes are ignored. Supported platforms are: ``ios`` - Apple's iOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-ios*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=ios*version*`` + Apple's iOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-ios*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=ios*version*`` command-line argument. ``macos`` - Apple's macOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-macos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=macos*version*`` - command-line argument. ``macosx`` is supported for + Apple's macOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-macos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=macos*version*`` + command-line argument. ``macosx`` is supported for backward-compatibility reasons, but it is deprecated. ``tvos`` - Apple's tvOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-tvos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` + Apple's tvOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-tvos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` command-line argument. ``watchos`` Apple's watchOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-watchos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` + as part of the ``-target *arch*-apple-watchos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` command-line argument. ``visionos`` Apple's visionOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-visionos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` + as part of the ``-target *arch*-apple-visionos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` command-line argument. ``driverkit`` Apple's DriverKit userspace kernel extensions. The minimum deployment target - is specified as part of the ``-target *arch*-apple-driverkit*version*`` + is specified as part of the ``-target *arch*-apple-driverkit*version*`` command line argument. A declaration can typically be used even when deploying back to a platform @@ -7522,7 +7522,7 @@ means that it can e.g no longer be part of an initializer expression. /* This may print something else than "6 * 7 = 42", if there is a non-weak definition of "ANSWER" in -an object linked in */ + an object linked in */ printf("6 * 7 = %d\n", ANSWER); return 0; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
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/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Chris Copeland (chrisnc) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/88631.diff 1 Files Affected: - (modified) clang/include/clang/Basic/AttrDocs.td (+16-16) ``diff diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td index 8687c4f57d3f83..a0bbe5861c5722 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -1604,39 +1604,39 @@ specifies availability for the current target platform, the availability attributes are ignored. Supported platforms are: ``ios`` - Apple's iOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-ios*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=ios*version*`` + Apple's iOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-ios*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=ios*version*`` command-line argument. ``macos`` - Apple's macOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-macos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=macos*version*`` - command-line argument. ``macosx`` is supported for + Apple's macOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-macos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=macos*version*`` + command-line argument. ``macosx`` is supported for backward-compatibility reasons, but it is deprecated. ``tvos`` - Apple's tvOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-tvos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` + Apple's tvOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-tvos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` command-line argument. ``watchos`` Apple's watchOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-watchos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` + as part of the ``-target *arch*-apple-watchos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` command-line argument. ``visionos`` Apple's visionOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-visionos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` + as part of the ``-target *arch*-apple-visionos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` command-line argument. ``driverkit`` Apple's DriverKit userspace kernel extensions. The minimum deployment target - is specified as part of the ``-target *arch*-apple-driverkit*version*`` + is specified as part of the ``-target *arch*-apple-driverkit*version*`` command line argument. A declaration can typically be used even when deploying back to a platform @@ -7522,7 +7522,7 @@ means that it can e.g no longer be part of an initializer expression. /* This may print something else than "6 * 7 = 42", if there is a non-weak definition of "ANSWER" in -an object linked in */ + an object linked in */ printf("6 * 7 = %d\n", ANSWER); return 0; `` https://github.com/llvm/llvm-project/pull/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
https://github.com/chrisnc edited https://github.com/llvm/llvm-project/pull/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
https://github.com/chrisnc updated https://github.com/llvm/llvm-project/pull/88631 >From d3e993c34e9d05f149b2670502794eaf93dee89a Mon Sep 17 00:00:00 2001 From: Chris Copeland Date: Fri, 12 Apr 2024 23:42:32 -0700 Subject: [PATCH] [clang][docs] fix whitespace in AttrDocs.td --- clang/include/clang/Basic/AttrDocs.td | 32 +-- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td index 8687c4f57d3f83..a0bbe5861c5722 100644 --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -1604,39 +1604,39 @@ specifies availability for the current target platform, the availability attributes are ignored. Supported platforms are: ``ios`` - Apple's iOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-ios*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=ios*version*`` + Apple's iOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-ios*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=ios*version*`` command-line argument. ``macos`` - Apple's macOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-macos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=macos*version*`` - command-line argument. ``macosx`` is supported for + Apple's macOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-macos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=macos*version*`` + command-line argument. ``macosx`` is supported for backward-compatibility reasons, but it is deprecated. ``tvos`` - Apple's tvOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-tvos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` + Apple's tvOS operating system. The minimum deployment target is specified + as part of the ``-target *arch*-apple-tvos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=tvos*version*`` command-line argument. ``watchos`` Apple's watchOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-watchos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` + as part of the ``-target *arch*-apple-watchos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=watchos*version*`` command-line argument. ``visionos`` Apple's visionOS operating system. The minimum deployment target is specified - as part of the ``-target *arch*-apple-visionos*version*`` command line argument. - Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` + as part of the ``-target *arch*-apple-visionos*version*`` command line argument. + Alternatively, it can be specified by the ``-mtargetos=visionos*version*`` command-line argument. ``driverkit`` Apple's DriverKit userspace kernel extensions. The minimum deployment target - is specified as part of the ``-target *arch*-apple-driverkit*version*`` + is specified as part of the ``-target *arch*-apple-driverkit*version*`` command line argument. A declaration can typically be used even when deploying back to a platform @@ -7522,7 +7522,7 @@ means that it can e.g no longer be part of an initializer expression. /* This may print something else than "6 * 7 = 42", if there is a non-weak definition of "ANSWER" in -an object linked in */ + an object linked in */ printf("6 * 7 = %d\n", ANSWER); return 0; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
chrisnc wrote: @cachemeifyoucan @cyndyishida for review? https://github.com/llvm/llvm-project/pull/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] fad3752 - [clang-tidy] Export fixes from check_clang_tidy.py (#88186)
Author: Edwin Vane Date: 2024-04-13T21:01:06+02:00 New Revision: fad37526a3ea7d669af621342968029085862281 URL: https://github.com/llvm/llvm-project/commit/fad37526a3ea7d669af621342968029085862281 DIFF: https://github.com/llvm/llvm-project/commit/fad37526a3ea7d669af621342968029085862281.diff LOG: [clang-tidy] Export fixes from check_clang_tidy.py (#88186) Makes it possible to export fixes from running llvm-lit on a clang-tidy test. To enable, modify the RUN invocation directly in the test with the new -export flag. llvm-lit will report the test passed and fixes can be found in the file specified to the -export flag. Added: Modified: clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/check_clang_tidy.py Removed: diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index b66be44e9f8a6f..1405fb0df1f8dd 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -100,6 +100,8 @@ Improvements to clang-tidy - Improved :program:`run-clang-tidy.py` script. Added argument `-source-filter` to filter source files from the compilation database, via a RegEx. In a similar fashion to what `-header-filter` does for header files. +- Improved :program:`check_clang_tidy.py` script. Added argument `-export-fixes` + to aid in clang-tidy and test development. New checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py index 53ffca0bad8d06..6d4b466afa691a 100755 --- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py +++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py @@ -8,25 +8,35 @@ # # ======# -r""" +""" ClangTidy Test Helper = -This script runs clang-tidy in fix mode and verify fixes, messages or both. +This script is used to simplify writing, running, and debugging tests compatible +with llvm-lit. By default it runs clang-tidy in fix mode and uses FileCheck to +verify messages and/or fixes. + +For debugging, with --export-fixes, the tool simply exports fixes to a provided +file and does not run FileCheck. -Usage: - check_clang_tidy.py [-resource-dir=] \ -[-assume-filename=] \ -[-check-suffix=] \ -[-check-suffixes=] \ -[-std=c++(98|11|14|17|20)[-or-later]] \ - \ --- [optional clang-tidy arguments] +Extra arguments, those after the first -- if any, are passed to either +clang-tidy or clang: +* Arguments between the first -- and second -- are clang-tidy arguments. + * May be only whitespace if there are no clang-tidy arguments. + * clang-tidy's --config would go here. +* Arguments after the second -- are clang arguments + +Examples + -Example: // RUN: %check_clang_tidy %s llvm-include-order %t -- -- -isystem %S/Inputs -Notes: +or + + // RUN: %check_clang_tidy %s llvm-include-order --export-fixes=fixes.yaml %t -std=c++20 + +Notes +- -std=c++(98|11|14|17|20)-or-later: This flag will cause multiple runs within the same check_clang_tidy execution. Make sure you don't have shared state across these runs. @@ -34,6 +44,7 @@ import argparse import os +import pathlib import re import subprocess import sys @@ -88,6 +99,7 @@ def __init__(self, args, extra_args): self.has_check_fixes = False self.has_check_messages = False self.has_check_notes = False +self.export_fixes = args.export_fixes self.fixes = MessagePrefix("CHECK-FIXES") self.messages = MessagePrefix("CHECK-MESSAGES") self.notes = MessagePrefix("CHECK-NOTES") @@ -181,7 +193,13 @@ def run_clang_tidy(self): [ "clang-tidy", self.temp_file_name, -"-fix", +] ++ [ +"-fix" +if self.export_fixes is None +else "--export-fixes=" + self.export_fixes +] ++ [ "--checks=-*," + self.check_name, ] + self.clang_tidy_extra_args @@ -255,12 +273,14 @@ def check_notes(self, clang_tidy_output): def run(self): self.read_input() -self.get_prefixes() +if self.export_fixes is None: +self.get_prefixes() self.prepare_test_inputs() clang_tidy_output = self.run_clang_tidy() -self.check_fixes() -self.check_messages(clang_tidy_output) -self.check_notes(clang_tidy_output) +if self.export_fixes is None: +self.check_fixes() +self.check_messages(clang_tidy_output) +self.check_notes(clang_tidy_output) def expand_std(std): @@ -284,7 +304,11 @@ def csv(string): def parse_arguments(): -parser = argparse.ArgumentParser(
[clang-tools-extra] [clang-tidy] Export fixes from check_clang_tidy.py (PR #88186)
https://github.com/PiotrZSL closed https://github.com/llvm/llvm-project/pull/88186 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
https://github.com/cachemeifyoucan approved this pull request. LGTM. Thanks for fixing. https://github.com/llvm/llvm-project/pull/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Ignore deleted ctor in `bugprone-forwarding-reference-overload` (PR #88138)
https://github.com/PiotrZSL commented: Missing release notes entry, except that looks fine. https://github.com/llvm/llvm-project/pull/88138 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
https://github.com/steakhal edited https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
@@ -2836,6 +2836,10 @@ bool RangeConstraintManager::canReasonAbout(SVal X) const { return false; } + // Non-integer types are not supported. + if (X.getAs()) +return false; + steakhal wrote: My problem with this is that I think LCVs shouldn't even appear here. And even if they could, why don't we also handle `nonloc::CompoundVals` too? They are basically the same thing, except for the lazyness. So, this patch masks some fundamental problem somewhere else - probably within the iterator checker or container modeling, actually passing an LCV. But I get it, its better to not crash, sure. I'd be happy to merge this and creating a new ticket for investigating what's going on. https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
@@ -0,0 +1,16 @@ +// RUN: %clang_analyze_cc1 %s \ +// RUN: -analyzer-checker=alpha.cplusplus.InvalidatedIterator \ +// RUN: -analyzer-config aggressive-binary-operation-simplification=true \ +// RUN: 2>&1 + +struct node {}; +struct prop : node {}; +struct bitvec : node { + prop operator==(bitvec) { return prop(); } + bitvec extend(); // { return *this; } steakhal wrote: ```suggestion bitvec extend(); ``` https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
@@ -57,10 +57,14 @@ ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef State, // We cannot reason about SymSymExprs, and can only reason about some // SymIntExprs. if (!canReasonAbout(Cond)) { -// Just add the constraint to the expression without trying to simplify. SymbolRef Sym = Cond.getAsSymbol(); -assert(Sym); -return assumeSymUnsupported(State, Sym, Assumption); +if (Sym) { + // this will simplify the symbol, so only call this if we have a + // symbol. + return assumeSymUnsupported(State, Sym, Assumption); +} else { + return State; +} steakhal wrote: ```suggestion if (SymbolRef Sym = Cond.getAsSymbol()) return assumeSymUnsupported(State, Sym, Assumption); return State; ``` https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
@@ -0,0 +1,16 @@ +// RUN: %clang_analyze_cc1 %s \ steakhal wrote: I think you should put this test without the RUN lines into the `clang/test/Analysis/invalidated-iterator.cpp` to have them at one place. https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)
https://github.com/steakhal requested changes to this pull request. https://github.com/llvm/llvm-project/pull/87521 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clang analysis] ExprMutationAnalyzer avoid infinite recursion for recursive forwarding reference (PR #87954)
https://github.com/PiotrZSL edited https://github.com/llvm/llvm-project/pull/87954 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clang analysis] ExprMutationAnalyzer avoid infinite recursion for recursive forwarding reference (PR #87954)
@@ -22,8 +21,15 @@ class FunctionParmMutationAnalyzer; /// a given statement. class ExprMutationAnalyzer { public: + friend class FunctionParmMutationAnalyzer; + struct Cache { +llvm::DenseMaphttps://github.com/llvm/llvm-project/pull/87954 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [clang analysis] ExprMutationAnalyzer avoid infinite recursion for recursive forwarding reference (PR #87954)
https://github.com/PiotrZSL approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/87954 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Introduce `SemaCUDA` (PR #88559)
fhahn wrote: Is it possible that this broke this bot failing with the error below? ``` usr/local/clang-17.0.2/bin/clang++ -DGTEST_HAS_RTTI=0 -D_CINDEX_LIB_ -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_LARGE_FILE_API -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/tools/libclang -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/tools/libclang -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/include -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/include -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/include -I/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/llvm/include -mcmodel=large -fPIC -Werror -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual -Wno-nested-anon-types -O3 -DNDEBUG -std=c++17 -fPIC -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -MD -MT tools/clang/tools/libclang/CMakeFiles/libclang.dir/CIndexCodeCompletion.cpp.o -MF tools/clang/tools/libclang/CMakeFiles/libclang.dir/CIndexCodeCompletion.cpp.o.d -o tools/clang/tools/libclang/CMakeFiles/libclang.dir/CIndexCodeCompletion.cpp.o -c /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/tools/libclang/CIndexCodeCompletion.cpp In file included from /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/tools/libclang/CIndexCodeCompletion.cpp:30: In file included from /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/include/clang/Sema/Sema.h:41: /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/include/clang/Basic/Cuda.h:59:3: error: expected identifier 59 | SM_32, | ^ /usr/include/sys/mac.h:79:15: note: expanded from macro 'SM_32' 79 | #define SM_32 8 /* number of 32 bit words for markings */ | ^ ``` https://lab.llvm.org/buildbot/#/builders/214/builds/11887 https://github.com/llvm/llvm-project/pull/88559 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang Format] Fixing erroneous statements in tests; nsc (PR #88628)
https://github.com/rymiel closed https://github.com/llvm/llvm-project/pull/88628 ___ 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 check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
PiotrZSL wrote: @sopyb Check is for modernize, not performance, so: - Add entry in documentation that due to need of copy object into initialization list check may cause performance degradation, add entry that using std::ref, std::cref is recommended in such case: `b = std::max({std::ref(i), std::ref(j), std::ref(k)});` - Add option - IgnoreNonTrivialTypes - set by default to true - Add option - IgnoreTrivialTypesOfSizeAbove - set by default to 32 bytes Options should be easy to add, check other checks. If you want quickly deliver version 1.0, then just limit check to built-in types. As for copies of large types, that's more a thing for new performance check. https://github.com/llvm/llvm-project/pull/85572 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-repl] Set up executor implicitly to account for init PTUs (PR #84758)
Stefan =?utf-8?q?Gränitz?= Message-ID: In-Reply-To: https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/84758 >From f28fc3aa917b24063707f99dd6545512630f48e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Sun, 10 Mar 2024 18:17:48 +0100 Subject: [PATCH 1/2] [clang-repl] Set up executor implicitly to account for init PTUs --- clang/lib/Interpreter/Interpreter.cpp | 32 +++ clang/test/Interpreter/execute.cpp| 4 ++-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index cf31456b6950ac..c6ca68db9b8056 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -229,12 +229,30 @@ IncrementalCompilerBuilder::CreateCudaHost() { } Interpreter::Interpreter(std::unique_ptr CI, - llvm::Error &Err) { - llvm::ErrorAsOutParameter EAO(&Err); + llvm::Error &ErrOut) { + llvm::ErrorAsOutParameter EAO(&ErrOut); auto LLVMCtx = std::make_unique(); TSCtx = std::make_unique(std::move(LLVMCtx)); - IncrParser = std::make_unique(*this, std::move(CI), - *TSCtx->getContext(), Err); + IncrParser = std::make_unique( + *this, std::move(CI), *TSCtx->getContext(), ErrOut); + if (ErrOut) +return; + + // Not all frontends support code-generation, e.g. ast-dump actions don't + if (IncrParser->getCodeGen()) { +if (llvm::Error Err = CreateExecutor()) { + ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); + return; +} + +// Process the PTUs that came from initialization. For example -include will +// give us a header that's processed at initialization of the preprocessor. +for (PartialTranslationUnit &PTU : IncrParser->getPTUs()) + if (llvm::Error Err = Execute(PTU)) { +ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); +return; + } + } } Interpreter::~Interpreter() { @@ -395,10 +413,16 @@ llvm::Error Interpreter::CreateExecutor() { return llvm::make_error("Operation failed. " "Execution engine exists", std::error_code()); + if (!IncrParser->getCodeGen()) +return llvm::make_error("Operation failed. " + "No code generator available", + std::error_code()); + llvm::Expected> JB = CreateJITBuilder(*getCompilerInstance()); if (!JB) return JB.takeError(); + llvm::Error Err = llvm::Error::success(); auto Executor = std::make_unique(*TSCtx, **JB, Err); if (!Err) diff --git a/clang/test/Interpreter/execute.cpp b/clang/test/Interpreter/execute.cpp index 6e73ed3927e815..534a54ed94fba2 100644 --- a/clang/test/Interpreter/execute.cpp +++ b/clang/test/Interpreter/execute.cpp @@ -7,6 +7,8 @@ // RUN: cat %s | clang-repl | FileCheck %s // RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s +// RUN: clang-repl -Xcc -include -Xcc %s | FileCheck %s +// RUN: clang-repl -Xcc -fsyntax-only -Xcc -include -Xcc %s extern "C" int printf(const char *, ...); int i = 42; auto r1 = printf("i = %d\n", i); @@ -19,5 +21,3 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_castFrom 0af28b70ea86ec56ab1ee83877d9021b791ba909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Mon, 11 Mar 2024 14:10:58 +0100 Subject: [PATCH 2/2] [tmp] Add crash note --- clang/test/Interpreter/inline-virtual.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/test/Interpreter/inline-virtual.cpp b/clang/test/Interpreter/inline-virtual.cpp index 79ab8ed337ffea..d862b3354f61fe 100644 --- a/clang/test/Interpreter/inline-virtual.cpp +++ b/clang/test/Interpreter/inline-virtual.cpp @@ -14,7 +14,7 @@ struct A { int a; A(int a) : a(a) {} virtual ~A(); }; // PartialTranslationUnit. inline A::~A() { printf("~A(%d)\n", a); } -// Create one instance with new and delete it. +// Create one instance with new and delete it. We crash here now: A *a1 = new A(1); delete a1; // CHECK: ~A(1) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -5598,10 +5598,34 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // FIXME: Breaking after newlines seems useful in general. Turn this into an // option and recognize more cases like endl etc, and break independent of // what comes after operator lessless. - if (Right.is(tok::lessless) && Right.Next && - Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && - Left.TokenText.ends_with("\\n\"")) { -return true; + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenStrings) { +if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && +Right.Next->is(tok::string_literal)) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_BetweenNewlineStrings) { +if (Right.is(tok::lessless) && Right.Next && +Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && +Left.TokenText.ends_with("\\n\"")) { + return true; +} + } + if (Style.BreakChevronOperator == FormatStyle::BCOS_Always) { +// can be std::os or os HazardyKnusperkeks wrote: Yeah ok, but I'd skip the `os`. https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -2193,6 +2193,41 @@ struct FormatStyle { /// \version 3.7 bool BreakBeforeTernaryOperators; + /// Different ways to Break Between Chevrons. + enum BreakChevronOperatorStyle : int8_t { +/// Break using ColumnLimit rules. +/// \code +/// os << "a" << "b" << "\n"; +/// \endcode +BCOS_Never, +/// Break between adjacent strings. +/// \code +/// os << "a" +/// << "b" +/// << "\n"; +/// \endcode +BCOS_BetweenStrings, +/// Break between adjacent strings that end with \n. +/// \code +/// os << "a\n" +/// << "b" << "c\n" +/// << "\n"; +/// \endcode +BCOS_BetweenNewlineStrings, +/// Break between adjacent chevrons. +/// \code +/// os << "a\n" +/// << "b" +/// << "c\n" +/// << "\n"; +/// \endcode +BCOS_Always + }; + + /// Break Between Chevron Operators + /// \version 19 + BreakChevronOperatorStyle BreakChevronOperator; HazardyKnusperkeks wrote: That's good. https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] revert to string << string handling to previous default (PR #88490)
@@ -5598,11 +5598,45 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, // FIXME: Breaking after newlines seems useful in general. Turn this into an // option and recognize more cases like endl etc, and break independent of // what comes after operator lessless. - if (Right.is(tok::lessless) && Right.Next && - Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && - Left.TokenText.ends_with("\\n\"")) { -return true; + switch (Style.BreakStreamOperator) { + case FormatStyle::BCOS_BetweenStrings: { +if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && +Right.Next->is(tok::string_literal)) { + return true; +} +break; + } + case FormatStyle::BCOS_BetweenNewlineStrings: { +if (Right.is(tok::lessless) && Right.Next && +Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) && +Left.TokenText.ends_with("\\n\"")) { + return true; +} +break; + } + case FormatStyle::BCOS_Always: { +// Don't break after the very first << or >> +// but the Left token can be os or std::os so HazardyKnusperkeks wrote: Still don't understand the part of `os` or `std::os`. https://github.com/llvm/llvm-project/pull/88490 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][docs] fix whitespace in AttrDocs.td (PR #88631)
chrisnc wrote: Ready to merge, but I'm not able to myself. https://github.com/llvm/llvm-project/pull/88631 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 created https://github.com/llvm/llvm-project/pull/88636 This PR aims to expand the list of classes that are considered to be "strings" by `readability-string-compare` check. 1. Currently `readability-string-compare` only checks `std::string;:compare`, but `std::string_view` has a similar `compare` method, which also should not be used to check equality of two strings. 2. Some codebases use custom string-like classes that have public interfaces similar to `std::string` or `std::string_view`. Example: [TStringBase](https://github.com/yandex/yatool/blob/main/util/generic/strbase.h#L38), Related to, but does not solve #28396 (only adds support for custom string-like classes, not custom functions) >From eb5279fd83ba114b8eb094099d5993d6bfb003e3 Mon Sep 17 00:00:00 2001 From: Vadim Dudkin Date: Sat, 13 Apr 2024 23:36:12 +0300 Subject: [PATCH] readability-string-compare: check std::string_view, allow custom string-like classes --- .../readability/StringCompareCheck.cpp| 75 +-- .../readability/StringCompareCheck.h | 10 ++- .../clang-tidy/checkers/Inputs/Headers/string | 10 +++ .../string-compare-custom-string-classes.cpp | 41 ++ .../checkers/readability/string-compare.cpp | 14 5 files changed, 125 insertions(+), 25 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..30bde1f8b75b61 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,15 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +23,55 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const StringRef DefaultStringClassNames = "::std::basic_string;" + "::std::basic_string_view"; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringClassNames(optutils::parseStringList( + Options.get("StringClassNames", DefaultStringClassNames))), + // Both std::string and std::string_view are templates, so this check only + // needs to match template classes by default. + // Custom `StringClassNames` may contain non-template classes, and + // it's impossible to tell them apart from templates just by name. + CheckNonTemplateClasses(Options.get("StringClassNames").has_value()) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + if (StringClassNames.empty()) { +return; + } + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), +
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 edited https://github.com/llvm/llvm-project/pull/88636 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix an issue where clang++ and clang uses enormous amounts of memory (PR #88637)
https://github.com/term-est created https://github.com/llvm/llvm-project/pull/88637 Henlo frens! 🍓 We folks at Armelsan Defense has been using LLVM for quite some time. Recently we encountered an issue with clangd where it tries to allocate 137 gigs of memory in one of our template heavy codebases. We recompiled the trunk with sanitizers, and got this -> ``` I[20:24:45.715] <-- reply(1) LLVM ERROR: SmallVector capacity unable to grow. Requested capacity (4294963200) is larger than maximum value for size type (4294967295) PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace. ``` So this is not a leak. Notice that requested capacity is 4294963200, which is quite near to i32 max. Further tests has showed that ```cpp /// Prepare to directly deduce arguments of the parameter with index \p Index. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, SmallVectorImpl &Deduced, TemplateDeductionInfo &Info, unsigned Index) : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { addPack(Index); finishConstruction(1); } private: void addPack(unsigned Index) { // Save the deduced template argument for the parameter pack expanded // by this pack expansion, then clear out the deduction. DeducedFromEarlierParameter = !Deduced[Index].isNull(); DeducedPack Pack(Index); Pack.Saved = Deduced[Index]; Deduced[Index] = TemplateArgument(); // FIXME: What if we encounter multiple packs with different numbers of // pre-expanded expansions? (This should already have been diagnosed // during substitution.) if (std::optional ExpandedPackExpansions = getExpandedPackSize(TemplateParams->getParam(Index))) FixedNumExpansions = ExpandedPackExpansions; Packs.push_back(Pack); [clangd-stacktrace.txt](https://github.com/llvm/llvm-project/files/14968656/clangd-stacktrace.txt) } ``` `addPack` might not initialize the `std::optional FixedNumExpansions` given that `getExpandedPackSize` returns a `nullopt`, which causes the access to `FixedNumExpansions` via the `operator*` to be Undefined. `PackElements` is eventually used in `SmallVector::grow_pod`, and vector tries to allocate 137 gigs. Attached, you can find the full stacktrace. [clangd-stacktrace.txt](https://github.com/llvm/llvm-project/files/14968658/clangd-stacktrace.txt) I can supply the exact code that causes this issue if needed, but I would appreciate if you frends can point me to any tools that can generate an obfuscated minimal reproducible example. Although this was discovered in clangd, it also appears to affect clang++ as well.   After this change, both seems to work just fine with clangd using only 300mb and clang++ compiling the codebase successfully and correctly. Thank you for your amazing work and thanks for the review~ >From 1c639842d1b5b79692c097df24757a90eeac888f Mon Sep 17 00:00:00 2001 From: term-est <62337595+term-...@users.noreply.github.com> Date: Sat, 13 Apr 2024 23:04:00 +0300 Subject: [PATCH] Fix the bug which causes the SmallVector to be not so small. PackDeductionScope::PackDeductionScope calls PackDeductionScope::addPack, which might not assign a value to PackDeductionScope::FixedNumExpansions given that getExpandedPackSize returns a nullopt. Access to an empty std::optional via the operator* is UB, and there is a case where IsExpanded is true while FixedNumberExpansions is empty. We access the empty optional, and this value is eventually used to in a call to SmallVector::reserve, which ends up trying to reserve 137 gigs of space and crashes clangd/clang++ --- clang/lib/Sema/SemaTemplateDeduction.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index 0b6375001f5326..1679852cdb386b 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -831,7 +831,7 @@ class PackDeductionScope { if (IsPartiallyExpanded) PackElements += NumPartialPackArgs; else if (IsExpanded) - PackElements += *FixedNumExpansions; + PackElements += FixedNumExpansions.value_or(1); for (auto &Pack : Packs) { if (Info.PendingDeducedPacks.size() > Pack.Index) ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix an issue where clang++ and clang uses enormous amounts of memory (PR #88637)
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/88637 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix an issue where clang++ and clang uses enormous amounts of memory (PR #88637)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (term-est) Changes Henlo frens! 🍓 We folks at Armelsan Defense has been using LLVM for quite some time. Recently we encountered an issue with clangd where it tries to allocate 137 gigs of memory in one of our template heavy codebases. We recompiled the trunk with sanitizers, and got this -> ``` I[20:24:45.715] <-- reply(1) LLVM ERROR: SmallVector capacity unable to grow. Requested capacity (4294963200) is larger than maximum value for size type (4294967295) PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace. ``` So this is not a leak. Notice that requested capacity is 4294963200, which is quite near to i32 max. Further tests has showed that ```cpp /// Prepare to directly deduce arguments of the parameter with index \p Index. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams, SmallVectorImpl&Deduced, TemplateDeductionInfo &Info, unsigned Index) : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) { addPack(Index); finishConstruction(1); } private: void addPack(unsigned Index) { // Save the deduced template argument for the parameter pack expanded // by this pack expansion, then clear out the deduction. DeducedFromEarlierParameter = !Deduced[Index].isNull(); DeducedPack Pack(Index); Pack.Saved = Deduced[Index]; Deduced[Index] = TemplateArgument(); // FIXME: What if we encounter multiple packs with different numbers of // pre-expanded expansions? (This should already have been diagnosed // during substitution.) if (std::optional ExpandedPackExpansions = getExpandedPackSize(TemplateParams->getParam(Index))) FixedNumExpansions = ExpandedPackExpansions; Packs.push_back(Pack); [clangd-stacktrace.txt](https://github.com/llvm/llvm-project/files/14968656/clangd-stacktrace.txt) } ``` `addPack` might not initialize the `std::optional FixedNumExpansions` given that `getExpandedPackSize` returns a `nullopt`, which causes the access to `FixedNumExpansions` via the `operator*` to be Undefined. `PackElements` is eventually used in `SmallVector::grow_pod`, and vector tries to allocate 137 gigs. Attached, you can find the full stacktrace. [clangd-stacktrace.txt](https://github.com/llvm/llvm-project/files/14968658/clangd-stacktrace.txt) I can supply the exact code that causes this issue if needed, but I would appreciate if you frends can point me to any tools that can generate an obfuscated minimal reproducible example. Although this was discovered in clangd, it also appears to affect clang++ as well.   After this change, both seems to work just fine with clangd using only 300mb and clang++ compiling the codebase successfully and correctly. Thank you for your amazing work and thanks for the review~ --- Full diff: https://github.com/llvm/llvm-project/pull/88637.diff 1 Files Affected: - (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+1-1) ``diff diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp b/clang/lib/Sema/SemaTemplateDeduction.cpp index 0b6375001f5326..1679852cdb386b 100644 --- a/clang/lib/Sema/SemaTemplateDeduction.cpp +++ b/clang/lib/Sema/SemaTemplateDeduction.cpp @@ -831,7 +831,7 @@ class PackDeductionScope { if (IsPartiallyExpanded) PackElements += NumPartialPackArgs; else if (IsExpanded) - PackElements += *FixedNumExpansions; + PackElements += FixedNumExpansions.value_or(1); for (auto &Pack : Packs) { if (Info.PendingDeducedPacks.size() > Pack.Index) `` https://github.com/llvm/llvm-project/pull/88637 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix an issue where clang++ and clangd uses enormous amounts of memory (PR #88637)
https://github.com/term-est edited https://github.com/llvm/llvm-project/pull/88637 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] Add ``ignoringParenImpCasts`` in ``hasAnyArgument`` fix#75754 (PR #87268)
https://github.com/komalverma04 updated https://github.com/llvm/llvm-project/pull/87268 >From 9b5781108081565e4009c3809eab623387655f1c Mon Sep 17 00:00:00 2001 From: komalverma04 Date: Mon, 1 Apr 2024 22:43:10 +0530 Subject: [PATCH 1/7] [clang-tidy] Add ignoringParenImpCasts in hasAnyArgument --- .../bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp| 2 +- .../clang-tidy/bugprone/MisplacedWideningCastCheck.cpp| 2 +- .../bugprone/MultipleNewInOneExpressionCheck.cpp | 8 .../clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp | 2 +- .../bugprone/StringLiteralWithEmbeddedNulCheck.cpp| 2 +- .../bugprone/SuspiciousStringviewDataUsageCheck.cpp | 2 +- .../clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp| 4 ++-- .../clang-tidy/modernize/UseEmplaceCheck.cpp | 6 +++--- .../performance/InefficientStringConcatenationCheck.cpp | 4 ++-- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp index 40e4ab6c8b12af..415183d5c57ba7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp @@ -24,7 +24,7 @@ void MisplacedOperatorInStrlenInAllocCheck::registerMatchers( const auto BadUse = callExpr(callee(StrLenFunc), - hasAnyArgument(ignoringImpCasts( + hasAnyArgument(ignoringParenImpCasts( binaryOperator( hasOperatorName("+"), hasRHS(ignoringParenImpCasts(integerLiteral(equals(1) diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp index a1f92aae55448c..b62829a3776572 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp @@ -42,7 +42,7 @@ void MisplacedWideningCastCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(varDecl(hasInitializer(Cast)), this); Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this); - Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this); + Finder->addMatcher(callExpr(hasAnyArgument(ignoringParenImpCasts(Cast))), this); Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this); Finder->addMatcher( binaryOperator(isComparisonOperator(), hasEitherOperand(Cast)), this); diff --git a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp index 41191a3cfed23a..b8dbea600fd368 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp @@ -96,17 +96,17 @@ void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( callExpr( hasAnyArgument( - expr(HasNewExpr1).bind("arg1")), + ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))), hasAnyArgument( - expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")), + ignoringParenImpCasts(expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2"))), hasAncestor(BadAllocCatchingTryBlock)), this); Finder->addMatcher( cxxConstructExpr( hasAnyArgument( - expr(HasNewExpr1).bind("arg1")), + ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))), hasAnyArgument( - expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")), + ignoringParenImpCasts(expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2"))), unless(isListInitialization()), hasAncestor(BadAllocCatchingTryBlock)), this); diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index 977241e91b9a93..d322f2488f8082 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -621,7 +621,7 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { auto MallocLengthExpr = allOf( callee(functionDecl( hasAnyName("::alloca", "::calloc", "malloc", "realloc"))), - hasAnyArgument(allOf(unless(SizeExpr), expr().bind(DestMallocExprName; + hasAnyArgument(ignoringParenImpCasts(allOf(unless(SizeExpr), expr().bind(DestMallocExprName); // - Example: (char *)malloc(length); auto DestMalloc = anyOf(callExpr(MallocLengthExpr), diff --git a/cl
[clang] Fix an issue where clang++ and clangd uses enormous amounts of memory (PR #88637)
https://github.com/term-est edited https://github.com/llvm/llvm-project/pull/88637 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 updated https://github.com/llvm/llvm-project/pull/88636 >From 91eccdd291fa4f0753aa8e9970fa146516823e22 Mon Sep 17 00:00:00 2001 From: Vadim Dudkin Date: Sat, 13 Apr 2024 23:36:12 +0300 Subject: [PATCH] readability-string-compare: check std::string_view, allow custom string-like classes --- .../readability/StringCompareCheck.cpp| 73 +-- .../readability/StringCompareCheck.h | 9 ++- clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../checks/readability/string-compare.rst | 33 - .../clang-tidy/checkers/Inputs/Headers/string | 10 +++ .../string-compare-custom-string-classes.cpp | 36 + .../checkers/readability/string-compare.cpp | 23 ++ 7 files changed, 162 insertions(+), 27 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..20218975ec121b 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,16 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +24,52 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), + has(StrCompare)) + .bind("match1")), +this); + +// Third and fourth case: str.compare(str) == 0 +// and str.compare(str) != 0. +Finder->addMatcher( +binaryOperator(hasAnyOperatorName("==", "!="), + hasOperands(StrCompare.bind("compare"), + integerLiteral(equals(0)).bind("zero"))) +.bind("match2"), +this); + }; + if (StringLikeClasses.empty()) { +RegisterForClasses( +classTemplateSpecializationDecl(hasAnyName(StringClasses))); + } else { +// StringLikeClasses may or may not be templates, so we need to match both. +std::vector PossiblyTemplateClasses = StringClasses; +PossiblyTemplateClasses.insert(PossiblyTemplateClasses.end(), + StringLikeClasses.begin(), + StringLikeClasses.end()); +RegisterForClasses(anyOf( +classTemplateSpecializationDecl(hasAnyName(PossiblyTemp
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 updated https://github.com/llvm/llvm-project/pull/88636 >From b63dd11ea87cd504c8972de6ed29330d6702abca Mon Sep 17 00:00:00 2001 From: Vadim Dudkin Date: Sat, 13 Apr 2024 23:36:12 +0300 Subject: [PATCH] readability-string-compare: check std::string_view, allow custom string-like classes --- .../readability/StringCompareCheck.cpp| 74 +-- .../readability/StringCompareCheck.h | 9 ++- clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../checks/readability/string-compare.rst | 33 - .../clang-tidy/checkers/Inputs/Headers/string | 10 +++ .../string-compare-custom-string-classes.cpp | 36 + .../checkers/readability/string-compare.cpp | 23 ++ 7 files changed, 163 insertions(+), 27 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..905e5b156ef864 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,16 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +24,53 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), + has(StrCompare)) + .bind("match1")), +this); + +// Third and fourth case: str.compare(str) == 0 +// and str.compare(str) != 0. +Finder->addMatcher( +binaryOperator(hasAnyOperatorName("==", "!="), + hasOperands(StrCompare.bind("compare"), + integerLiteral(equals(0)).bind("zero"))) +.bind("match2"), +this); + }; + if (StringLikeClasses.empty()) { +RegisterForClasses( +classTemplateSpecializationDecl(hasAnyName(StringClasses))); + } else { +// StringLikeClasses may or may not be templates, so we need to match both +// template and non-template classes. +std::vector PossiblyTemplateClasses = StringClasses; +PossiblyTemplateClasses.insert(PossiblyTemplateClasses.end(), + StringLikeClasses.begin(), + StringLikeClasses.end()); +RegisterForClasses(anyOf( +classTemplate
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 updated https://github.com/llvm/llvm-project/pull/88636 >From 0db24a6806e9429b5e7b9cd9d0777315b3e6d87e Mon Sep 17 00:00:00 2001 From: Vadim Dudkin Date: Sat, 13 Apr 2024 23:36:12 +0300 Subject: [PATCH] readability-string-compare: check std::string_view, allow custom string-like classes --- .../readability/StringCompareCheck.cpp| 74 +-- .../readability/StringCompareCheck.h | 9 ++- clang-tools-extra/docs/ReleaseNotes.rst | 5 ++ .../checks/readability/string-compare.rst | 33 - .../clang-tidy/checkers/Inputs/Headers/string | 10 +++ .../string-compare-custom-string-classes.cpp | 38 ++ .../checkers/readability/string-compare.cpp | 23 ++ 7 files changed, 165 insertions(+), 27 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..905e5b156ef864 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,16 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +24,53 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), + has(StrCompare)) + .bind("match1")), +this); + +// Third and fourth case: str.compare(str) == 0 +// and str.compare(str) != 0. +Finder->addMatcher( +binaryOperator(hasAnyOperatorName("==", "!="), + hasOperands(StrCompare.bind("compare"), + integerLiteral(equals(0)).bind("zero"))) +.bind("match2"), +this); + }; + if (StringLikeClasses.empty()) { +RegisterForClasses( +classTemplateSpecializationDecl(hasAnyName(StringClasses))); + } else { +// StringLikeClasses may or may not be templates, so we need to match both +// template and non-template classes. +std::vector PossiblyTemplateClasses = StringClasses; +PossiblyTemplateClasses.insert(PossiblyTemplateClasses.end(), + StringLikeClasses.begin(), + StringLikeClasses.end()); +RegisterForClasses(anyOf( +classTemplat
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
@@ -7,42 +7,70 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { vvd170501 wrote: Type of `StringClassMatcher` dependinds on whether the check is used with or without `StringLikeClasses`, so a template lambda is needed. It's possible to use `anyOf` and `cxxRecordDecl` in both cases and remove the lambda, but this will probably slow the check down in default case. https://github.com/llvm/llvm-project/pull/88636 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
https://github.com/vvd170501 ready_for_review https://github.com/llvm/llvm-project/pull/88636 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Vadim D. (vvd170501) Changes This PR aims to expand the list of classes that are considered to be "strings" by `readability-string-compare` check. 1. Currently only `std::string;:compare` is checked, but `std::string_view` has a similar `compare` method. This PR enables checking of `std::string_view::compare` by default. 2. Some codebases use custom string-like classes that have public interfaces similar to `std::string` or `std::string_view`. Example: [TStringBase](https://github.com/yandex/yatool/blob/main/util/generic/strbase.h#L38), A new option, `readability-string-compare.StringClassNames`, is added to allow specifying a custom list of string-like classes. Related to, but does not solve #28396 (only adds support for custom string-like classes, not custom functions) --- Full diff: https://github.com/llvm/llvm-project/pull/88636.diff 7 Files Affected: - (modified) clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp (+51-23) - (modified) clang-tools-extra/clang-tidy/readability/StringCompareCheck.h (+7-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) - (modified) clang-tools-extra/docs/clang-tidy/checks/readability/string-compare.rst (+31-2) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string (+10) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp (+38) - (modified) clang-tools-extra/test/clang-tidy/checkers/readability/string-compare.cpp (+23) ``diff diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..905e5b156ef864 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,16 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +24,53 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), + has(StrCompare)) + .bind("match1")), +this); + +// Third and fourth case: str.compare(str) == 0 +// and str.compare(str) != 0. +Finder->addMatcher( +binaryOperator(hasAnyOperatorName("==", "!="), + hasOperands(StrCompare.bind("compare"), +
[clang-tools-extra] [clang-tidy] check `std::string_view` and custom string-like classes in `readability-string-compare` (PR #88636)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Vadim D. (vvd170501) Changes This PR aims to expand the list of classes that are considered to be "strings" by `readability-string-compare` check. 1. Currently only `std::string;:compare` is checked, but `std::string_view` has a similar `compare` method. This PR enables checking of `std::string_view::compare` by default. 2. Some codebases use custom string-like classes that have public interfaces similar to `std::string` or `std::string_view`. Example: [TStringBase](https://github.com/yandex/yatool/blob/main/util/generic/strbase.h#L38), A new option, `readability-string-compare.StringClassNames`, is added to allow specifying a custom list of string-like classes. Related to, but does not solve #28396 (only adds support for custom string-like classes, not custom functions) --- Full diff: https://github.com/llvm/llvm-project/pull/88636.diff 7 Files Affected: - (modified) clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp (+51-23) - (modified) clang-tools-extra/clang-tidy/readability/StringCompareCheck.h (+7-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) - (modified) clang-tools-extra/docs/clang-tidy/checks/readability/string-compare.rst (+31-2) - (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/string (+10) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/string-compare-custom-string-classes.cpp (+38) - (modified) clang-tools-extra/test/clang-tidy/checkers/readability/string-compare.cpp (+23) ``diff diff --git a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp index 3b5d89c8c64719..905e5b156ef864 100644 --- a/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp @@ -7,12 +7,16 @@ //===--===// #include "StringCompareCheck.h" -#include "../utils/FixItHintUtils.h" +#include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/FixIt.h" +#include "llvm/ADT/StringRef.h" +#include using namespace clang::ast_matchers; +namespace optutils = clang::tidy::utils::options; namespace clang::tidy::readability { @@ -20,29 +24,53 @@ static const StringRef CompareMessage = "do not use 'compare' to test equality " "of strings; use the string equality " "operator instead"; +static const std::vector StringClasses = { +"::std::basic_string", "::std::basic_string_view"}; + +StringCompareCheck::StringCompareCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringLikeClasses( + optutils::parseStringList(Options.get("StringLikeClasses", ""))) {} + void StringCompareCheck::registerMatchers(MatchFinder *Finder) { - const auto StrCompare = cxxMemberCallExpr( - callee(cxxMethodDecl(hasName("compare"), - ofClass(classTemplateSpecializationDecl( - hasName("::std::basic_string"), - hasArgument(0, expr().bind("str2")), argumentCountIs(1), - callee(memberExpr().bind("str1"))); - - // First and second case: cast str.compare(str) to boolean. - Finder->addMatcher( - traverse(TK_AsIs, - implicitCastExpr(hasImplicitDestinationType(booleanType()), -has(StrCompare)) - .bind("match1")), - this); - - // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0. - Finder->addMatcher( - binaryOperator(hasAnyOperatorName("==", "!="), - hasOperands(StrCompare.bind("compare"), - integerLiteral(equals(0)).bind("zero"))) - .bind("match2"), - this); + const auto RegisterForClasses = [&, this](const auto &StringClassMatcher) { +const auto StrCompare = cxxMemberCallExpr( +callee(cxxMethodDecl(hasName("compare"), ofClass(StringClassMatcher))), +hasArgument(0, expr().bind("str2")), argumentCountIs(1), +callee(memberExpr().bind("str1"))); + +// First and second case: cast str.compare(str) to boolean. +Finder->addMatcher( +traverse(TK_AsIs, + implicitCastExpr(hasImplicitDestinationType(booleanType()), + has(StrCompare)) + .bind("match1")), +this); + +// Third and fourth case: str.compare(str) == 0 +// and str.compare(str) != 0. +Finder->addMatcher( +binaryOperator(hasAnyOperatorName("==", "!="), + hasOperands(StrCompare.bind("compare"), +
[clang] [clang-format] New clang-format-indent-mode for Emacs (PR #78904)
amygrinn wrote: ping https://github.com/llvm/llvm-project/pull/78904 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Fix an issue where clang++ and clangd uses enormous amounts of memory (PR #88637)
github-actions[bot] wrote: ⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo. Please turn off [Keep my email addresses private](https://github.com/settings/emails) setting in your account. See [LLVM Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it) for more information. https://github.com/llvm/llvm-project/pull/88637 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits