[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)
https://github.com/yronglin deleted https://github.com/llvm/llvm-project/pull/76361 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV][NFC] Pass LMUL to copyPhysRegVector (PR #84448)
https://github.com/wangpc-pp closed https://github.com/llvm/llvm-project/pull/84448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV][NFC] Pass LMUL to copyPhysRegVector (PR #84448)
https://github.com/wangpc-pp edited https://github.com/llvm/llvm-project/pull/84448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add generic CPUs for profiles (PR #84877)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/84877 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add generic CPUs for profiles (PR #84877)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the C/C++ code formatter. https://github.com/llvm/llvm-project/pull/84877 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [RISCV] Add generic CPUs for profiles (PR #84877)
https://github.com/wangpc-pp updated https://github.com/llvm/llvm-project/pull/84877 >From ec68548a470d6d9032a900a725e95b92691657b2 Mon Sep 17 00:00:00 2001 From: Wang Pengcheng Date: Tue, 12 Mar 2024 14:28:09 +0800 Subject: [PATCH 1/2] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?= =?UTF-8?q?itial=20version?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created using spr 1.3.4 --- clang/test/Driver/riscv-cpus.c| 319 ++ clang/test/Misc/target-invalid-cpu-note.c | 8 +- llvm/lib/Target/RISCV/RISCVProcessors.td | 224 ++- 3 files changed, 539 insertions(+), 12 deletions(-) diff --git a/clang/test/Driver/riscv-cpus.c b/clang/test/Driver/riscv-cpus.c index ff2bd6f7c8ba34..a285f0f9c41f54 100644 --- a/clang/test/Driver/riscv-cpus.c +++ b/clang/test/Driver/riscv-cpus.c @@ -302,3 +302,322 @@ // RUN: not %clang --target=riscv32 -### -c %s 2>&1 -mcpu=generic-rv32 -march=rv64i | FileCheck -check-prefix=MISMATCH-ARCH %s // MISMATCH-ARCH: cpu 'generic-rv32' does not support rv64 + +// Check profile CPUs + +// RUN: %clang -target riscv32 -### -c %s 2>&1 -mcpu=generic-rvi20u32 | FileCheck -check-prefix=MCPU-GENERIC-RVI20U32 %s +// MCPU-GENERIC-RVI20U32: "-target-cpu" "generic-rvi20u32" +// MCPU-GENERIC-RVI20U32-SAME: "-target-feature" "-a" +// MCPU-GENERIC-RVI20U32-SAME: "-target-feature" "-c" +// MCPU-GENERIC-RVI20U32-SAME: "-target-feature" "-d" +// MCPU-GENERIC-RVI20U32-SAME: "-target-feature" "-f" +// MCPU-GENERIC-RVI20U32-SAME: "-target-feature" "-m" +// MCPU-GENERIC-RVI20U32-SAME: "-target-abi" "ilp32" + +// RUN: %clang -target riscv64 -### -c %s 2>&1 -mcpu=generic-rvi20u64 | FileCheck -check-prefix=MCPU-GENERIC-RVI20U64 %s +// MCPU-GENERIC-RVI20U64: "-target-cpu" "generic-rvi20u64" +// MCPU-GENERIC-RVI20U64: "-target-feature" "-a" +// MCPU-GENERIC-RVI20U64: "-target-feature" "-c" +// MCPU-GENERIC-RVI20U64: "-target-feature" "-d" +// MCPU-GENERIC-RVI20U64: "-target-feature" "-f" +// MCPU-GENERIC-RVI20U64: "-target-feature" "-m" +// MCPU-GENERIC-RVI20U64-SAME: "-target-abi" "lp64" + +// RUN: %clang -target riscv64 -### -c %s 2>&1 -mcpu=generic-rva20u64 | FileCheck -check-prefix=MCPU-GENERIC-RVA20U64 %s +// MCPU-GENERIC-RVA20U64: "-target-cpu" "generic-rva20u64" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+m" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+a" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+f" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+d" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+c" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+ziccamoa" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+ziccif" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+zicclsm" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+ziccrse" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+zicntr" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+zicsr" +// MCPU-GENERIC-RVA20U64: "-target-feature" "+za128rs" +// MCPU-GENERIC-RVA20U64-SAME: "-target-abi" "lp64d" + +// RUN: %clang -target riscv64 -### -c %s 2>&1 -mcpu=generic-rva20s64 | FileCheck -check-prefix=MCPU-GENERIC-RVA20S64 %s +// MCPU-GENERIC-RVA20S64: "-target-cpu" "generic-rva20s64" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+m" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+a" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+f" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+d" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+c" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+ziccamoa" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+ziccif" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+zicclsm" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+ziccrse" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+zicntr" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+zicsr" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+zifencei" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+za128rs" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+ssccptr" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+sstvala" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+sstvecd" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+svade" +// MCPU-GENERIC-RVA20S64-SAME: "-target-feature" "+svbare" +// MCPU-GENERIC-RVA20S64-SAME: "-target-abi" "lp64d" + +// RUN: %clang -target riscv64 -### -c %s 2>&1 -mcpu=generic-rva22u64 | FileCheck -check-prefix=MCPU-GENERIC-RVA22U64 %s +// MCPU-GENERIC-RVA22U64: "-target-cpu" "generic-rva22u64" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+m" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+a" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+f" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+d" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+c" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+zic64b" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+zicbom" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature" "+zicbop" +// MCPU-GENERIC-RVA22U64-SAME: "-target-feature"
[clang] [llvm] [RISCV] Add generic CPUs for profiles (PR #84877)
https://github.com/wangpc-pp edited https://github.com/llvm/llvm-project/pull/84877 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)
https://github.com/wangpc-pp updated https://github.com/llvm/llvm-project/pull/83774 >From f1653805def59bc6eb23052b3ade80c900b4daaa Mon Sep 17 00:00:00 2001 From: wangpc Date: Fri, 14 Jul 2023 10:38:14 +0800 Subject: [PATCH 1/5] [clang] Enable sized deallocation by default in C++14 onwards Since C++14 has been released for about nine years and most standard libraries have implemented sized deallocation functions, it's time to make this feature default again. Differential Revision: https://reviews.llvm.org/D112921 --- .../clangd/unittests/FindTargetTests.cpp | 4 +- .../checkers/misc/new-delete-overloads.cpp| 10 - clang/docs/ReleaseNotes.rst | 5 + clang/include/clang/Driver/Options.td | 5 +- clang/lib/Driver/ToolChains/Clang.cpp | 13 +- clang/lib/Driver/ToolChains/Darwin.cpp| 58 - clang/lib/Driver/ToolChains/Darwin.h | 4 + clang/lib/Driver/ToolChains/ZOS.cpp | 6 + clang/test/AST/ast-dump-expr-json.cpp | 2 +- clang/test/AST/ast-dump-expr.cpp | 2 +- clang/test/AST/ast-dump-stmt-json.cpp | 244 +- clang/test/Analysis/cxxnewexpr-callback.cpp | 4 +- .../basic.stc.dynamic.deallocation/p2.cpp | 2 +- clang/test/CXX/drs/dr292.cpp | 17 +- .../test/CXX/expr/expr.unary/expr.new/p14.cpp | 2 +- .../CodeGenCXX/cxx1y-sized-deallocation.cpp | 10 +- .../CodeGenCXX/cxx1z-aligned-allocation.cpp | 6 +- .../CodeGenCXX/cxx2a-destroying-delete.cpp| 4 +- clang/test/CodeGenCXX/delete-two-arg.cpp | 4 +- clang/test/CodeGenCXX/delete.cpp | 12 +- clang/test/CodeGenCXX/dllimport.cpp | 4 +- clang/test/CodeGenCXX/new.cpp | 6 +- .../coro-aligned-alloc-2.cpp | 2 - .../CodeGenCoroutines/coro-aligned-alloc.cpp | 6 +- clang/test/CodeGenCoroutines/coro-alloc.cpp | 6 +- clang/test/CodeGenCoroutines/coro-cleanup.cpp | 6 +- clang/test/CodeGenCoroutines/coro-dealloc.cpp | 2 - clang/test/CodeGenCoroutines/coro-gro.cpp | 3 +- clang/test/CodeGenCoroutines/pr56919.cpp | 9 +- clang/test/Lexer/cxx-features.cpp | 20 +- clang/test/PCH/cxx1z-aligned-alloc.cpp| 10 +- clang/test/SemaCXX/MicrosoftExtensions.cpp| 8 +- .../SemaCXX/builtin-operator-new-delete.cpp | 2 +- .../test/SemaCXX/cxx1y-sized-deallocation.cpp | 2 +- .../unavailable_aligned_allocation.cpp| 15 +- .../StaticAnalyzer/CallEventTest.cpp | 2 +- clang/www/cxx_status.html | 11 +- .../support.dynamic/libcpp_deallocate.sh.cpp | 3 + .../sized_delete_array14.pass.cpp | 8 +- .../new.delete.single/sized_delete14.pass.cpp | 8 +- 40 files changed, 436 insertions(+), 111 deletions(-) diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp index 0af6036734ba53..1b7b96281dfaa5 100644 --- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp @@ -839,7 +839,9 @@ TEST_F(TargetDeclTest, OverloadExpr) { [[delete]] x; } )cpp"; - EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept"); + // Sized deallocation is enabled by default in C++14 onwards. + EXPECT_DECLS("CXXDeleteExpr", + "void operator delete(void *, unsigned long) noexcept"); } TEST_F(TargetDeclTest, DependentExprs) { diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp index 78f021144b2e19..f86fe8a4c5b14f 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp @@ -12,16 +12,6 @@ struct S { // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope void *operator new(size_t size) noexcept(false); -struct T { - // Sized deallocations are not enabled by default, and so this new/delete pair - // does not match. However, we expect only one warning, for the new, because - // the operator delete is a placement delete and we do not warn on mismatching - // placement operations. - // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope - void *operator new(size_t size) noexcept; - void operator delete(void *ptr, size_t) noexcept; // ok only if sized deallocation is enabled -}; - struct U { void *operator new(size_t size) noexcept; void operator delete(void *ptr) noexcept; diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index d6e179ca9d6904..489679d8c0c681 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -83,6 +83,11 @@
[clang] [llvm] [PowerPC] Tune AIX shared library TLS model at function level by heuristic (PR #84132)
@@ -80,6 +80,7 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public TargetInfo { bool IsISA3_0 = false; bool IsISA3_1 = false; bool HasQuadwordAtomics = false; + bool HasAIXShLibTLSModelHeuristic = false; orcguru wrote: Hi Kai, Thank you for pointing out this. I checked the code and it seems this flag is being used by backend in various places (for example: `PPCTargetLowering::LowerGlobalTLSAddressAIX`). You referred to another example that this flag is redundant, may I know the details and I will cross check with that scenario? https://github.com/llvm/llvm-project/pull/84132 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86_64] fix SSE type error in vaarg. (PR #86377)
https://github.com/CoTinker updated https://github.com/llvm/llvm-project/pull/86377 >From b494f2e7f59668678f95d4a739d810f6fd6944aa Mon Sep 17 00:00:00 2001 From: Longsheng Mou Date: Sat, 23 Mar 2024 11:52:04 +0800 Subject: [PATCH] [X86_64] fix SSE type error in vaarg. tweak the position of the ++neededSSE when Lo is NoClass and Hi is SSE. --- clang/lib/CodeGen/Targets/X86.cpp | 3 +- clang/test/CodeGen/X86/x86_64-vaarg.c | 69 ++ clang/test/CodeGenCXX/x86_64-vaarg.cpp | 50 +-- 3 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 clang/test/CodeGen/X86/x86_64-vaarg.c diff --git a/clang/lib/CodeGen/Targets/X86.cpp b/clang/lib/CodeGen/Targets/X86.cpp index 1ec0f159ebcb8a..6931768147a9b2 100644 --- a/clang/lib/CodeGen/Targets/X86.cpp +++ b/clang/lib/CodeGen/Targets/X86.cpp @@ -2788,12 +2788,11 @@ X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs, // memory), except in situations involving unions. case X87Up: case SSE: +++neededSSE; HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); if (Lo == NoClass) // Pass HighPart at offset 8 in memory. return ABIArgInfo::getDirect(HighPart, 8); - -++neededSSE; break; // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the diff --git a/clang/test/CodeGen/X86/x86_64-vaarg.c b/clang/test/CodeGen/X86/x86_64-vaarg.c new file mode 100644 index 00..a18ba836423881 --- /dev/null +++ b/clang/test/CodeGen/X86/x86_64-vaarg.c @@ -0,0 +1,69 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 4 +// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s + + +typedef struct { struct {} a; } empty; + +// CHECK-LABEL: define dso_local void @empty_record_test( +// CHECK-SAME: i32 noundef [[Z:%.*]], ...) #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_EMPTY:%.*]], align 1 +// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4 +// CHECK-NEXT:[[LIST:%.*]] = alloca [1 x %struct.__va_list_tag], align 16 +// CHECK-NEXT:[[TMP:%.*]] = alloca [[STRUCT_EMPTY]], align 1 +// CHECK-NEXT:store i32 [[Z]], ptr [[Z_ADDR]], align 4 +// CHECK-NEXT:[[ARRAYDECAY:%.*]] = getelementptr inbounds [1 x %struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0 +// CHECK-NEXT:call void @llvm.va_start(ptr [[ARRAYDECAY]]) +// CHECK-NEXT:[[ARRAYDECAY1:%.*]] = getelementptr inbounds [1 x %struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0 +// CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 1 [[RETVAL]], ptr align 1 [[TMP]], i64 0, i1 false) +// CHECK-NEXT:ret void +// +empty empty_record_test(int z, ...) { + __builtin_va_list list; + __builtin_va_start(list, z); + return __builtin_va_arg(list, empty); +} + +typedef struct { + struct{} a; + double b; +} s1; + +// CHECK-LABEL: define dso_local double @f( +// CHECK-SAME: i32 noundef [[Z:%.*]], ...) #[[ATTR0]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_S1:%.*]], align 8 +// CHECK-NEXT:[[Z_ADDR:%.*]] = alloca i32, align 4 +// CHECK-NEXT:[[LIST:%.*]] = alloca [1 x %struct.__va_list_tag], align 16 +// CHECK-NEXT:store i32 [[Z]], ptr [[Z_ADDR]], align 4 +// CHECK-NEXT:[[ARRAYDECAY:%.*]] = getelementptr inbounds [1 x %struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0 +// CHECK-NEXT:call void @llvm.va_start(ptr [[ARRAYDECAY]]) +// CHECK-NEXT:[[ARRAYDECAY1:%.*]] = getelementptr inbounds [1 x %struct.__va_list_tag], ptr [[LIST]], i64 0, i64 0 +// CHECK-NEXT:[[FP_OFFSET_P:%.*]] = getelementptr inbounds [[STRUCT___VA_LIST_TAG:%.*]], ptr [[ARRAYDECAY1]], i32 0, i32 1 +// CHECK-NEXT:[[FP_OFFSET:%.*]] = load i32, ptr [[FP_OFFSET_P]], align 4 +// CHECK-NEXT:[[FITS_IN_FP:%.*]] = icmp ule i32 [[FP_OFFSET]], 160 +// CHECK-NEXT:br i1 [[FITS_IN_FP]], label [[VAARG_IN_REG:%.*]], label [[VAARG_IN_MEM:%.*]] +// CHECK: vaarg.in_reg: +// CHECK-NEXT:[[TMP0:%.*]] = getelementptr inbounds [[STRUCT___VA_LIST_TAG]], ptr [[ARRAYDECAY1]], i32 0, i32 3 +// CHECK-NEXT:[[REG_SAVE_AREA:%.*]] = load ptr, ptr [[TMP0]], align 16 +// CHECK-NEXT:[[TMP1:%.*]] = getelementptr i8, ptr [[REG_SAVE_AREA]], i32 [[FP_OFFSET]] +// CHECK-NEXT:[[TMP2:%.*]] = add i32 [[FP_OFFSET]], 16 +// CHECK-NEXT:store i32 [[TMP2]], ptr [[FP_OFFSET_P]], align 4 +// CHECK-NEXT:br label [[VAARG_END:%.*]] +// CHECK: vaarg.in_mem: +// CHECK-NEXT:[[OVERFLOW_ARG_AREA_P:%.*]] = getelementptr inbounds [[STRUCT___VA_LIST_TAG]], ptr [[ARRAYDECAY1]], i32 0, i32 2 +// CHECK-NEXT:[[OVERFLOW_ARG_AREA:%.*]] = load ptr, ptr [[OVERFLOW_ARG_AREA_P]], align 8 +// CHECK-NEXT:[[OVERFLOW_ARG_AREA_NEXT:%.*]] = getelementptr i8, ptr [[OVERFLOW_ARG_AREA]], i32 8 +// CHECK-NEXT:store ptr [[OVERFLOW_ARG_AREA_NEXT]], ptr [[OVERFLOW_ARG_AREA_P]], align 8 +// CHECK-NEXT:br label [[VAARG_END]] +// CHECK:
[clang] [clang] Resolve FIXME in altivec.h (PR #78905)
https://github.com/AtariDreams converted_to_draft https://github.com/llvm/llvm-project/pull/78905 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)
https://github.com/AtariDreams closed https://github.com/llvm/llvm-project/pull/81367 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [OpenMP] Allow dynamic `condition` selector in Metadirective (PR #86457)
shiltian wrote: I'm not familiar with that section of code. Maybe @jdoerfert could give you more insights. https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Support outgoing calls in call hierarchy (PR #77556)
HighCommander4 wrote: Shopping around for some potential alternative reviewers :) https://github.com/llvm/llvm-project/pull/77556 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the C/C++ code formatter. https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,60 @@ +// RUN: %check_clang_tidy %s bugprone-exception-rethrow %t -- -- -fexceptions + +struct exception {}; + +void correct() { + try { + throw exception(); + } catch(const exception &) { + throw; + } +} + +void correct2() { + try { + throw exception(); + } catch(const exception ) { + try { +throw exception(); + } catch(...) {} + } +} + +void not_correct() { + try { + throw exception(); + } catch(const exception ) { + throw e; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: throwing a copy of the caught 'exception' exception, remove the argument to throw the original exception object [bugprone-exception-rethrow] + } +} + +void not_correct2() { + try { + throw 5; + } catch(const int ) { + throw e; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: throwing a copy of the caught 'int' exception, remove the argument to throw the original exception object [bugprone-exception-rethrow] + } +} + +void rethrow_not_correct() { + throw; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: empty 'throw' outside a catch block without an exception can trigger 'std::terminate' [bugprone-exception-rethrow] +} + +void rethrow_not_correct2() { + try { +throw; +// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: empty 'throw' outside a catch block without an exception can trigger 'std::terminate' [bugprone-exception-rethrow] + } catch(...) { + } +} + +void rethrow_correct() { + try { +throw 5; + } catch(...) { +throw; + } +} isuckatcs wrote: Also the `optionally(hasAncestor(cxxCatchStmt().bind("catch")))` matcher allows escaping `throw;` statements to slip through the check. This could also be documented as a limitation. E.g.: ```c++ void foo() { std::function fn; try { throw 1; } catch (...) { fn = [] { throw; }; } fn(); } ``` https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fixes #86451. --- Full diff: https://github.com/llvm/llvm-project/pull/86458.diff 2 Files Affected: - (modified) clang/lib/Format/TokenAnnotator.cpp (+4) - (modified) clang/unittests/Format/FormatTest.cpp (+1) ``diff diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 4c83a7a3a323be..b9144cf55452e2 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -4827,6 +4827,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine , Right.is(TT_TemplateOpener)) { return true; } +if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && +Right.TokenText[0] == '.') { + return false; +} } else if (Style.isProto()) { if (Right.is(tok::period) && Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 03005384a6f667..2f9ff43b9fa5bc 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -12075,6 +12075,7 @@ TEST_F(FormatTest, UnderstandsSquareAttributes) { verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); + verifyFormat("[[suppress(type.5)]] int uninitialized_on_purpose;"); verifyFormat("void f() [[deprecated(\"so sorry\")]];"); verifyFormat("aa\n" "[[unused]] aaa(int i);"); `` https://github.com/llvm/llvm-project/pull/86458 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Handle C++ Core Guidelines suppression tags (PR #86458)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/86458 Fixes #86451. >From 4149b046f97a4416041e2cd3fe5f134abed2f5d9 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sun, 24 Mar 2024 16:06:14 -0700 Subject: [PATCH] [clang-format] Handle C++ Core Guidelines suppression tags Fixes #86451. --- clang/lib/Format/TokenAnnotator.cpp | 4 clang/unittests/Format/FormatTest.cpp | 1 + 2 files changed, 5 insertions(+) diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp index 4c83a7a3a323be..b9144cf55452e2 100644 --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -4827,6 +4827,10 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine , Right.is(TT_TemplateOpener)) { return true; } +if (Left.is(tok::identifier) && Right.is(tok::numeric_constant) && +Right.TokenText[0] == '.') { + return false; +} } else if (Style.isProto()) { if (Right.is(tok::period) && Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 03005384a6f667..2f9ff43b9fa5bc 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -12075,6 +12075,7 @@ TEST_F(FormatTest, UnderstandsSquareAttributes) { verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); + verifyFormat("[[suppress(type.5)]] int uninitialized_on_purpose;"); verifyFormat("void f() [[deprecated(\"so sorry\")]];"); verifyFormat("aa\n" "[[unused]] aaa(int i);"); ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), isuckatcs wrote: How about adding a `FixItHint`? https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,60 @@ +// RUN: %check_clang_tidy %s bugprone-exception-rethrow %t -- -- -fexceptions + +struct exception {}; + +void correct() { + try { + throw exception(); + } catch(const exception &) { + throw; + } +} + +void correct2() { + try { + throw exception(); + } catch(const exception ) { + try { +throw exception(); + } catch(...) {} + } +} + +void not_correct() { + try { + throw exception(); + } catch(const exception ) { + throw e; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: throwing a copy of the caught 'exception' exception, remove the argument to throw the original exception object [bugprone-exception-rethrow] + } +} + +void not_correct2() { + try { + throw 5; + } catch(const int ) { + throw e; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: throwing a copy of the caught 'int' exception, remove the argument to throw the original exception object [bugprone-exception-rethrow] + } +} + +void rethrow_not_correct() { + throw; +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: empty 'throw' outside a catch block without an exception can trigger 'std::terminate' [bugprone-exception-rethrow] +} + +void rethrow_not_correct2() { + try { +throw; +// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: empty 'throw' outside a catch block without an exception can trigger 'std::terminate' [bugprone-exception-rethrow] + } catch(...) { + } +} + +void rethrow_correct() { + try { +throw 5; + } catch(...) { +throw; + } +} isuckatcs wrote: Please add a testcase, where the exception object is moved before it's rethrowed. ```c++ void foo() { try { throw std::unique_ptr(); } catch (std::unique_ptr ) { throw std::move(uptr); } } ``` I think this is ignored because of the `unless(has(expr()))` matcher, but this might not be correct in every case. In the following example the caught exception is still copied. ```c++ void foo() { try { throw S(); } catch (const S ) { throw(1, s); } } ``` I don't mind if this latter case is not handled, because it might be difficult to do so properly (imagine a constant expression here with branches, etc.), but this should be documented as a tradeoff. There is also the following case, that will be ignored by the check, which is once again difficult to handle. ```c++ void foo() { try { throw S(); } catch (const S ) { const auto = s; throw ref; } } ``` I don't know if it worths mentioning in the docs that we don't perform any flow-sensitive analysis here, because clang-tidy in general doesn't do that, but it also integrates some Clang Static Analyzer checks, which do. It might make sense though, so that users are fully aware of the limitations and won't think the missing warning for the above snippet is a bug. https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } isuckatcs wrote: There is already a "builtin" `isExceptionVariable()` matcher, which is defined exactly like this, so this definition is redundant. Please remove it. https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = + Result.Nodes.getNodeAs("catch") != nullptr; + if (!HasCatchAnsestor) { +diag(MatchedThrow->getThrowLoc(), + "empty 'throw' outside a catch block without an exception can trigger " + "'std::terminate'"); isuckatcs wrote: ```suggestion "empty 'throw' outside a catch block with no operand triggers 'std::terminate()'"); ``` According to the standard this always happens, and the check is only enabled if exceptions are enabled, so I think the message should reflect this too. >[N4917 7.6.18 4] If no exception is presently being handled, evaluating a >throw-expression with no operand calls std:: terminate() (14.6.2). https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = + Result.Nodes.getNodeAs("catch") != nullptr; + if (!HasCatchAnsestor) { +diag(MatchedThrow->getThrowLoc(), isuckatcs wrote: How about adding a `FixItHint` here too? https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = isuckatcs wrote: ```suggestion const bool HasCatchAncestor = ``` https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
https://github.com/isuckatcs requested changes to this pull request. Overall the patch looks good apart from some typos and documentation. By the way, looking at the issue, it seems like someone claimed to be working on it, though we haven't seen any progress so far. Was it okay to take over before asking that person first? https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
@@ -0,0 +1,37 @@ +//===--- ExceptionRethrowCheck.h - clang-tidy ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_EXCEPTIONRETHROWCHECK_H isuckatcs wrote: I know a lot of checkers have it this way, but some others have it the way below. How about making it more readable? ```suggestion #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_EXCEPTION_RETHROW_CHECK_H ``` https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
https://github.com/isuckatcs edited https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a crash with AlignArrayOfStructures option (PR #86420)
https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/86420 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] cceedc9 - [clang-format] Fix a crash with AlignArrayOfStructures option (#86420)
Author: Owen Pan Date: 2024-03-24T15:22:40-07:00 New Revision: cceedc939a43c7c732a5888364251775bffc2dba URL: https://github.com/llvm/llvm-project/commit/cceedc939a43c7c732a5888364251775bffc2dba DIFF: https://github.com/llvm/llvm-project/commit/cceedc939a43c7c732a5888364251775bffc2dba.diff LOG: [clang-format] Fix a crash with AlignArrayOfStructures option (#86420) Fixes #86109. Added: Modified: clang/lib/Format/WhitespaceManager.cpp clang/unittests/Format/FormatTest.cpp Removed: diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp index fef85abf79a38c..710bf8d8a8ec70 100644 --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -1491,7 +1491,7 @@ WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start, : Cell); // Go to the next non-comment and ensure there is a break in front const auto *NextNonComment = C.Tok->getNextNonComment(); -while (NextNonComment->is(tok::comma)) +while (NextNonComment && NextNonComment->is(tok::comma)) NextNonComment = NextNonComment->getNextNonComment(); auto j = i; while (j < End && Changes[j].Tok != NextNonComment) diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index cf8d6ab691d9a0..03005384a6f667 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -21100,7 +21100,14 @@ TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { "[0] = {1, 1},\n" "[1] { 1, 1, },\n" "[2] { 1, 1, },\n" -"};"); +"};", +Style); + verifyNoCrash("test arr[] = {\n" +"#define FOO(i) {i, i},\n" +"SOME_GENERATOR(FOO)\n" +"{2, 2}\n" +"};", +Style); verifyFormat("return GradForUnaryCwise(g, {\n" "{{\"sign\"}, \"Sign\", " @@ -21353,7 +21360,14 @@ TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { "[0] = {1, 1},\n" "[1] { 1, 1, },\n" "[2] { 1, 1, },\n" -"};"); +"};", +Style); + verifyNoCrash("test arr[] = {\n" +"#define FOO(i) {i, i},\n" +"SOME_GENERATOR(FOO)\n" +"{2, 2}\n" +"};", +Style); verifyFormat("return GradForUnaryCwise(g, {\n" "{{\"sign\"}, \"Sign\", {\"x\", " ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [OpenMP] Allow dynamic `condition` selector in Metadirective (PR #86457)
@@ -107,5 +112,8 @@ void foo(void) { // CHECK-AMDGCN-NEXT: for (int i = 0; i < 100; i++) // CHECK: for (int i = 0; i < 16; i++) // CHECK: for (int i = 0; i < 16; i++) +// CHECK: int non_const_val = 1; +// CHECK-NEXT: #pragma omp parallel robincaloudis wrote: `#pragma omp parallel` will not be written as the default for non-const user condition is used https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [OpenMP] Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
robincaloudis wrote: >From what I understood, I'd say that there is a chance that wrong semantics >are attached against the `trait-selector` when it is a dynamic condition >selector, i.e. `condition(non_const_val > 0)`. I'd base my argumentation on >the fact that static condition selector do work. @shiltian, what do you think? >Any other idea? Code where `selector-set` (i.e. `user={}`) is parsed: https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseOpenMP.cpp#L2649-L2657 Code where `selector`(i.e. `condition(non_const_val > 0)`) is parsed: https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseOpenMP.cpp#L1185-L1225 https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the C/C++ code formatter. https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Allow dynamic `condition` selector in Metadirective (PR #86457)
https://github.com/robincaloudis edited https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Metadirective uses default for non-const user condition (PR #86457)
https://github.com/robincaloudis converted_to_draft https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Metadirective uses default for non-const user condition (PR #86457)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Robin Caloudis (robincaloudis) Changes As reported in https://github.com/llvm/llvm-project/issues/82754, Metadirectives uses default for non-const user condition. This is unexpected as the OpenMP specification 5.1 allows dynamic `condition` selector within Metadirectives. In contrast static `condition` selector work. ### Example: ```c++ int non_const_val = 1; // A non const value makes the `condition` selector dynamic; a const value makes it static #pragma omp metadirective \ when( user= {condition(non_const_val 0)} : parallel num_threads( num_threads ) ) \ default() { #pragma omp single assert( num_threads == omp_get_num_threads() ); } ``` where as `user` is called _selector set_ and `condition` is called _selector_ (must evaluate to true for the selector to be true). ## Background informations ### As of OpenMP 5.1, dynamic `condition` selectors seem to be allowed "[...] Any non-constant expression that is evaluated to determine the suitability of a variant is evaluated according to the data state trait in the dynamic trait set of the OpenMP context. The user selector set is dynamic if the _condition selector_ is present and the expression in the condition selector is not a constant expression; otherwise, it is static. [...]" ### Assembled grammar (copied from OpenMP 5.1. specification on [Metadirectives](https://www.openmp.org/spec-html/5.1/openmpsu28.html#x45-440002.3.4) and [Context Selectors](https://www.openmp.org/spec-html/5.1/openmpsu26.html#x43-420002.3.2)): There is a change that wrong semantics (meaning) are attached against the `trait-selector` when it is a dynamic condition selector ```c++ #pragma omp metadirective [clause[ [,] clause] ... ] new-line // where clause is one of the following: when(context-selector-specification: [directive-variant]) default([directive-variant]) // where context-selector-specification is context-selector-specification: trait-set-selector[,trait-set-selector[,...]] // where trait-set-selector is trait-set-selector: trait-set-selector-name={trait-selector[, trait-selector[, ...]]} ``` Specification of [Metadirectives](https://www.openmp.org/spec-html/5.1/openmpsu26.html#x43-420002.3.2) in OpenMP 5.1 Issue: https://github.com/llvm/llvm-project/issues/82754 --- Full diff: https://github.com/llvm/llvm-project/pull/86457.diff 1 Files Affected: - (modified) clang/test/OpenMP/metadirective_ast_print.c (+8) ``diff diff --git a/clang/test/OpenMP/metadirective_ast_print.c b/clang/test/OpenMP/metadirective_ast_print.c index d9ff7e76452160..afc150610f197b 100644 --- a/clang/test/OpenMP/metadirective_ast_print.c +++ b/clang/test/OpenMP/metadirective_ast_print.c @@ -77,6 +77,11 @@ void foo(void) { : parallel) default(nothing) for (int i = 0; i < 16; i++) ; + + int non_const_val = 1; +#pragma omp metadirective when(user = {condition(non_const_val > 0)} \ + : parallel) default(nothing) + bar(); } // CHECK: void bar(void); @@ -107,5 +112,8 @@ void foo(void) { // CHECK-AMDGCN-NEXT: for (int i = 0; i < 100; i++) // CHECK: for (int i = 0; i < 16; i++) // CHECK: for (int i = 0; i < 16; i++) +// CHECK: int non_const_val = 1; +// CHECK-NEXT: #pragma omp parallel +// CHECK-NEXT: bar() #endif `` https://github.com/llvm/llvm-project/pull/86457 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] WIP: Metadirective uses default for non-const user condition (PR #86457)
https://github.com/robincaloudis created https://github.com/llvm/llvm-project/pull/86457 As reported in https://github.com/llvm/llvm-project/issues/82754, Metadirectives uses default for non-const user condition. This is unexpected as the OpenMP specification 5.1 allows dynamic `condition` selector within Metadirectives. In contrast static `condition` selector work. ### Example: ```c++ int non_const_val = 1; // A non const value makes the `condition` selector dynamic; a const value makes it static #pragma omp metadirective \ when( user= {condition(non_const_val > 0)} : parallel num_threads( num_threads ) ) \ default() { #pragma omp single assert( num_threads == omp_get_num_threads() ); } ``` where as `user` is called _selector set_ and `condition` is called _selector_ (must evaluate to true for the selector to be true). ## Background informations ### As of OpenMP 5.1, dynamic `condition` selectors seem to be allowed "[...] Any non-constant expression that is evaluated to determine the suitability of a variant is evaluated according to the data state trait in the dynamic trait set of the OpenMP context. The user selector set is dynamic if the _condition selector_ is present and the expression in the condition selector is not a constant expression; otherwise, it is static. [...]" ### Assembled grammar (copied from OpenMP 5.1. specification on [Metadirectives](https://www.openmp.org/spec-html/5.1/openmpsu28.html#x45-440002.3.4) and [Context Selectors](https://www.openmp.org/spec-html/5.1/openmpsu26.html#x43-420002.3.2)): There is a change that wrong semantics (meaning) are attached against the `trait-selector` when it is a dynamic condition selector ```c++ #pragma omp metadirective [clause[ [,] clause] ... ] new-line // where clause is one of the following: when(context-selector-specification: [directive-variant]) default([directive-variant]) // where context-selector-specification is context-selector-specification: trait-set-selector[,trait-set-selector[,...]] // where trait-set-selector is trait-set-selector: trait-set-selector-name={trait-selector[, trait-selector[, ...]]} ``` Specification of [Metadirectives](https://www.openmp.org/spec-html/5.1/openmpsu26.html#x43-420002.3.2) in OpenMP 5.1 Issue: https://github.com/llvm/llvm-project/issues/82754 >From bc962815d5587ffb16a178b4b766ffe36ee1c8a0 Mon Sep 17 00:00:00 2001 From: Robin Caloudis Date: Sun, 24 Mar 2024 21:37:33 +0100 Subject: [PATCH] Reproduce reported issue --- clang/test/OpenMP/metadirective_ast_print.c | 8 1 file changed, 8 insertions(+) diff --git a/clang/test/OpenMP/metadirective_ast_print.c b/clang/test/OpenMP/metadirective_ast_print.c index d9ff7e76452160..afc150610f197b 100644 --- a/clang/test/OpenMP/metadirective_ast_print.c +++ b/clang/test/OpenMP/metadirective_ast_print.c @@ -77,6 +77,11 @@ void foo(void) { : parallel) default(nothing) for (int i = 0; i < 16; i++) ; + + int non_const_val = 1; +#pragma omp metadirective when(user = {condition(non_const_val > 0)} \ + : parallel) default(nothing) + bar(); } // CHECK: void bar(void); @@ -107,5 +112,8 @@ void foo(void) { // CHECK-AMDGCN-NEXT: for (int i = 0; i < 100; i++) // CHECK: for (int i = 0; i < 16; i++) // CHECK: for (int i = 0; i < 16; i++) +// CHECK: int non_const_val = 1; +// CHECK-NEXT: #pragma omp parallel +// CHECK-NEXT: bar() #endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a crash with AlignArrayOfStructures option (PR #86420)
https://github.com/HazardyKnusperkeks approved this pull request. https://github.com/llvm/llvm-project/pull/86420 ___ 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 expresions in unevaluated context in bugprone-inc-dec-in-conditions (PR #85849)
https://github.com/PiotrZSL closed https://github.com/llvm/llvm-project/pull/85849 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] d4a4585 - [clang-tidy] Ignore expresions in unevaluated context in bugprone-inc-dec-in-conditions (#85849)
Author: Piotr Zegar Date: 2024-03-24T19:52:19+01:00 New Revision: d4a4585165f5c6ca8c42920b70e1b47696ff1172 URL: https://github.com/llvm/llvm-project/commit/d4a4585165f5c6ca8c42920b70e1b47696ff1172 DIFF: https://github.com/llvm/llvm-project/commit/d4a4585165f5c6ca8c42920b70e1b47696ff1172.diff LOG: [clang-tidy] Ignore expresions in unevaluated context in bugprone-inc-dec-in-conditions (#85849) Skip checking for references to variable in unevaluated context, like decltype, static_assert and so on. Closes #85838 Added: Modified: clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp index 16f43128d55e87..9b3b01eb026833 100644 --- a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp @@ -31,6 +31,10 @@ void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { anyOf(binaryOperator(anyOf(isComparisonOperator(), isLogicalOperator())), cxxOperatorCallExpr(isComparisonOperator(; + auto IsInUnevaluatedContext = + expr(anyOf(hasAncestor(expr(matchers::hasUnevaluatedContext())), + hasAncestor(typeLoc(; + Finder->addMatcher( expr( OperatorMatcher, unless(isExpansionInSystemHeader()), @@ -42,12 +46,14 @@ void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { cxxOperatorCallExpr( isPrePostOperator(), hasUnaryOperand(expr().bind("operand", + unless(IsInUnevaluatedContext), hasAncestor( expr(equalsBoundNode("parent"), hasDescendant( expr(unless(equalsBoundNode("operand")), matchers::isStatementIdenticalToBoundNode( - "operand")) + "operand"), + unless(IsInUnevaluatedContext)) .bind("second") .bind("operator"))), this); diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index a604e9276668ae..2392ccaf65754f 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -139,6 +139,10 @@ Changes in existing checks ` check by detecting side effect from calling a method with non-const reference parameters. +- Improved :doc:`bugprone-inc-dec-in-conditions + ` check to ignore code + within unevaluated contexts, such as ``decltype``. + - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion ` check by eliminating false positives resulting from direct usage of bitwise operators diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp index 82af039973c3bb..91de013138f0de 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp @@ -68,3 +68,13 @@ bool doubleCheck(Container x) { // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: decrementing and referencing a variable in a complex condition can cause unintended side-effects due to C++'s order of evaluation, consider moving the modification outside of the condition to avoid misunderstandings [bugprone-inc-dec-in-conditions] // CHECK-MESSAGES: :[[@LINE-2]]:31: warning: incrementing and referencing a variable in a complex condition can cause unintended side-effects due to C++'s order of evaluation, consider moving the modification outside of the condition to avoid misunderstandings [bugprone-inc-dec-in-conditions] } + +namespace PR85838 { + void test() + { +auto foo = 0; +auto bar = 0; +if (++foo < static_cast(bar)) {} +if (static_cast(bar) < foo) {} + } +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the C/C++ code formatter. https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/86448 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
https://github.com/PiotrZSL updated https://github.com/llvm/llvm-project/pull/86448 >From 05cf976fd14e3d2a7e716e26e80e8958dff4222c Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Sun, 24 Mar 2024 18:39:54 + Subject: [PATCH 1/2] [clang-tidy] Added bugprone-exception-rethrow check Identifies problematic exception rethrowing, especially with caught exception variables or empty throw statements outside catch blocks. Closes #71292 --- .../bugprone/BugproneTidyModule.cpp | 3 + .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../bugprone/ExceptionRethrowCheck.cpp| 50 ++ .../bugprone/ExceptionRethrowCheck.h | 37 ++ clang-tools-extra/docs/ReleaseNotes.rst | 6 ++ .../checks/bugprone/exception-rethrow.rst | 68 +++ .../docs/clang-tidy/checks/list.rst | 1 + .../checkers/bugprone/exception-rethrow.cpp | 60 8 files changed, 226 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/exception-rethrow.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-rethrow.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..adaa77fdbfbde0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -26,6 +26,7 @@ #include "EasilySwappableParametersCheck.h" #include "EmptyCatchCheck.h" #include "ExceptionEscapeCheck.h" +#include "ExceptionRethrowCheck.h" #include "FoldInitTypeCheck.h" #include "ForwardDeclarationNamespaceCheck.h" #include "ForwardingReferenceOverloadCheck.h" @@ -126,6 +127,8 @@ class BugproneModule : public ClangTidyModule { CheckFactories.registerCheck("bugprone-empty-catch"); CheckFactories.registerCheck( "bugprone-exception-escape"); +CheckFactories.registerCheck( +"bugprone-exception-rethrow"); CheckFactories.registerCheck("bugprone-fold-init-type"); CheckFactories.registerCheck( "bugprone-forward-declaration-namespace"); diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..7c7288f75e1888 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -20,6 +20,7 @@ add_clang_library(clangTidyBugproneModule EasilySwappableParametersCheck.cpp EmptyCatchCheck.cpp ExceptionEscapeCheck.cpp + ExceptionRethrowCheck.cpp FoldInitTypeCheck.cpp ForwardDeclarationNamespaceCheck.cpp ForwardingReferenceOverloadCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp new file mode 100644 index 00..4855ccc2724a92 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp @@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = + Result.Nodes.getNodeAs("catch") != nullptr; + if (!HasCatchAnsestor) { +diag(MatchedThrow->getThrowLoc(), + "empty 'throw' outside a catch block without an exception can trigger " + "'std::terminate'"); + }
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clang-tidy Author: Piotr Zegar (PiotrZSL) Changes Identifies problematic exception rethrowing, especially with caught exception variables or empty throw statements outside catch blocks. Closes #71292 --- Full diff: https://github.com/llvm/llvm-project/pull/86448.diff 8 Files Affected: - (modified) clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp (+3) - (modified) clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt (+1) - (added) clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp (+50) - (added) clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.h (+37) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) - (added) clang-tools-extra/docs/clang-tidy/checks/bugprone/exception-rethrow.rst (+68) - (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-rethrow.cpp (+60) ``diff diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..adaa77fdbfbde0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -26,6 +26,7 @@ #include "EasilySwappableParametersCheck.h" #include "EmptyCatchCheck.h" #include "ExceptionEscapeCheck.h" +#include "ExceptionRethrowCheck.h" #include "FoldInitTypeCheck.h" #include "ForwardDeclarationNamespaceCheck.h" #include "ForwardingReferenceOverloadCheck.h" @@ -126,6 +127,8 @@ class BugproneModule : public ClangTidyModule { CheckFactories.registerCheck("bugprone-empty-catch"); CheckFactories.registerCheck( "bugprone-exception-escape"); +CheckFactories.registerCheck( +"bugprone-exception-rethrow"); CheckFactories.registerCheck("bugprone-fold-init-type"); CheckFactories.registerCheck( "bugprone-forward-declaration-namespace"); diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..7c7288f75e1888 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -20,6 +20,7 @@ add_clang_library(clangTidyBugproneModule EasilySwappableParametersCheck.cpp EmptyCatchCheck.cpp ExceptionEscapeCheck.cpp + ExceptionRethrowCheck.cpp FoldInitTypeCheck.cpp ForwardDeclarationNamespaceCheck.cpp ForwardingReferenceOverloadCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp new file mode 100644 index 00..4855ccc2724a92 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp @@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = + Result.Nodes.getNodeAs("catch") != nullptr; + if (!HasCatchAnsestor) { +diag(MatchedThrow->getThrowLoc(), + "empty 'throw' outside a catch block without an exception can trigger " + "'std::terminate'"); + } +} + +} // namespace clang::tidy::bugprone diff --git a/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.h b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.h new file mode 100644 index 00..bbb30f779cf258 --- /dev/null +++
[clang-tools-extra] [clang-tidy] Added bugprone-exception-rethrow check (PR #86448)
https://github.com/PiotrZSL created https://github.com/llvm/llvm-project/pull/86448 Identifies problematic exception rethrowing, especially with caught exception variables or empty throw statements outside catch blocks. Closes #71292 >From 05cf976fd14e3d2a7e716e26e80e8958dff4222c Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Sun, 24 Mar 2024 18:39:54 + Subject: [PATCH] [clang-tidy] Added bugprone-exception-rethrow check Identifies problematic exception rethrowing, especially with caught exception variables or empty throw statements outside catch blocks. Closes #71292 --- .../bugprone/BugproneTidyModule.cpp | 3 + .../clang-tidy/bugprone/CMakeLists.txt| 1 + .../bugprone/ExceptionRethrowCheck.cpp| 50 ++ .../bugprone/ExceptionRethrowCheck.h | 37 ++ clang-tools-extra/docs/ReleaseNotes.rst | 6 ++ .../checks/bugprone/exception-rethrow.rst | 68 +++ .../docs/clang-tidy/checks/list.rst | 1 + .../checkers/bugprone/exception-rethrow.cpp | 60 8 files changed, 226 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/bugprone/exception-rethrow.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-rethrow.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 2931325d8b5798..adaa77fdbfbde0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -26,6 +26,7 @@ #include "EasilySwappableParametersCheck.h" #include "EmptyCatchCheck.h" #include "ExceptionEscapeCheck.h" +#include "ExceptionRethrowCheck.h" #include "FoldInitTypeCheck.h" #include "ForwardDeclarationNamespaceCheck.h" #include "ForwardingReferenceOverloadCheck.h" @@ -126,6 +127,8 @@ class BugproneModule : public ClangTidyModule { CheckFactories.registerCheck("bugprone-empty-catch"); CheckFactories.registerCheck( "bugprone-exception-escape"); +CheckFactories.registerCheck( +"bugprone-exception-rethrow"); CheckFactories.registerCheck("bugprone-fold-init-type"); CheckFactories.registerCheck( "bugprone-forward-declaration-namespace"); diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 081ba67efe1538..7c7288f75e1888 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -20,6 +20,7 @@ add_clang_library(clangTidyBugproneModule EasilySwappableParametersCheck.cpp EmptyCatchCheck.cpp ExceptionEscapeCheck.cpp + ExceptionRethrowCheck.cpp FoldInitTypeCheck.cpp ForwardDeclarationNamespaceCheck.cpp ForwardingReferenceOverloadCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp new file mode 100644 index 00..4855ccc2724a92 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/ExceptionRethrowCheck.cpp @@ -0,0 +1,50 @@ +//===--- ExceptionRethrowCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "ExceptionRethrowCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } +} // namespace + +void ExceptionRethrowCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + cxxThrowExpr(unless(isExpansionInSystemHeader()), + anyOf(unless(has(expr())), + has(declRefExpr(to(varDecl(isExceptionVariable()), + optionally(hasAncestor(cxxCatchStmt().bind("catch" + .bind("throw"), + this); +} + +void ExceptionRethrowCheck::check(const MatchFinder::MatchResult ) { + const auto *MatchedThrow = Result.Nodes.getNodeAs("throw"); + + if (const Expr *ThrownObject = MatchedThrow->getSubExpr()) { +diag(MatchedThrow->getThrowLoc(), + "throwing a copy of the caught %0 exception, remove the argument to " + "throw the original exception object") +<< ThrownObject->getType().getNonReferenceType(); +return; + } + + const bool HasCatchAnsestor = + Result.Nodes.getNodeAs("catch") != nullptr; + if (!HasCatchAnsestor) { +
[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)
komalverma04 wrote: @AtariDreams Thank you for pointing out. I apologies for that mistake. Please review it, if there are more changes. https://github.com/llvm/llvm-project/pull/86411 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] remove double impelementation of log, sin, trunc intrinsics (PR #86440)
https://github.com/aabysswalker edited https://github.com/llvm/llvm-project/pull/86440 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Match against all plugins when parsing microsoft attributes (PR #86426)
https://github.com/Sirraide edited https://github.com/llvm/llvm-project/pull/86426 ___ 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 expresions in unevaluated context in bugprone-inc-dec-in-conditions (PR #85849)
https://github.com/5chmidti approved this pull request. https://github.com/llvm/llvm-project/pull/85849 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)
https://github.com/komalverma04 updated https://github.com/llvm/llvm-project/pull/86411 >From b6ca6f0ef83d03e299d6ee9a8ed9b8044477914e Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:14:44 -0700 Subject: [PATCH 1/5] Update checkers.rst Modification of documentation to demonstrate utilization of AllowedPad within PaddingChecker, along with its use and effects on code analysis. --- clang/docs/analyzer/checkers.rst | 22 -- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index fe211514914272..64b09bc6ecd1d8 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,10 +804,28 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding -" +optin.performance.Padding (PaddingChecker) +""" Check for excessively padded structs. +.. code-block:: objc + + struct TestStruct { + int data1; // 4 bytes + char data2; // 1 byte + char padding[27]; // 27 bytes of padding +}; // Total size: 32 bytes + + void TestFunction() { + struct TestStruct struct1; // Warning is generated due to excessive padding. +} + + // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. + + // AllowedPad: Default Value: 24 bytes + + Usage: `AllowedPad=` + .. _optin-portability-UnixAPI: optin.portability.UnixAPI >From 403115cd960653a3afe0491d2855d35d377d9312 Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:20:46 -0700 Subject: [PATCH 2/5] Update Checkers.td Changed NotDocumented to HasDocumentation for Padding Checker under performance checker. --- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index 686e5e99f4a62c..c0e4e9a70c2ef3 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -908,7 +908,7 @@ def PaddingChecker : Checker<"Padding">, "24", Released> ]>, - Documentation; + Documentation; } // end: "padding" >From cdef12fa6a6b6c4833bc2017dae9557ee7115c92 Mon Sep 17 00:00:00 2001 From: komalverma04 Date: Sun, 24 Mar 2024 20:39:56 +0530 Subject: [PATCH 3/5] Update checkers.rst Made Indentation consistent and added description on limitation of checker. --- clang/docs/analyzer/checkers.rst | 44 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index 64b09bc6ecd1d8..85f3f33d68bc5d 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,27 +804,37 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding (PaddingChecker) -""" +optin.performance.Padding (C, C++, objC) + Check for excessively padded structs. -.. code-block:: objc - - struct TestStruct { - int data1; // 4 bytes - char data2; // 1 byte - char padding[27]; // 27 bytes of padding -}; // Total size: 32 bytes - - void TestFunction() { - struct TestStruct struct1; // Warning is generated due to excessive padding. -} - - // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. +This checker detects structs with excessive padding, which can lead to wasted memory and decreased performance. Padding bytes are added by compilers to align data within the struct for performance optimization or memory alignment purposes. However, excessive padding can significantly increase the size of the struct without adding useful data, leading to inefficient memory usage, cache misses, and decreased performance. + +.. code-block:: C + + #include + // #pragma pack(1) // Uncomment it to disable structure padding + struct TestStruct { + char data1; // 1 byte + char data2; // 1 byte + int data3; // 4 bytes + }; // Total size: 6 bytes + + int main () { + struct TestStruct struct1; + print("Structure size: %d",sizeof(struct1)); // Structure size: 8 + return 0; + } + +Total memory used is 8 bytes due to structure padding. In this case, padding is of 2 bytes. Padding is done to decrease the number of CPU cycles needed to access data members of the structure; it increases the performance of the
[clang] [llvm] [mlir] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)
https://github.com/arichardson approved this pull request. https://github.com/llvm/llvm-project/pull/85460 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)
https://github.com/AtariDreams requested changes to this pull request. Capitalize the O in ObjC https://github.com/llvm/llvm-project/pull/86411 ___ 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 expresions in unevaluated context in bugprone-inc-dec-in-conditions (PR #85849)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/85849 ___ 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 expresions in unevaluated context in bugprone-inc-dec-in-conditions (PR #85849)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the C/C++ code formatter. https://github.com/llvm/llvm-project/pull/85849 ___ 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 expresions in unevaluated context in bugprone-inc-dec-in-conditions (PR #85849)
https://github.com/PiotrZSL updated https://github.com/llvm/llvm-project/pull/85849 >From 2bd3d15a9e4a9a34bb9edb12815207093c0f3157 Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Tue, 19 Mar 2024 19:09:38 + Subject: [PATCH 1/2] [clang-tidy] Ignore expresions in unevaluated context in bugprone-inc-dec-in-conditions Skip checking for references to variable in unevaluated context, like decltype, static_assert and so on. Closes #85838 --- .../clang-tidy/bugprone/IncDecInConditionsCheck.cpp | 7 ++- clang-tools-extra/docs/ReleaseNotes.rst | 4 .../checkers/bugprone/inc-dec-in-conditions.cpp | 9 + 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp index 16f43128d55e87..c9990cf6d10fd5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp @@ -31,6 +31,10 @@ void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { anyOf(binaryOperator(anyOf(isComparisonOperator(), isLogicalOperator())), cxxOperatorCallExpr(isComparisonOperator(; + auto IsInUnevaluatedContext = + expr(anyOf(hasAncestor(expr(matchers::hasUnevaluatedContext())), + hasAncestor(typeLoc(; + Finder->addMatcher( expr( OperatorMatcher, unless(isExpansionInSystemHeader()), @@ -47,7 +51,8 @@ void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { hasDescendant( expr(unless(equalsBoundNode("operand")), matchers::isStatementIdenticalToBoundNode( - "operand")) + "operand"), + unless(IsInUnevaluatedContext)) .bind("second") .bind("operator"))), this); diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 44680f79de6f54..8803be56d4fd1a 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -132,6 +132,10 @@ Changes in existing checks ` check by detecting side effect from calling a method with non-const reference parameters. +- Improved :doc:`bugprone-inc-dec-in-conditions + ` check to ignore code + within unevaluated contexts, such as ``decltype``. + - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion ` check by eliminating false positives resulting from direct usage of bitwise operators diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp index 82af039973c3bb..a9cb27a47f35b5 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp @@ -68,3 +68,12 @@ bool doubleCheck(Container x) { // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: decrementing and referencing a variable in a complex condition can cause unintended side-effects due to C++'s order of evaluation, consider moving the modification outside of the condition to avoid misunderstandings [bugprone-inc-dec-in-conditions] // CHECK-MESSAGES: :[[@LINE-2]]:31: warning: incrementing and referencing a variable in a complex condition can cause unintended side-effects due to C++'s order of evaluation, consider moving the modification outside of the condition to avoid misunderstandings [bugprone-inc-dec-in-conditions] } + +namespace PR85838 { + void test() + { +auto foo = 0; +auto bar = 0; +if (++foo < static_cast(bar)) {} + } +} >From f8e1862b5e1bec5af8f71bcddb6ef44169f65ffa Mon Sep 17 00:00:00 2001 From: Piotr Zegar Date: Sun, 24 Mar 2024 15:43:07 + Subject: [PATCH 2/2] Add checking for unevaluated context also on operand side --- .../clang-tidy/bugprone/IncDecInConditionsCheck.cpp | 1 + .../test/clang-tidy/checkers/bugprone/inc-dec-in-conditions.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp index c9990cf6d10fd5..9b3b01eb026833 100644 --- a/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp @@ -46,6 +46,7 @@ void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { cxxOperatorCallExpr( isPrePostOperator(), hasUnaryOperand(expr().bind("operand", + unless(IsInUnevaluatedContext),
[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)
https://github.com/komalverma04 updated https://github.com/llvm/llvm-project/pull/86411 >From b6ca6f0ef83d03e299d6ee9a8ed9b8044477914e Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:14:44 -0700 Subject: [PATCH 1/4] Update checkers.rst Modification of documentation to demonstrate utilization of AllowedPad within PaddingChecker, along with its use and effects on code analysis. --- clang/docs/analyzer/checkers.rst | 22 -- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index fe211514914272..64b09bc6ecd1d8 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,10 +804,28 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding -" +optin.performance.Padding (PaddingChecker) +""" Check for excessively padded structs. +.. code-block:: objc + + struct TestStruct { + int data1; // 4 bytes + char data2; // 1 byte + char padding[27]; // 27 bytes of padding +}; // Total size: 32 bytes + + void TestFunction() { + struct TestStruct struct1; // Warning is generated due to excessive padding. +} + + // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. + + // AllowedPad: Default Value: 24 bytes + + Usage: `AllowedPad=` + .. _optin-portability-UnixAPI: optin.portability.UnixAPI >From 403115cd960653a3afe0491d2855d35d377d9312 Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:20:46 -0700 Subject: [PATCH 2/4] Update Checkers.td Changed NotDocumented to HasDocumentation for Padding Checker under performance checker. --- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index 686e5e99f4a62c..c0e4e9a70c2ef3 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -908,7 +908,7 @@ def PaddingChecker : Checker<"Padding">, "24", Released> ]>, - Documentation; + Documentation; } // end: "padding" >From cdef12fa6a6b6c4833bc2017dae9557ee7115c92 Mon Sep 17 00:00:00 2001 From: komalverma04 Date: Sun, 24 Mar 2024 20:39:56 +0530 Subject: [PATCH 3/4] Update checkers.rst Made Indentation consistent and added description on limitation of checker. --- clang/docs/analyzer/checkers.rst | 44 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index 64b09bc6ecd1d8..85f3f33d68bc5d 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,27 +804,37 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding (PaddingChecker) -""" +optin.performance.Padding (C, C++, objC) + Check for excessively padded structs. -.. code-block:: objc - - struct TestStruct { - int data1; // 4 bytes - char data2; // 1 byte - char padding[27]; // 27 bytes of padding -}; // Total size: 32 bytes - - void TestFunction() { - struct TestStruct struct1; // Warning is generated due to excessive padding. -} - - // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. +This checker detects structs with excessive padding, which can lead to wasted memory and decreased performance. Padding bytes are added by compilers to align data within the struct for performance optimization or memory alignment purposes. However, excessive padding can significantly increase the size of the struct without adding useful data, leading to inefficient memory usage, cache misses, and decreased performance. + +.. code-block:: C + + #include + // #pragma pack(1) // Uncomment it to disable structure padding + struct TestStruct { + char data1; // 1 byte + char data2; // 1 byte + int data3; // 4 bytes + }; // Total size: 6 bytes + + int main () { + struct TestStruct struct1; + print("Structure size: %d",sizeof(struct1)); // Structure size: 8 + return 0; + } + +Total memory used is 8 bytes due to structure padding. In this case, padding is of 2 bytes. Padding is done to decrease the number of CPU cycles needed to access data members of the structure; it increases the performance of the
[clang] [clang-tools-extra] [libcxx] [clang] Enable sized deallocation by default in C++14 onwards (PR #83774)
https://github.com/wangpc-pp updated https://github.com/llvm/llvm-project/pull/83774 >From f1653805def59bc6eb23052b3ade80c900b4daaa Mon Sep 17 00:00:00 2001 From: wangpc Date: Fri, 14 Jul 2023 10:38:14 +0800 Subject: [PATCH 1/4] [clang] Enable sized deallocation by default in C++14 onwards Since C++14 has been released for about nine years and most standard libraries have implemented sized deallocation functions, it's time to make this feature default again. Differential Revision: https://reviews.llvm.org/D112921 --- .../clangd/unittests/FindTargetTests.cpp | 4 +- .../checkers/misc/new-delete-overloads.cpp| 10 - clang/docs/ReleaseNotes.rst | 5 + clang/include/clang/Driver/Options.td | 5 +- clang/lib/Driver/ToolChains/Clang.cpp | 13 +- clang/lib/Driver/ToolChains/Darwin.cpp| 58 - clang/lib/Driver/ToolChains/Darwin.h | 4 + clang/lib/Driver/ToolChains/ZOS.cpp | 6 + clang/test/AST/ast-dump-expr-json.cpp | 2 +- clang/test/AST/ast-dump-expr.cpp | 2 +- clang/test/AST/ast-dump-stmt-json.cpp | 244 +- clang/test/Analysis/cxxnewexpr-callback.cpp | 4 +- .../basic.stc.dynamic.deallocation/p2.cpp | 2 +- clang/test/CXX/drs/dr292.cpp | 17 +- .../test/CXX/expr/expr.unary/expr.new/p14.cpp | 2 +- .../CodeGenCXX/cxx1y-sized-deallocation.cpp | 10 +- .../CodeGenCXX/cxx1z-aligned-allocation.cpp | 6 +- .../CodeGenCXX/cxx2a-destroying-delete.cpp| 4 +- clang/test/CodeGenCXX/delete-two-arg.cpp | 4 +- clang/test/CodeGenCXX/delete.cpp | 12 +- clang/test/CodeGenCXX/dllimport.cpp | 4 +- clang/test/CodeGenCXX/new.cpp | 6 +- .../coro-aligned-alloc-2.cpp | 2 - .../CodeGenCoroutines/coro-aligned-alloc.cpp | 6 +- clang/test/CodeGenCoroutines/coro-alloc.cpp | 6 +- clang/test/CodeGenCoroutines/coro-cleanup.cpp | 6 +- clang/test/CodeGenCoroutines/coro-dealloc.cpp | 2 - clang/test/CodeGenCoroutines/coro-gro.cpp | 3 +- clang/test/CodeGenCoroutines/pr56919.cpp | 9 +- clang/test/Lexer/cxx-features.cpp | 20 +- clang/test/PCH/cxx1z-aligned-alloc.cpp| 10 +- clang/test/SemaCXX/MicrosoftExtensions.cpp| 8 +- .../SemaCXX/builtin-operator-new-delete.cpp | 2 +- .../test/SemaCXX/cxx1y-sized-deallocation.cpp | 2 +- .../unavailable_aligned_allocation.cpp| 15 +- .../StaticAnalyzer/CallEventTest.cpp | 2 +- clang/www/cxx_status.html | 11 +- .../support.dynamic/libcpp_deallocate.sh.cpp | 3 + .../sized_delete_array14.pass.cpp | 8 +- .../new.delete.single/sized_delete14.pass.cpp | 8 +- 40 files changed, 436 insertions(+), 111 deletions(-) diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp index 0af6036734ba53..1b7b96281dfaa5 100644 --- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp @@ -839,7 +839,9 @@ TEST_F(TargetDeclTest, OverloadExpr) { [[delete]] x; } )cpp"; - EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept"); + // Sized deallocation is enabled by default in C++14 onwards. + EXPECT_DECLS("CXXDeleteExpr", + "void operator delete(void *, unsigned long) noexcept"); } TEST_F(TargetDeclTest, DependentExprs) { diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp index 78f021144b2e19..f86fe8a4c5b14f 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp @@ -12,16 +12,6 @@ struct S { // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope void *operator new(size_t size) noexcept(false); -struct T { - // Sized deallocations are not enabled by default, and so this new/delete pair - // does not match. However, we expect only one warning, for the new, because - // the operator delete is a placement delete and we do not warn on mismatching - // placement operations. - // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' has no matching declaration of 'operator delete' at the same scope - void *operator new(size_t size) noexcept; - void operator delete(void *ptr, size_t) noexcept; // ok only if sized deallocation is enabled -}; - struct U { void *operator new(size_t size) noexcept; void operator delete(void *ptr) noexcept; diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index d6e179ca9d6904..489679d8c0c681 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -83,6 +83,11 @@
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
https://github.com/5chmidti edited 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); 5chmidti wrote: The location of `TopCall` may be inside a header, so this include would be in the wrong file. Please use `createIncludeInsertion(Match.SourceManager->getFileID(TopCall->getBeginLoc()), "")` 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,65 @@ +//===--- MinMaxUseInitializerListCheck.h - clang-tidy ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_MINMAXUSEINITIALIZERLISTCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_MINMAXUSEINITIALIZERLISTCHECK_H + +#include "../ClangTidyCheck.h" +#include "../utils/IncludeInserter.h" + +namespace clang::tidy::modernize { + +/// Replaces chained ``std::min`` and ``std::max`` calls with a initializer list 5chmidti wrote: `chained` sound like statement after statement. I think `nested` sounds better, wdyt? Also: `an initializer list` instead of `a initializer list` (same in release notes and check docs). Of course, chained `min`/`max` calls could also be detected, but that may be better left for a follow-up pr. 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), 5chmidti wrote: You can use `CharSourceRange::getTokenRange(TopCall->getSourceRange())` here. You can actually omit the `CharSourceRange::getTokenRange` as well, your tests pass fine as well. (Unless there was a reason you used `getTokenRange`, then there would be a test missing for that case) 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); 5chmidti wrote: Add `const` 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") 5chmidti wrote: Please add `'` quotes around the `std::%0` and `%1` 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,138 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::max"), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("maxCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + hasAnyArgument(callExpr(callee(functionDecl(hasName("::std::min"), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("minCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const auto *MaxCall = Result.Nodes.getNodeAs("maxCall"); + const auto *MinCall = Result.Nodes.getNodeAs("minCall"); + + const CallExpr *TopCall = MaxCall ? MaxCall : MinCall; + if (!TopCall) { +return; + } + const QualType ResultType = + TopCall->getDirectCallee()->getReturnType().getNonReferenceType(); + + const Expr *FirstArg = nullptr; + const Expr *LastArg = nullptr; + std::vector Args; + findArgs(TopCall, , , Args); + + if (!FirstArg || !LastArg || Args.size() <= 2) { +return; + } + + std::string ReplacementText = "{"; + for (const Expr *Arg : Args) { +QualType ArgType = Arg->getType(); +bool CastNeeded = +ArgType.getCanonicalType() != ResultType.getCanonicalType(); + +if (CastNeeded) + ReplacementText += "static_cast<" + ResultType.getAsString() + ">("; 5chmidti wrote: When using template argument deduction, conflicting types are deduced -> compile-time error, but when you explicitly specify the template arg for `min`/`max`, then you would need a cast `std::min(0U, 0.0);` And when the user has already cast one arg, then `ArgType.getCanonicalType` will already equal the result type. To catch the `std::min(0U, 0.0);` pattern, you probably want to use `const QualType ArgType = Arg->IgnoreImpCasts()->getType();` https://godbolt.org/z/onMv71bfY 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); 5chmidti wrote: If the type is already on the right-hand-side, then you can use `auto` to declare the variable. 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); 5chmidti wrote: You are repeating yourself a lot here, please add a variable like `const auto callsStdMax = callee(functionDecl(hasName("::std::max")));` for `min` and `max`. 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
@@ -0,0 +1,199 @@ +//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "MinMaxUseInitializerListCheck.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +MinMaxUseInitializerListCheck::MinMaxUseInitializerListCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + Inserter(Options.getLocalOrGlobal("IncludeStyle", +utils::IncludeSorter::IS_LLVM), + areDiagsSelfContained()) {} + +void MinMaxUseInitializerListCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "IncludeStyle", Inserter.getStyle()); +} + +void MinMaxUseInitializerListCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::max"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::max"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::max")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::max"))) + .bind("topCall"), + this); + + Finder->addMatcher( + callExpr( + callee(functionDecl(hasName("::std::min"))), + anyOf(hasArgument( +0, callExpr(callee(functionDecl(hasName("::std::min"), +hasArgument( +1, callExpr(callee(functionDecl(hasName("::std::min")), + unless( + hasParent(callExpr(callee(functionDecl(hasName("::std::min"))) + .bind("topCall"), + this); +} + +void MinMaxUseInitializerListCheck::registerPPCallbacks( +const SourceManager , Preprocessor *PP, Preprocessor *ModuleExpanderPP) { + Inserter.registerPreprocessor(PP); +} + +void MinMaxUseInitializerListCheck::check( +const MatchFinder::MatchResult ) { + const CallExpr *TopCall = Match.Nodes.getNodeAs("topCall"); + MinMaxUseInitializerListCheck::FindArgsResult Result = + findArgs(Match, TopCall); + + if (!Result.First || !Result.Last || Result.Args.size() <= 2) { +return; + } + + std::string ReplacementText = generateReplacement(Match, TopCall, Result); + + diag(TopCall->getBeginLoc(), + "do not use nested std::%0 calls, use %1 instead") + << TopCall->getDirectCallee()->getName() << ReplacementText + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(TopCall->getBeginLoc(), +TopCall->getEndLoc()), + ReplacementText) + << Inserter.createMainFileIncludeInsertion(""); +} + +MinMaxUseInitializerListCheck::FindArgsResult +MinMaxUseInitializerListCheck::findArgs(const MatchFinder::MatchResult , +const CallExpr *Call) { + FindArgsResult Result; + Result.First = nullptr; + Result.Last = nullptr; + Result.Compare = nullptr; + + if (Call->getNumArgs() > 2) { +auto ArgIterator = Call->arguments().begin(); +std::advance(ArgIterator, 2); +Result.Compare = *ArgIterator; + } + + for (const Expr *Arg : Call->arguments()) { +if (!Result.First) + Result.First = Arg; + +const CallExpr *InnerCall = dyn_cast(Arg); +if (InnerCall && InnerCall->getDirectCallee() && +InnerCall->getDirectCallee()->getNameAsString() == +Call->getDirectCallee()->getNameAsString()) { + FindArgsResult InnerResult = findArgs(Match, InnerCall); + + bool processInnerResult = false; + + if (!Result.Compare && !InnerResult.Compare) +processInnerResult = true; + else if (Result.Compare && InnerResult.Compare && + Lexer::getSourceText(CharSourceRange::getTokenRange( +Result.Compare->getSourceRange()), +*Match.SourceManager, +Match.Context->getLangOpts()) == + Lexer::getSourceText( + CharSourceRange::getTokenRange( + InnerResult.Compare->getSourceRange()), + *Match.SourceManager, Match.Context->getLangOpts())) +processInnerResult = true; + + if (processInnerResult) { +Result.Args.insert(Result.Args.end(), InnerResult.Args.begin(), + InnerResult.Args.end()); +continue; + } +} + +if (Arg == Result.Compare) + continue; +
[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
https://github.com/5chmidti requested changes to this pull request. Going in the right direction, but some things still have to be resolved or cleaned up. Add a few more test (these are the ones I tried locally): ```c++ template struct initializer_list { initializer_list()=default; initializer_list(T*,int){} }; template< class T > const T& max(initializer_list list); template< class T, class Compare > const T& max(initializer_list list, Compare comp); template< class T > const T& min(initializer_list list); template< class T, class Compare > const T& min(initializer_list list, Compare comp); ... int max2b = std::max(std::max(std::max(1, 2), std::max(3, 4)), std::max(std::max(5, 6), std::max(7, 8))); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use nested std::max calls, use std::max({1, 2, 3, 4, 5, 6, 7, 8}) instead [modernize-min-max-use-initializer-list] // CHECK-FIXES: int max2b = std::max({1, 2, 3, 4, 5, 6, 7, 8}); int max2c = std::max(std::max(1, std::max(2, 3)), 4); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use nested std::max calls, use std::max({1, 2, 3, 4}) instead [modernize-min-max-use-initializer-list] // CHECK-FIXES: int max2c = std::max({1, 2, 3, 4}); int max2d = std::max(std::max({1, 2, 3}), 4); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use nested std::max calls, use std::max({1, 2, 3, 4}) instead [modernize-min-max-use-initializer-list] // CHECK-FIXES: int max2d = std::max({1, 2, 3, 4}); int max2e = std::max(1, max(2, max(3, 4))); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use nested std::max calls, use std::max({1, 2, 3, 4}) instead [modernize-min-max-use-initializer-list] // CHECK-FIXES: int max2e = std::max({1, 2, 3, 4}); ``` In the above tests, `max2b` and `max2d` fail, which IMO should work, `max2b` especially. And please add some tests with type aliases. My quick test with templates also tells me that they are currently unsupported: ```c++ template void foo(T a, T b, T c){ auto v = std::max(a, std::max(b, c)); } ``` 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-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)
https://github.com/5chmidti edited 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] [HLSL] remove double impelementation of log, sin, trunc intrinsics (PR #86440)
llvmbot wrote: @llvm/pr-subscribers-backend-x86 @llvm/pr-subscribers-clang Author: Andrii Levitskiy (aabysswalker) Changes This change removes the log, log2, log10, sin, trunc intrinsics with parameters of type double as it is not available in the DCX compiler. https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log2 https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log10 https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-sin https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-trunc Closes #86189 --- Full diff: https://github.com/llvm/llvm-project/pull/86440.diff 1 Files Affected: - (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (-45) ``diff diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index 5e703772b7ee4f..90e115521e02f6 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -737,15 +737,6 @@ float3 log(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) float4 log(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double log(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double2 log(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double3 log(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double4 log(double4); - //===--===// // log10 builtins //===--===// @@ -779,15 +770,6 @@ float3 log10(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) float4 log10(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double log10(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double2 log10(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double3 log10(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double4 log10(double4); - //===--===// // log2 builtins //===--===// @@ -821,15 +803,6 @@ float3 log2(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) float4 log2(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double log2(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double2 log2(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double3 log2(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double4 log2(double4); - //===--===// // mad builtins //===--===// @@ -1393,15 +1366,6 @@ float3 sin(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) float4 sin(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double sin(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double2 sin(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double3 sin(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double4 sin(double4); - //===--===// // sqrt builtins //===--===// @@ -1450,15 +1414,6 @@ float3 trunc(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) float4 trunc(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double trunc(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double2 trunc(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double3 trunc(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double4 trunc(double4); - //===--===// // Wave* builtins //===--===// `` https://github.com/llvm/llvm-project/pull/86440 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] remove double impelementation of log, sin, trunc intrinsics (PR #86440)
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/86440 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] remove double impelementation of log, sin, trunc intrinsics (PR #86440)
https://github.com/aabysswalker created https://github.com/llvm/llvm-project/pull/86440 This change removes the log, log2, log10, sin, trunc intrinsics with parameters of type double as it is not available in the DCX compiler. https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log2 https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log10 https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-sin https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-trunc Closes #86189 >From 417b26ffeabf7ec2e99ee28f68b1c38d92e73bf1 Mon Sep 17 00:00:00 2001 From: aabysswalker Date: Sun, 24 Mar 2024 17:13:03 +0200 Subject: [PATCH] Removes the log, sin, trunc intrinsics with parameters of type double as it is not available in the DXC. --- clang/lib/Headers/hlsl/hlsl_intrinsics.h | 45 1 file changed, 45 deletions(-) diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index 5e703772b7ee4f..90e115521e02f6 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -737,15 +737,6 @@ float3 log(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) float4 log(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double log(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double2 log(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double3 log(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log) -double4 log(double4); - //===--===// // log10 builtins //===--===// @@ -779,15 +770,6 @@ float3 log10(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) float4 log10(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double log10(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double2 log10(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double3 log10(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log10) -double4 log10(double4); - //===--===// // log2 builtins //===--===// @@ -821,15 +803,6 @@ float3 log2(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) float4 log2(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double log2(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double2 log2(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double3 log2(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_log2) -double4 log2(double4); - //===--===// // mad builtins //===--===// @@ -1393,15 +1366,6 @@ float3 sin(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) float4 sin(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double sin(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double2 sin(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double3 sin(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_sin) -double4 sin(double4); - //===--===// // sqrt builtins //===--===// @@ -1450,15 +1414,6 @@ float3 trunc(float3); _HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) float4 trunc(float4); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double trunc(double); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double2 trunc(double2); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double3 trunc(double3); -_HLSL_BUILTIN_ALIAS(__builtin_elementwise_trunc) -double4 trunc(double4); - //===--===// // Wave* builtins //===--===// ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)
https://github.com/komalverma04 updated https://github.com/llvm/llvm-project/pull/86411 >From b6ca6f0ef83d03e299d6ee9a8ed9b8044477914e Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:14:44 -0700 Subject: [PATCH 1/3] Update checkers.rst Modification of documentation to demonstrate utilization of AllowedPad within PaddingChecker, along with its use and effects on code analysis. --- clang/docs/analyzer/checkers.rst | 22 -- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index fe211514914272..64b09bc6ecd1d8 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,10 +804,28 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding -" +optin.performance.Padding (PaddingChecker) +""" Check for excessively padded structs. +.. code-block:: objc + + struct TestStruct { + int data1; // 4 bytes + char data2; // 1 byte + char padding[27]; // 27 bytes of padding +}; // Total size: 32 bytes + + void TestFunction() { + struct TestStruct struct1; // Warning is generated due to excessive padding. +} + + // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. + + // AllowedPad: Default Value: 24 bytes + + Usage: `AllowedPad=` + .. _optin-portability-UnixAPI: optin.portability.UnixAPI >From 403115cd960653a3afe0491d2855d35d377d9312 Mon Sep 17 00:00:00 2001 From: komalverma04 <114138604+komalverm...@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:20:46 -0700 Subject: [PATCH 2/3] Update Checkers.td Changed NotDocumented to HasDocumentation for Padding Checker under performance checker. --- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index 686e5e99f4a62c..c0e4e9a70c2ef3 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -908,7 +908,7 @@ def PaddingChecker : Checker<"Padding">, "24", Released> ]>, - Documentation; + Documentation; } // end: "padding" >From cdef12fa6a6b6c4833bc2017dae9557ee7115c92 Mon Sep 17 00:00:00 2001 From: komalverma04 Date: Sun, 24 Mar 2024 20:39:56 +0530 Subject: [PATCH 3/3] Update checkers.rst Made Indentation consistent and added description on limitation of checker. --- clang/docs/analyzer/checkers.rst | 44 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst index 64b09bc6ecd1d8..85f3f33d68bc5d 100644 --- a/clang/docs/analyzer/checkers.rst +++ b/clang/docs/analyzer/checkers.rst @@ -804,27 +804,37 @@ Check for performance anti-patterns when using Grand Central Dispatch. .. _optin-performance-Padding: -optin.performance.Padding (PaddingChecker) -""" +optin.performance.Padding (C, C++, objC) + Check for excessively padded structs. -.. code-block:: objc - - struct TestStruct { - int data1; // 4 bytes - char data2; // 1 byte - char padding[27]; // 27 bytes of padding -}; // Total size: 32 bytes - - void TestFunction() { - struct TestStruct struct1; // Warning is generated due to excessive padding. -} - - // Reports are only generated if the excessive padding exceeds 'AllowedPad' in bytes. +This checker detects structs with excessive padding, which can lead to wasted memory and decreased performance. Padding bytes are added by compilers to align data within the struct for performance optimization or memory alignment purposes. However, excessive padding can significantly increase the size of the struct without adding useful data, leading to inefficient memory usage, cache misses, and decreased performance. + +.. code-block:: C + + #include + // #pragma pack(1) // Uncomment it to disable structure padding + struct TestStruct { + char data1; // 1 byte + char data2; // 1 byte + int data3; // 4 bytes + }; // Total size: 6 bytes + + int main () { + struct TestStruct struct1; + print("Structure size: %d",sizeof(struct1)); // Structure size: 8 + return 0; + } + +Total memory used is 8 bytes due to structure padding. In this case, padding is of 2 bytes. Padding is done to decrease the number of CPU cycles needed to access data members of the structure; it increases the performance of the
[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)
@@ -6375,12 +6383,16 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { ImmediateCallVisitor V(getASTContext()); if (!NestedDefaultChecking) V.TraverseDecl(Field); - if (V.HasImmediateCalls) { + if (V.HasImmediateCalls || InLifetimeExtendingContext) { ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, CurContext}; ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = NestedDefaultChecking; +// Pass down lifetime extending flag, and collect temporaries in +// CreateMaterializeTemporaryExpr when we rewrite the call argument. +keepInLifetimeExtendingContext(); +keepInMaterializeTemporaryObjectContext(); yronglin wrote: I try to extend lifetime of the `MaterializedTemporaryExpr`s in `CXXDefaultInitExpr`, but looking from the generated IR, `MaterializedTemporaryExpr ::setExtendingDecl` does not take effect. I think some modifications may be needed in CodeGen. https://github.com/llvm/llvm-project/pull/76361 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improved --verify-config when using literal style in config file (PR #85591)
@@ -454,52 +454,31 @@ static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n"; static bool verifyChecks(const StringSet<> , StringRef CheckGlob, StringRef Source) { - llvm::StringRef Cur, Rest; + GlobList Globs(CheckGlob); bool AnyInvalid = false; - for (std::tie(Cur, Rest) = CheckGlob.split(','); - !(Cur.empty() && Rest.empty()); std::tie(Cur, Rest) = Rest.split(',')) { -Cur = Cur.trim(); -if (Cur.empty()) + for (const auto : Globs.getItems()) { +const llvm::Regex = Item.Regex; +const llvm::StringRef Text = Item.Text; SimplyDanny wrote: Fine from my point of view to inline both of these variables as it doesn't improve much to have them. If you insist to keep them, use them wherever `Item.` appears. https://github.com/llvm/llvm-project/pull/85591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improved --verify-config when using literal style in config file (PR #85591)
@@ -454,52 +454,31 @@ static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n"; static bool verifyChecks(const StringSet<> , StringRef CheckGlob, StringRef Source) { - llvm::StringRef Cur, Rest; + GlobList Globs(CheckGlob); bool AnyInvalid = false; - for (std::tie(Cur, Rest) = CheckGlob.split(','); - !(Cur.empty() && Rest.empty()); std::tie(Cur, Rest) = Rest.split(',')) { -Cur = Cur.trim(); -if (Cur.empty()) + for (const auto : Globs.getItems()) { +const llvm::Regex = Item.Regex; +const llvm::StringRef Text = Item.Text; +if (Text.starts_with("clang-diagnostic")) continue; -Cur.consume_front("-"); -if (Cur.starts_with("clang-diagnostic")) - continue; -if (Cur.contains('*')) { - SmallString<128> RegexText("^"); - StringRef MetaChars("()^$|*+?.[]\\{}"); - for (char C : Cur) { -if (C == '*') - RegexText.push_back('.'); -else if (MetaChars.contains(C)) - RegexText.push_back('\\'); -RegexText.push_back(C); - } - RegexText.push_back('$'); - llvm::Regex Glob(RegexText); - std::string Error; - if (!Glob.isValid(Error)) { -AnyInvalid = true; -llvm::WithColor::error(llvm::errs(), Source) -<< "building check glob '" << Cur << "' " << Error << "'\n"; -continue; - } - if (llvm::none_of(AllChecks.keys(), -[](StringRef S) { return Glob.match(S); })) { -AnyInvalid = true; +if (llvm::none_of(AllChecks.keys(), [](StringRef S) { + llvm::errs() << S << '\n'; + return Reg.match(S); +})) { + AnyInvalid = true; + if (Item.Text.contains('*')) SimplyDanny wrote: Previously this came before the checks for matches in line 466. Seems like the semantic has so changed slightly if only performance-wise, hasn't it? https://github.com/llvm/llvm-project/pull/85591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improved --verify-config when using literal style in config file (PR #85591)
@@ -454,52 +454,31 @@ static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n"; static bool verifyChecks(const StringSet<> , StringRef CheckGlob, StringRef Source) { - llvm::StringRef Cur, Rest; + GlobList Globs(CheckGlob); bool AnyInvalid = false; - for (std::tie(Cur, Rest) = CheckGlob.split(','); - !(Cur.empty() && Rest.empty()); std::tie(Cur, Rest) = Rest.split(',')) { -Cur = Cur.trim(); -if (Cur.empty()) + for (const auto : Globs.getItems()) { +const llvm::Regex = Item.Regex; +const llvm::StringRef Text = Item.Text; +if (Text.starts_with("clang-diagnostic")) continue; -Cur.consume_front("-"); -if (Cur.starts_with("clang-diagnostic")) - continue; -if (Cur.contains('*')) { - SmallString<128> RegexText("^"); - StringRef MetaChars("()^$|*+?.[]\\{}"); - for (char C : Cur) { -if (C == '*') - RegexText.push_back('.'); -else if (MetaChars.contains(C)) - RegexText.push_back('\\'); -RegexText.push_back(C); - } - RegexText.push_back('$'); - llvm::Regex Glob(RegexText); - std::string Error; - if (!Glob.isValid(Error)) { -AnyInvalid = true; -llvm::WithColor::error(llvm::errs(), Source) -<< "building check glob '" << Cur << "' " << Error << "'\n"; -continue; - } - if (llvm::none_of(AllChecks.keys(), -[](StringRef S) { return Glob.match(S); })) { -AnyInvalid = true; +if (llvm::none_of(AllChecks.keys(), [](StringRef S) { + llvm::errs() << S << '\n'; SimplyDanny wrote: Is this output intended? https://github.com/llvm/llvm-project/pull/85591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improved --verify-config when using literal style in config file (PR #85591)
@@ -19,12 +19,17 @@ static bool consumeNegativeIndicator(StringRef ) { return GlobList.consume_front("-"); } -// Converts first glob from the comma-separated list of globs to Regex and -// removes it and the trailing comma from the GlobList. -static llvm::Regex consumeGlob(StringRef ) { +// Extract the first glob from the comma-separated list of globs SimplyDanny wrote: ```suggestion // Extracts the first glob from the comma-separated list of globs, ``` https://github.com/llvm/llvm-project/pull/85591 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)
https://github.com/Endilll updated https://github.com/llvm/llvm-project/pull/84184 >From 23f4208fb9978370f59cae16db0747acb3e2c906 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Wed, 6 Mar 2024 18:01:35 +0300 Subject: [PATCH 1/7] [clang] Factor out OpenACC part of `Sema` This patch moves OpenACC parts of `Sema` into a separate class `SemaOpenACC` that is placed in a separate header `Sema/SemaOpenACC.h`. This patch is intended to be a model of factoring things out of `Sema`, so I picked a small OpenACC part. Goals are the following: 1) Split `Sema` into manageable parts. 2) Make dependencies between parts visible. 3) Improve Clang development cycle by avoiding recompiling unrelated parts of the compiler. 4) Avoid compile-time regressions. 5) Avoid notational regressions in the code that uses Sema. --- clang/include/clang/Sema/Sema.h| 77 -- clang/include/clang/Sema/SemaOpenACC.h | 68 +++ clang/lib/Parse/ParseOpenACC.cpp | 22 clang/lib/Sema/Sema.cpp| 4 +- clang/lib/Sema/SemaOpenACC.cpp | 44 --- clang/lib/Sema/TreeTransform.h | 11 ++-- 6 files changed, 137 insertions(+), 89 deletions(-) create mode 100644 clang/include/clang/Sema/SemaOpenACC.h diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f3d3a57104ee07..932676c52b1f30 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -183,6 +183,7 @@ class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; +class SemaOpenACC; class StandardConversionSequence; class Stmt; class StringLiteral; @@ -466,9 +467,8 @@ class Sema final { // 37. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp) // 38. CUDA (SemaCUDA.cpp) // 39. HLSL Constructs (SemaHLSL.cpp) - // 40. OpenACC Constructs (SemaOpenACC.cpp) - // 41. OpenMP Directives and Clauses (SemaOpenMP.cpp) - // 42. SYCL Constructs (SemaSYCL.cpp) + // 40. OpenMP Directives and Clauses (SemaOpenMP.cpp) + // 41. SYCL Constructs (SemaSYCL.cpp) /// \name Semantic Analysis /// Implementations are in Sema.cpp @@ -1200,6 +1200,27 @@ class Sema final { // // + /// \name Sema Components + /// Parts of Sema + ///@{ + + // Just in this section, private members are followed by public, because + // C++ requires us to create (private) objects before (public) references. + +private: + std::unique_ptr OpenACCPtr; + +public: + SemaOpenACC + + ///@} + + // + // + // - + // + // + /// \name C++ Access Control /// Implementations are in SemaAccess.cpp ///@{ @@ -13309,56 +13330,6 @@ class Sema final { // // - /// \name OpenACC Constructs - /// Implementations are in SemaOpenACC.cpp - ///@{ - -public: - /// Called after parsing an OpenACC Clause so that it can be checked. - bool ActOnOpenACCClause(OpenACCClauseKind ClauseKind, - SourceLocation StartLoc); - - /// Called after the construct has been parsed, but clauses haven't been - /// parsed. This allows us to diagnose not-implemented, as well as set up any - /// state required for parsing the clauses. - void ActOnOpenACCConstruct(OpenACCDirectiveKind K, SourceLocation StartLoc); - - /// Called after the directive, including its clauses, have been parsed and - /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES - /// happen before any associated declarations or statements have been parsed. - /// This function is only called when we are parsing a 'statement' context. - bool ActOnStartOpenACCStmtDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc); - - /// Called after the directive, including its clauses, have been parsed and - /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES - /// happen before any associated declarations or statements have been parsed. - /// This function is only called when we are parsing a 'Decl' context. - bool ActOnStartOpenACCDeclDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc); - /// Called when we encounter an associated statement for our construct, this - /// should check legality of the statement as it appertains to this Construct. - StmtResult ActOnOpenACCAssociatedStmt(OpenACCDirectiveKind K, -StmtResult AssocStmt); - - /// Called after the directive has been completely parsed, including the - /// declaration group or associated statement. - StmtResult ActOnEndOpenACCStmtDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc, - SourceLocation EndLoc, - StmtResult AssocStmt); - /// Called after the directive has been
[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)
Endilll wrote: I added convenience functions to access `ASTContext` and other widely used facilities of `Sema` to `SemaOpenACC`. I intentionally didn't go full base class approach, saving this option for the future. https://github.com/llvm/llvm-project/pull/84184 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)
github-actions[bot] wrote: :white_check_mark: With the latest revision this PR passed the Python code formatter. https://github.com/llvm/llvm-project/pull/84184 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)
https://github.com/Endilll updated https://github.com/llvm/llvm-project/pull/84184 >From 23f4208fb9978370f59cae16db0747acb3e2c906 Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Wed, 6 Mar 2024 18:01:35 +0300 Subject: [PATCH 1/6] [clang] Factor out OpenACC part of `Sema` This patch moves OpenACC parts of `Sema` into a separate class `SemaOpenACC` that is placed in a separate header `Sema/SemaOpenACC.h`. This patch is intended to be a model of factoring things out of `Sema`, so I picked a small OpenACC part. Goals are the following: 1) Split `Sema` into manageable parts. 2) Make dependencies between parts visible. 3) Improve Clang development cycle by avoiding recompiling unrelated parts of the compiler. 4) Avoid compile-time regressions. 5) Avoid notational regressions in the code that uses Sema. --- clang/include/clang/Sema/Sema.h| 77 -- clang/include/clang/Sema/SemaOpenACC.h | 68 +++ clang/lib/Parse/ParseOpenACC.cpp | 22 clang/lib/Sema/Sema.cpp| 4 +- clang/lib/Sema/SemaOpenACC.cpp | 44 --- clang/lib/Sema/TreeTransform.h | 11 ++-- 6 files changed, 137 insertions(+), 89 deletions(-) create mode 100644 clang/include/clang/Sema/SemaOpenACC.h diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index f3d3a57104ee07..932676c52b1f30 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -183,6 +183,7 @@ class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; +class SemaOpenACC; class StandardConversionSequence; class Stmt; class StringLiteral; @@ -466,9 +467,8 @@ class Sema final { // 37. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp) // 38. CUDA (SemaCUDA.cpp) // 39. HLSL Constructs (SemaHLSL.cpp) - // 40. OpenACC Constructs (SemaOpenACC.cpp) - // 41. OpenMP Directives and Clauses (SemaOpenMP.cpp) - // 42. SYCL Constructs (SemaSYCL.cpp) + // 40. OpenMP Directives and Clauses (SemaOpenMP.cpp) + // 41. SYCL Constructs (SemaSYCL.cpp) /// \name Semantic Analysis /// Implementations are in Sema.cpp @@ -1200,6 +1200,27 @@ class Sema final { // // + /// \name Sema Components + /// Parts of Sema + ///@{ + + // Just in this section, private members are followed by public, because + // C++ requires us to create (private) objects before (public) references. + +private: + std::unique_ptr OpenACCPtr; + +public: + SemaOpenACC + + ///@} + + // + // + // - + // + // + /// \name C++ Access Control /// Implementations are in SemaAccess.cpp ///@{ @@ -13309,56 +13330,6 @@ class Sema final { // // - /// \name OpenACC Constructs - /// Implementations are in SemaOpenACC.cpp - ///@{ - -public: - /// Called after parsing an OpenACC Clause so that it can be checked. - bool ActOnOpenACCClause(OpenACCClauseKind ClauseKind, - SourceLocation StartLoc); - - /// Called after the construct has been parsed, but clauses haven't been - /// parsed. This allows us to diagnose not-implemented, as well as set up any - /// state required for parsing the clauses. - void ActOnOpenACCConstruct(OpenACCDirectiveKind K, SourceLocation StartLoc); - - /// Called after the directive, including its clauses, have been parsed and - /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES - /// happen before any associated declarations or statements have been parsed. - /// This function is only called when we are parsing a 'statement' context. - bool ActOnStartOpenACCStmtDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc); - - /// Called after the directive, including its clauses, have been parsed and - /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES - /// happen before any associated declarations or statements have been parsed. - /// This function is only called when we are parsing a 'Decl' context. - bool ActOnStartOpenACCDeclDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc); - /// Called when we encounter an associated statement for our construct, this - /// should check legality of the statement as it appertains to this Construct. - StmtResult ActOnOpenACCAssociatedStmt(OpenACCDirectiveKind K, -StmtResult AssocStmt); - - /// Called after the directive has been completely parsed, including the - /// declaration group or associated statement. - StmtResult ActOnEndOpenACCStmtDirective(OpenACCDirectiveKind K, - SourceLocation StartLoc, - SourceLocation EndLoc, - StmtResult AssocStmt); - /// Called after the directive has been
[clang] Match against all plugins when parsing microsoft attributes (PR #86426)
@@ -5061,11 +5061,15 @@ void Parser::ParseMicrosoftAttributes(ParsedAttributes ) { IdentifierInfo *II = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); ConsumeToken(); -ParsedAttr::Kind AttrKind = -ParsedAttr::getParsedKind(II, nullptr, ParsedAttr::AS_Microsoft); + // For HLSL we want to handle all attributes, but for MSVC compat, we // silently ignore unknown Microsoft attributes. -if (getLangOpts().HLSL || AttrKind != ParsedAttr::UnknownAttribute) { +AttributeCommonInfo Info{II, NameLoc, + AttributeCommonInfo::Form::Microsoft()}; +const ParsedAttrInfo = ParsedAttrInfo::get(Info); +if (getLangOpts().HLSL || +AttrInfo.hasSpelling(AttributeCommonInfo::AS_Microsoft, + II->getName())) { Sirraide wrote: Hmm, I can’t find a place where we’re doing anything like this here for the other syntaxes, so I’m not sure this is the right approach. `hasAttribute()` from `clang/Basic/Attributes.h` seems to do what you’re trying to do here; have you tried using that one? https://github.com/llvm/llvm-project/pull/86426 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Match against all plugins when parsing microsoft attributes (PR #86426)
https://github.com/Sirraide edited https://github.com/llvm/llvm-project/pull/86426 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits