From ffb5831fceac7dd0af461f0abd0bd66cdc6e77a8 Mon Sep 17 00:00:00 2001 From: Connector Switch Date: Sat, 8 Nov 2025 20:39:26 +0800 Subject: [PATCH 01/18] [libc] add various macros relate to *ADDR* (#164830) This patch adds 4 macros in the `netinet/in.h` header, as specified by POSIX standards. --- libc/include/llvm-libc-macros/netinet-in-macros.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/libc/include/llvm-libc-macros/netinet-in-macros.h b/libc/include/llvm-libc-macros/netinet-in-macros.h index fb7564cee9e80..2011c34e288cd 100644 --- a/libc/include/llvm-libc-macros/netinet-in-macros.h +++ b/libc/include/llvm-libc-macros/netinet-in-macros.h @@ -9,6 +9,9 @@ #ifndef LLVM_LIBC_MACROS_NETINET_IN_MACROS_H #define LLVM_LIBC_MACROS_NETINET_IN_MACROS_H +#include "../llvm-libc-types/in_addr_t.h" +#include "__llvm-libc-common.h" + #define IPPROTO_IP 0 #define IPPROTO_ICMP 1 #define IPPROTO_TCP 6 @@ -24,4 +27,10 @@ #define IPV6_LEAVE_GROUP 21 #define IPV6_V6ONLY 26 +#define INADDR_ANY __LLVM_LIBC_CAST(static_cast, in_addr_t, 0x00000000) +#define INADDR_BROADCAST __LLVM_LIBC_CAST(static_cast, in_addr_t, 0xffffffff) + +#define INET_ADDRSTRLEN 16 +#define INET6_ADDRSTRLEN 46 + #endif // LLVM_LIBC_MACROS_NETINET_IN_MACROS_H From a0e222f7c7bc7b6de43391fbbdada8d511004b9c Mon Sep 17 00:00:00 2001 From: Kunqiu Chen Date: Sat, 8 Nov 2025 20:52:19 +0800 Subject: [PATCH 02/18] [SimplifyCFG] Simplify uncond br with icmp & select (#165580) Previously, SimplifyCFG only simplified unconditional branches when they met a pattern (`swicth` -> `icmp` -> `br` -> `phi`) as follows: ```LLVM switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] DEFAULT: %tmp = icmp eq i8 %A, 92 br label %end end: ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] ``` This PR supports a new and more generic pattern (`switch` -> `icmp` -> `select` -> `br` -> `phi` ) to simplify unconditional branches as follows: ```LLVM ; BEFORE case1: switch i32 %x, label %DEFAULT [ i32 0, label %end i32 1, label %case2 ] case2: br label %end DEFAULT: %tmp = icmp eq i32 %x, 2 %val = select i1 %tmp, i32 V3, i32 V4 br label %end end: ... = phi i32 [ V1, %case1 ], [ V2, %case2 ], [ %val, %DEFAULT ] ``` We prefer to split the edge to 'end' so that there are TWO entries of V3/V4 to the PHI, merging the icmp & select into the switch, as follows: ```LLVM ; AFTER case1: switch i32 %x, label %DEFAULT [ i32 0, label %end i32 1, label %case2 i32 2, label %case3 ] case2: br label %end case3: br label %end DEFAULT: br label %end end: ... = phi i32 [ V1, %case1 ], [ V2, %case2 ], [ V3, %case3 ], [ V4, %DEFAULT] ``` Alive2 Proof: https://alive2.llvm.org/ce/z/jYHM4f Promising Optimization Impact: https://github.com/dtcxzyw/llvm-opt-benchmark/pull/3006 --- llvm/lib/Transforms/Utils/SimplifyCFG.cpp | 133 +++++++++++++++--- .../SimplifyCFG/ARM/switch-to-lookup-table.ll | 4 +- .../switch-transformations-no-lut.ll | 5 +- .../Transforms/SimplifyCFG/switch_create.ll | 130 +++++++++++++++++ 4 files changed, 245 insertions(+), 27 deletions(-) diff --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp index 37c048f421f1a..ed2a5c292fa54 100644 --- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp +++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp @@ -302,7 +302,9 @@ class SimplifyCFGOpt { bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI, IRBuilder<> &Builder); - + bool tryToSimplifyUncondBranchWithICmpSelectInIt(ICmpInst *ICI, + SelectInst *Select, + IRBuilder<> &Builder); bool hoistCommonCodeFromSuccessors(Instruction *TI, bool AllInstsEqOnly); bool hoistSuccIdenticalTerminatorToSwitchOrIf( Instruction *TI, Instruction *I1, @@ -5023,16 +5025,65 @@ bool SimplifyCFGOpt::simplifyIndirectBrOnSelect(IndirectBrInst *IBI, /// the PHI, merging the third icmp into the switch. bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( ICmpInst *ICI, IRBuilder<> &Builder) { + // Select == nullptr means we assume that there is a hidden no-op select + // instruction of `_ = select %icmp, true, false` after `%icmp = icmp ...` + return tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, nullptr, Builder); +} + +/// Similar to tryToSimplifyUncondBranchWithICmpInIt, but handle a more generic +/// case. This is called when we find an icmp instruction (a seteq/setne with a +/// constant) and its following select instruction as the only TWO instructions +/// in a block that ends with an uncond branch. We are looking for a very +/// specific pattern that occurs when " +/// if (A == 1) return C1; +/// if (A == 2) return C2; +/// if (A < 3) return C3; +/// return C4; +/// " gets simplified. In this case, we merge the first two "branches of icmp" +/// into a switch, but then the default value goes to an uncond block with a lt +/// icmp and select in it, as InstCombine can not simplify "A < 3" as "A == 2". +/// After SimplifyCFG and other subsequent optimizations (e.g., SCCP), we might +/// get something like: +/// +/// case1: +/// switch i8 %A, label %DEFAULT [ i8 0, label %end i8 1, label %case2 ] +/// case2: +/// br label %end +/// DEFAULT: +/// %tmp = icmp eq i8 %A, 2 +/// %val = select i1 %tmp, i8 C3, i8 C4 +/// br label %end +/// end: +/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ %val, %DEFAULT ] +/// +/// We prefer to split the edge to 'end' so that there are TWO entries of V3/V4 +/// to the PHI, merging the icmp & select into the switch, as follows: +/// +/// case1: +/// switch i8 %A, label %DEFAULT [ +/// i8 0, label %end +/// i8 1, label %case2 +/// i8 2, label %case3 +/// ] +/// case2: +/// br label %end +/// case3: +/// br label %end +/// DEFAULT: +/// br label %end +/// end: +/// _ = phi i8 [ C1, %case1 ], [ C2, %case2 ], [ C3, %case2 ], [ C4, %DEFAULT] +bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt( + ICmpInst *ICI, SelectInst *Select, IRBuilder<> &Builder) { BasicBlock *BB = ICI->getParent(); - // If the block has any PHIs in it or the icmp has multiple uses, it is too - // complex. - if (isa(BB->begin()) || !ICI->hasOneUse()) + // If the block has any PHIs in it or the icmp/select has multiple uses, it is + // too complex. + /// TODO: support multi-phis in succ BB of select's BB. + if (isa(BB->begin()) || !ICI->hasOneUse() || + (Select && !Select->hasOneUse())) return false; - Value *V = ICI->getOperand(0); - ConstantInt *Cst = cast(ICI->getOperand(1)); - // The pattern we're looking for is where our only predecessor is a switch on // 'V' and this block is the default case for the switch. In this case we can // fold the compared value into the switch to simplify things. @@ -5040,8 +5091,36 @@ bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( if (!Pred || !isa(Pred->getTerminator())) return false; + Value *IcmpCond; + ConstantInt *NewCaseVal; + CmpPredicate Predicate; + + // Match icmp X, C + if (!match(ICI, + m_ICmp(Predicate, m_Value(IcmpCond), m_ConstantInt(NewCaseVal)))) + return false; + + Value *SelectCond, *SelectTrueVal, *SelectFalseVal; + Instruction *User; + if (!Select) { + // If Select == nullptr, we can assume that there is a hidden no-op select + // just after icmp + SelectCond = ICI; + SelectTrueVal = Builder.getTrue(); + SelectFalseVal = Builder.getFalse(); + User = ICI->user_back(); + } else { + SelectCond = Select->getCondition(); + // Check if the select condition is the same as the icmp condition. + if (SelectCond != ICI) + return false; + SelectTrueVal = Select->getTrueValue(); + SelectFalseVal = Select->getFalseValue(); + User = Select->user_back(); + } + SwitchInst *SI = cast(Pred->getTerminator()); - if (SI->getCondition() != V) + if (SI->getCondition() != IcmpCond) return false; // If BB is reachable on a non-default case, then we simply know the value of @@ -5063,9 +5142,9 @@ bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( // Ok, the block is reachable from the default dest. If the constant we're // comparing exists in one of the other edges, then we can constant fold ICI // and zap it. - if (SI->findCaseValue(Cst) != SI->case_default()) { + if (SI->findCaseValue(NewCaseVal) != SI->case_default()) { Value *V; - if (ICI->getPredicate() == ICmpInst::ICMP_EQ) + if (Predicate == ICmpInst::ICMP_EQ) V = ConstantInt::getFalse(BB->getContext()); else V = ConstantInt::getTrue(BB->getContext()); @@ -5076,25 +5155,30 @@ bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( return requestResimplify(); } - // The use of the icmp has to be in the 'end' block, by the only PHI node in + // The use of the select has to be in the 'end' block, by the only PHI node in // the block. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); - PHINode *PHIUse = dyn_cast(ICI->user_back()); + PHINode *PHIUse = dyn_cast(User); if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || isa(++BasicBlock::iterator(PHIUse))) return false; - // If the icmp is a SETEQ, then the default dest gets false, the new edge gets - // true in the PHI. - Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); - Constant *NewCst = ConstantInt::getFalse(BB->getContext()); + // If the icmp is a SETEQ, then the default dest gets SelectFalseVal, the new + // edge gets SelectTrueVal in the PHI. + Value *DefaultCst = SelectFalseVal; + Value *NewCst = SelectTrueVal; - if (ICI->getPredicate() == ICmpInst::ICMP_EQ) + if (ICI->getPredicate() == ICmpInst::ICMP_NE) std::swap(DefaultCst, NewCst); - // Replace ICI (which is used by the PHI for the default value) with true or - // false depending on if it is EQ or NE. - ICI->replaceAllUsesWith(DefaultCst); + // Replace Select (which is used by the PHI for the default value) with + // SelectFalseVal or SelectTrueVal depending on if ICI is EQ or NE. + if (Select) { + Select->replaceAllUsesWith(DefaultCst); + Select->eraseFromParent(); + } else { + ICI->replaceAllUsesWith(DefaultCst); + } ICI->eraseFromParent(); SmallVector Updates; @@ -5111,7 +5195,7 @@ bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( NewW = ((uint64_t(*W0) + 1) >> 1); SIW.setSuccessorWeight(0, *NewW); } - SIW.addCase(Cst, NewBB, NewW); + SIW.addCase(NewCaseVal, NewBB, NewW); if (DTU) Updates.push_back({DominatorTree::Insert, Pred, NewBB}); } @@ -8302,13 +8386,18 @@ bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, // If the only instruction in the block is a seteq/setne comparison against a // constant, try to simplify the block. - if (ICmpInst *ICI = dyn_cast(I)) + if (ICmpInst *ICI = dyn_cast(I)) { if (ICI->isEquality() && isa(ICI->getOperand(1))) { ++I; if (I->isTerminator() && tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) return true; + if (isa(I) && I->getNextNode()->isTerminator() && + tryToSimplifyUncondBranchWithICmpSelectInIt(ICI, cast(I), + Builder)) + return true; } + } // See if we can merge an empty landing pad block with another which is // equivalent. diff --git a/llvm/test/Transforms/SimplifyCFG/ARM/switch-to-lookup-table.ll b/llvm/test/Transforms/SimplifyCFG/ARM/switch-to-lookup-table.ll index 6def8f4eeb089..a51b816846cdc 100644 --- a/llvm/test/Transforms/SimplifyCFG/ARM/switch-to-lookup-table.ll +++ b/llvm/test/Transforms/SimplifyCFG/ARM/switch-to-lookup-table.ll @@ -15,8 +15,8 @@ ; DISABLE-NOT: @{{.*}} = private unnamed_addr constant [3 x ptr] [ptr @c1, ptr @c2, ptr @c3] ; ENABLE: @{{.*}} = private unnamed_addr constant [3 x ptr] [ptr @g1, ptr @g2, ptr @g3] ; DISABLE-NOT: @{{.*}} = private unnamed_addr constant [3 x ptr] [ptr @g1, ptr @g2, ptr @g3] -; ENABLE: @{{.*}} = private unnamed_addr constant [3 x ptr] [ptr @f1, ptr @f2, ptr @f3] -; DISABLE-NOT: @{{.*}} = private unnamed_addr constant [3 x ptr] [ptr @f1, ptr @f2, ptr @f3] +; ENABLE: @{{.*}} = private unnamed_addr constant [4 x ptr] [ptr @f1, ptr @f2, ptr @f3, ptr @f4] +; DISABLE-NOT: @{{.*}} = private unnamed_addr constant [4 x ptr] [ptr @f1, ptr @f2, ptr @f3, ptr @f4] target datalayout = "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64" target triple = "armv7a--none-eabi" diff --git a/llvm/test/Transforms/SimplifyCFG/switch-transformations-no-lut.ll b/llvm/test/Transforms/SimplifyCFG/switch-transformations-no-lut.ll index 25267dcc6dbcb..48be76c19e48f 100644 --- a/llvm/test/Transforms/SimplifyCFG/switch-transformations-no-lut.ll +++ b/llvm/test/Transforms/SimplifyCFG/switch-transformations-no-lut.ll @@ -410,13 +410,12 @@ define i1 @single_value_with_mask(i32 %x) { ; OPTNOLUT-NEXT: i32 21, label %[[END]] ; OPTNOLUT-NEXT: i32 48, label %[[END]] ; OPTNOLUT-NEXT: i32 16, label %[[END]] +; OPTNOLUT-NEXT: i32 80, label %[[END]] ; OPTNOLUT-NEXT: ] ; OPTNOLUT: [[DEFAULT]]: -; OPTNOLUT-NEXT: [[CMP:%.*]] = icmp eq i32 [[X]], 80 -; OPTNOLUT-NEXT: [[SEL:%.*]] = select i1 [[CMP]], i1 false, i1 true ; OPTNOLUT-NEXT: br label %[[END]] ; OPTNOLUT: [[END]]: -; OPTNOLUT-NEXT: [[RES:%.*]] = phi i1 [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ [[SEL]], %[[DEFAULT]] ] +; OPTNOLUT-NEXT: [[RES:%.*]] = phi i1 [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ false, %[[ENTRY]] ], [ true, %[[DEFAULT]] ], [ false, %[[ENTRY]] ] ; OPTNOLUT-NEXT: ret i1 [[RES]] ; ; TTINOLUT-LABEL: define i1 @single_value_with_mask( diff --git a/llvm/test/Transforms/SimplifyCFG/switch_create.ll b/llvm/test/Transforms/SimplifyCFG/switch_create.ll index ef5aee68e268e..64016f3a4b97c 100644 --- a/llvm/test/Transforms/SimplifyCFG/switch_create.ll +++ b/llvm/test/Transforms/SimplifyCFG/switch_create.ll @@ -1314,6 +1314,136 @@ if.end: ret void } +define i32 @switch_with_icmp_select_after_it(i32 %x) { +; CHECK-LABEL: @switch_with_icmp_select_after_it( +; CHECK-NEXT: entry: +; CHECK-NEXT: switch i32 [[X:%.*]], label [[DEFAULT:%.*]] [ +; CHECK-NEXT: i32 18, label [[END:%.*]] +; CHECK-NEXT: i32 21, label [[END]] +; CHECK-NEXT: i32 48, label [[END]] +; CHECK-NEXT: i32 16, label [[END]] +; CHECK-NEXT: i32 80, label [[SWITCH_EDGE:%.*]] +; CHECK-NEXT: ] +; CHECK: switch.edge: +; CHECK-NEXT: br label [[END]] +; CHECK: default: +; CHECK-NEXT: br label [[END]] +; CHECK: end: +; CHECK-NEXT: [[RES:%.*]] = phi i32 [ 1, [[ENTRY:%.*]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 3, [[DEFAULT]] ], [ 2, [[SWITCH_EDGE]] ] +; CHECK-NEXT: ret i32 [[RES]] +; +entry: + switch i32 %x, label %default [ + i32 18, label %end + i32 21, label %end + i32 48, label %end + i32 16, label %end + ] +default: + %cmp = icmp eq i32 %x, 80 + ; Create a new switch case BB for case 80. + %sel = select i1 %cmp, i32 2, i32 3 + br label %end +end: + %res = phi i32 [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ %sel, %default ] + ret i32 %res +} + +define i32 @switch_with_icmp_select_after_it2(i32 %x) { +; CHECK-LABEL: @switch_with_icmp_select_after_it2( +; CHECK-NEXT: entry: +; CHECK-NEXT: switch i32 [[X:%.*]], label [[DEFAULT:%.*]] [ +; CHECK-NEXT: i32 18, label [[END:%.*]] +; CHECK-NEXT: i32 21, label [[END]] +; CHECK-NEXT: i32 48, label [[END]] +; CHECK-NEXT: i32 16, label [[END]] +; CHECK-NEXT: i32 80, label [[END]] +; CHECK-NEXT: ] +; CHECK: default: +; CHECK-NEXT: br label [[END]] +; CHECK: end: +; CHECK-NEXT: [[RES:%.*]] = phi i32 [ 1, [[ENTRY:%.*]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 3, [[DEFAULT]] ], [ 1, [[ENTRY]] ] +; CHECK-NEXT: ret i32 [[RES]] +; +entry: + switch i32 %x, label %default [ + i32 18, label %end + i32 21, label %end + i32 48, label %end + i32 16, label %end + ] +default: + %cmp = icmp eq i32 %x, 80 + ; Should not create new case BB + %sel = select i1 %cmp, i32 1, i32 3 + br label %end +end: + %res = phi i32 [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ %sel, %default ] + ret i32 %res +} + +define i32 @switch_with_icmp_select_after_it3(i32 %x) { +; CHECK-LABEL: @switch_with_icmp_select_after_it3( +; CHECK-NEXT: entry: +; CHECK-NEXT: [[CMP:%.*]] = icmp eq i32 [[X:%.*]], 80 +; CHECK-NEXT: [[SEL:%.*]] = select i1 [[CMP]], i32 3, i32 1 +; CHECK-NEXT: ret i32 [[SEL]] +; +entry: + switch i32 %x, label %default [ + i32 18, label %end + i32 21, label %end + i32 48, label %end + i32 16, label %end + ] +default: + %cmp = icmp eq i32 %x, 80 + ; Should not create new case BB + %sel = select i1 %cmp, i32 3, i32 1 + br label %end +end: + %res = phi i32 [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ %sel, %default ] + ret i32 %res +} + +; TODO: support this case (multi-phis). +define i32 @switch_with_icmp_select_after_it_multi_phis(i32 %x) { +; CHECK-LABEL: @switch_with_icmp_select_after_it_multi_phis( +; CHECK-NEXT: entry: +; CHECK-NEXT: switch i32 [[X:%.*]], label [[DEFAULT:%.*]] [ +; CHECK-NEXT: i32 18, label [[END:%.*]] +; CHECK-NEXT: i32 21, label [[END]] +; CHECK-NEXT: i32 48, label [[END]] +; CHECK-NEXT: i32 16, label [[END]] +; CHECK-NEXT: ] +; CHECK: default: +; CHECK-NEXT: [[CMP:%.*]] = icmp eq i32 [[X]], 80 +; CHECK-NEXT: [[SEL:%.*]] = select i1 [[CMP]], i32 2, i32 3 +; CHECK-NEXT: br label [[END]] +; CHECK: end: +; CHECK-NEXT: [[RES1:%.*]] = phi i32 [ 0, [[ENTRY:%.*]] ], [ 0, [[ENTRY]] ], [ 0, [[ENTRY]] ], [ 0, [[ENTRY]] ], [ 100, [[DEFAULT]] ] +; CHECK-NEXT: [[RES2:%.*]] = phi i32 [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ 1, [[ENTRY]] ], [ [[SEL]], [[DEFAULT]] ] +; CHECK-NEXT: [[RES:%.*]] = xor i32 [[RES1]], [[RES2]] +; CHECK-NEXT: ret i32 [[RES]] +; +entry: + switch i32 %x, label %default [ + i32 18, label %end + i32 21, label %end + i32 48, label %end + i32 16, label %end + ] +default: + %cmp = icmp eq i32 %x, 80 + %sel = select i1 %cmp, i32 2, i32 3 + br label %end +end: + %res1 = phi i32 [ 0, %entry ], [ 0, %entry ], [ 0, %entry ], [ 0, %entry ], [ 100, %default ] + %res2 = phi i32 [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ 1, %entry ], [ %sel, %default ] + %res = xor i32 %res1, %res2 + ret i32 %res +} + !0 = !{!"function_entry_count", i32 100} !1 = !{!"branch_weights", i32 6, i32 10} ;. From 21c1b7845b05fb126631b91e7c978a51c3f9eb9a Mon Sep 17 00:00:00 2001 From: hstk30-hw Date: Sat, 8 Nov 2025 21:52:13 +0800 Subject: [PATCH 03/18] fix: C++ empty record with align lead to va_list out of sync (#72197) Fix AArch64 argument passing for C++ empty classes with large explicitly specified alignment reproducer: https://godbolt.org/z/qsze8fqra rel issue: https://github.com/llvm/llvm-project/issues/69872 rel commit: https://github.com/llvm/llvm-project/commit/1711cc930bda8d27e87a2092bd220c18e4600c98 --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/CodeGen/Targets/AArch64.cpp | 9 ++++++--- clang/test/CodeGen/AArch64/args.cpp | 20 ++++++++++++++++++- .../AArch64/struct-coerce-using-ptr.cpp | 10 ++++++---- .../CodeGen/arm64-microsoft-arguments.cpp | 4 ++-- clang/test/CodeGenCXX/aarch64-arguments.cpp | 2 +- clang/test/CodeGenCXX/arm64-darwinpcs.cpp | 2 +- 7 files changed, 36 insertions(+), 12 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 3a4e1fce2511e..6b396e7ba63f3 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -119,6 +119,7 @@ C++ Specific Potentially Breaking Changes ABI Changes in This Version --------------------------- +- Fix AArch64 argument passing for C++ empty classes with large explicitly specified alignment. AST Dumping Potentially Breaking Changes ---------------------------------------- diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp index bb41a14f5d2f3..d42fcd8b3237c 100644 --- a/clang/lib/CodeGen/Targets/AArch64.cpp +++ b/clang/lib/CodeGen/Targets/AArch64.cpp @@ -422,6 +422,12 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadicFn, } // Empty records: + // AAPCS64 does not say that empty records are ignored as arguments, + // but other compilers do so in certain situations, and we copy that behavior. + // Those situations are in fact language-mode-specific, which seems really + // unfortunate, but it's something we just have to accept. If this doesn't + // apply, just fall through to the standard argument-handling path. + // Darwin overrides the psABI here to ignore all empty records in all modes. uint64_t Size = getContext().getTypeSize(Ty); bool IsEmpty = isEmptyRecord(getContext(), Ty, true); if (!Ty->isSVESizelessBuiltinType() && (IsEmpty || Size == 0)) { @@ -434,9 +440,6 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadicFn, // behaviour here. if (Size == 0) return ABIArgInfo::getIgnore(); - - // Otherwise, they are passed as if they have a size of 1 byte. - return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); } // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. diff --git a/clang/test/CodeGen/AArch64/args.cpp b/clang/test/CodeGen/AArch64/args.cpp index 3cb62d3119ecf..c284316a5e1b4 100644 --- a/clang/test/CodeGen/AArch64/args.cpp +++ b/clang/test/CodeGen/AArch64/args.cpp @@ -17,11 +17,29 @@ struct Empty {}; // DARWIN: define{{.*}} i32 @empty_arg(i32 noundef %a) // C: define{{.*}} i32 @empty_arg(i32 noundef %a) -// CXX: define{{.*}} i32 @empty_arg(i8 %e.coerce, i32 noundef %a) +// CXX: define{{.*}} i32 @empty_arg(i64 %e.coerce, i32 noundef %a) EXTERNC int empty_arg(struct Empty e, int a) { return a; } +// CXX: define{{.*}} i32 @empty_align8_arg(i64 %a.coerce, i32 noundef %b) +struct EmptyAlign8 { int __attribute__((aligned(8))) : 0; }; +EXTERNC int empty_align8_arg(struct EmptyAlign8 a, int b) { + return b; +} + +// CXX: define{{.*}} i32 @empty_align16_arg(i128 %a.coerce, i32 noundef %b) +struct EmptyAlign16 { long long int __attribute__((aligned(16))) : 0; }; +EXTERNC int empty_align16_arg(struct EmptyAlign16 a, int b) { + return b; +} + +// CXX: define{{.*}} i32 @empty_align32_arg(ptr dead_on_return noundef %a, i32 noundef %b) +struct EmptyAlign32 { long long int __attribute__((aligned(32))) : 0; }; +EXTERNC int empty_align32_arg(struct EmptyAlign32 a, int b) { + return b; +} + // DARWIN: define{{.*}} void @empty_ret() // C: define{{.*}} void @empty_ret() // CXX: define{{.*}} void @empty_ret() diff --git a/clang/test/CodeGen/AArch64/struct-coerce-using-ptr.cpp b/clang/test/CodeGen/AArch64/struct-coerce-using-ptr.cpp index f0c9ef28201a5..97fdd0ce56c66 100644 --- a/clang/test/CodeGen/AArch64/struct-coerce-using-ptr.cpp +++ b/clang/test/CodeGen/AArch64/struct-coerce-using-ptr.cpp @@ -575,19 +575,21 @@ void TSpp_align16(SSpp_align16 s) { *s.a.x = 1; } struct Sempty { }; // CHECK-A64-LABEL: define dso_local void @_Z6Tempty6Sempty( -// CHECK-A64-SAME: i8 [[S_COERCE:%.*]]) #[[ATTR0]] { +// CHECK-A64-SAME: i64 [[S_COERCE:%.*]]) #[[ATTR0]] { // CHECK-A64-NEXT: [[ENTRY:.*:]] // CHECK-A64-NEXT: [[S:%.*]] = alloca [[STRUCT_SEMPTY:%.*]], align 1 // CHECK-A64-NEXT: [[COERCE_DIVE:%.*]] = getelementptr inbounds nuw [[STRUCT_SEMPTY]], ptr [[S]], i32 0, i32 0 -// CHECK-A64-NEXT: store i8 [[S_COERCE]], ptr [[COERCE_DIVE]], align 1 +// CHECK-A64-NEXT: [[COERCE_VAL_II:%.*]] = trunc i64 [[S_COERCE]] to i8 +// CHECK-A64-NEXT: store i8 [[COERCE_VAL_II]], ptr [[COERCE_DIVE]], align 1 // CHECK-A64-NEXT: ret void // // CHECK-A64_32-LABEL: define void @_Z6Tempty6Sempty( -// CHECK-A64_32-SAME: i8 [[S_COERCE:%.*]]) #[[ATTR0]] { +// CHECK-A64_32-SAME: i64 [[S_COERCE:%.*]]) #[[ATTR0]] { // CHECK-A64_32-NEXT: [[ENTRY:.*:]] // CHECK-A64_32-NEXT: [[S:%.*]] = alloca [[STRUCT_SEMPTY:%.*]], align 1 // CHECK-A64_32-NEXT: [[COERCE_DIVE:%.*]] = getelementptr inbounds nuw [[STRUCT_SEMPTY]], ptr [[S]], i32 0, i32 0 -// CHECK-A64_32-NEXT: store i8 [[S_COERCE]], ptr [[COERCE_DIVE]], align 1 +// CHECK-A64_32-NEXT: [[COERCE_VAL_II:%.*]] = trunc i64 [[S_COERCE]] to i8 +// CHECK-A64_32-NEXT: store i8 [[COERCE_VAL_II]], ptr [[COERCE_DIVE]], align 1 // CHECK-A64_32-NEXT: ret void // void Tempty(Sempty s) { } diff --git a/clang/test/CodeGen/arm64-microsoft-arguments.cpp b/clang/test/CodeGen/arm64-microsoft-arguments.cpp index a0a81be54325f..f7eb0cc765354 100644 --- a/clang/test/CodeGen/arm64-microsoft-arguments.cpp +++ b/clang/test/CodeGen/arm64-microsoft-arguments.cpp @@ -57,7 +57,7 @@ S4 f4() { // Pass and return from instance method called from instance method. // CHECK: define {{.*}} void @{{.*}}bar@Q1{{.*}}(ptr {{[^,]*}} %this, ptr dead_on_unwind inreg noalias writable sret(%class.P1) align 1 %agg.result) -// CHECK: call void {{.*}}foo@P1{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr dead_on_unwind inreg writable sret(%class.P1) align 1 %agg.result, i8 %0) +// CHECK: call void {{.*}}foo@P1{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr dead_on_unwind inreg writable sret(%class.P1) align 1 %agg.result, i64 %coerce.val.ii) class P1 { public: @@ -76,7 +76,7 @@ P1 Q1::bar() { // Pass and return from instance method called from free function. // CHECK: define {{.*}} void {{.*}}bar{{.*}}() -// CHECK: call void {{.*}}foo@P2{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr dead_on_unwind inreg writable sret(%class.P2) align 1 %retval, i8 %0) +// CHECK: call void {{.*}}foo@P2{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr dead_on_unwind inreg writable sret(%class.P2) align 1 %retval, i64 %coerce.val.ii) class P2 { public: P2 foo(P2 x); diff --git a/clang/test/CodeGenCXX/aarch64-arguments.cpp b/clang/test/CodeGenCXX/aarch64-arguments.cpp index ffb0cafa8882d..3206e38ad0090 100644 --- a/clang/test/CodeGenCXX/aarch64-arguments.cpp +++ b/clang/test/CodeGenCXX/aarch64-arguments.cpp @@ -1,5 +1,5 @@ // RUN: %clang_cc1 -triple arm64-none-linux -emit-llvm -w -o - %s | FileCheck -check-prefix=PCS %s -// PCS: define{{.*}} void @{{.*}}(i8 %a +// PCS: define{{.*}} void @{{.*}}(i64 %a.coerce) struct s0 {}; void f0(s0 a) {} diff --git a/clang/test/CodeGenCXX/arm64-darwinpcs.cpp b/clang/test/CodeGenCXX/arm64-darwinpcs.cpp index a0b0d9efdd4c4..ef0e2da3effac 100644 --- a/clang/test/CodeGenCXX/arm64-darwinpcs.cpp +++ b/clang/test/CodeGenCXX/arm64-darwinpcs.cpp @@ -7,7 +7,7 @@ void test_extensions(bool a, char b, short c) {} struct Empty {}; void test_empty(Empty e) {} -// CHECK: define{{.*}} void @_Z10test_empty5Empty(i8 +// CHECK: define{{.*}} void @_Z10test_empty5Empty(i64 %e.coerce) // CHECK-DARWIN: define{{.*}} void @_Z10test_empty5Empty() struct HFA { From b9ea93cd5c37fb6d606502fd01208dd48330549d Mon Sep 17 00:00:00 2001 From: Andreas Jonson Date: Sat, 8 Nov 2025 15:22:32 +0100 Subject: [PATCH 04/18] [InstCombine] Fold operation into select, when one operand is zext of select's condition (#166816) Proof https://alive2.llvm.org/ce/z/oCQyTG --- .../InstCombine/InstructionCombining.cpp | 3 ++ .../Transforms/InstCombine/binop-select.ll | 29 ++++--------------- 2 files changed, 9 insertions(+), 23 deletions(-) diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp index b158e0f626850..27ec6c6cb78a3 100644 --- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp +++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp @@ -1758,6 +1758,9 @@ static Value *simplifyOperationIntoSelectOperand(Instruction &I, SelectInst *SI, m_Specific(Op), m_Value(V))) && isGuaranteedNotToBeUndefOrPoison(V)) { // Pass + } else if (match(Op, m_ZExt(m_Specific(SI->getCondition())))) { + V = IsTrueArm ? ConstantInt::get(Op->getType(), 1) + : ConstantInt::getNullValue(Op->getType()); } else { V = Op; } diff --git a/llvm/test/Transforms/InstCombine/binop-select.ll b/llvm/test/Transforms/InstCombine/binop-select.ll index fe1ec9014f188..9e336ad104599 100644 --- a/llvm/test/Transforms/InstCombine/binop-select.ll +++ b/llvm/test/Transforms/InstCombine/binop-select.ll @@ -406,10 +406,7 @@ define i32 @ashr_sel_op1_use(i1 %b) { define i8 @commonArgWithOr0(i1 %arg0) { ; CHECK-LABEL: @commonArgWithOr0( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 0, i8 8 -; CHECK-NEXT: [[V2:%.*]] = or disjoint i8 [[V1]], [[V0]] -; CHECK-NEXT: [[V3:%.*]] = or disjoint i8 [[V2]], 16 +; CHECK-NEXT: [[V3:%.*]] = select i1 [[ARG0:%.*]], i8 17, i8 24 ; CHECK-NEXT: ret i8 [[V3]] ; %v0 = zext i1 %arg0 to i8 @@ -433,10 +430,7 @@ define i8 @commonArgWithOr1(i1 %arg0) { define i8 @commonArgWithOr2(i1 %arg0) { ; CHECK-LABEL: @commonArgWithOr2( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 5, i8 42 -; CHECK-NEXT: [[V2:%.*]] = or i8 [[V1]], [[V0]] -; CHECK-NEXT: [[V3:%.*]] = or disjoint i8 [[V2]], 16 +; CHECK-NEXT: [[V3:%.*]] = select i1 [[ARG0:%.*]], i8 21, i8 58 ; CHECK-NEXT: ret i8 [[V3]] ; %v0 = zext i1 %arg0 to i8 @@ -496,10 +490,7 @@ define i8 @commonArgWithAnd3(i1 %arg0) { define i8 @commonArgWithXor0(i1 %arg0) { ; CHECK-LABEL: @commonArgWithXor0( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 0, i8 8 -; CHECK-NEXT: [[V2:%.*]] = or disjoint i8 [[V1]], [[V0]] -; CHECK-NEXT: [[V3:%.*]] = or disjoint i8 [[V2]], 16 +; CHECK-NEXT: [[V3:%.*]] = select i1 [[ARG0:%.*]], i8 17, i8 24 ; CHECK-NEXT: ret i8 [[V3]] ; %v0 = zext i1 %arg0 to i8 @@ -511,9 +502,7 @@ define i8 @commonArgWithXor0(i1 %arg0) { define i8 @commonArgWithXor1(i1 %arg0) { ; CHECK-LABEL: @commonArgWithXor1( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 9, i8 1 -; CHECK-NEXT: [[V2:%.*]] = xor i8 [[V1]], [[V0]] +; CHECK-NEXT: [[V2:%.*]] = select i1 [[ARG0:%.*]], i8 8, i8 1 ; CHECK-NEXT: ret i8 [[V2]] ; %v0 = zext i1 %arg0 to i8 @@ -524,10 +513,7 @@ define i8 @commonArgWithXor1(i1 %arg0) { define i8 @commonArgWithXor2(i1 %arg0) { ; CHECK-LABEL: @commonArgWithXor2( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 1, i8 7 -; CHECK-NEXT: [[V2:%.*]] = xor i8 [[V1]], [[V0]] -; CHECK-NEXT: [[V3:%.*]] = or disjoint i8 [[V2]], 16 +; CHECK-NEXT: [[V3:%.*]] = select i1 [[ARG0:%.*]], i8 16, i8 23 ; CHECK-NEXT: ret i8 [[V3]] ; %v0 = zext i1 %arg0 to i8 @@ -539,10 +525,7 @@ define i8 @commonArgWithXor2(i1 %arg0) { define i8 @commonArgWithXor3(i1 %arg0) { ; CHECK-LABEL: @commonArgWithXor3( -; CHECK-NEXT: [[V0:%.*]] = zext i1 [[ARG0:%.*]] to i8 -; CHECK-NEXT: [[V1:%.*]] = select i1 [[ARG0]], i8 5, i8 45 -; CHECK-NEXT: [[V2:%.*]] = xor i8 [[V1]], [[V0]] -; CHECK-NEXT: [[V3:%.*]] = or disjoint i8 [[V2]], 16 +; CHECK-NEXT: [[V3:%.*]] = select i1 [[ARG0:%.*]], i8 20, i8 61 ; CHECK-NEXT: ret i8 [[V3]] ; %v0 = zext i1 %arg0 to i8 From fa98c8dfde45eae4608e1cdaa33b088cd7aff01b Mon Sep 17 00:00:00 2001 From: Walter Lee <49250218+googlewalt@users.noreply.github.com> Date: Sat, 8 Nov 2025 10:12:23 -0500 Subject: [PATCH 05/18] Fix bazel build for #166719 --- .../bazel/llvm-project-overlay/libc/test/src/stdlib/BUILD.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/stdlib/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/stdlib/BUILD.bazel index fd4389e8c0579..8d30869056ec7 100644 --- a/utils/bazel/llvm-project-overlay/libc/test/src/stdlib/BUILD.bazel +++ b/utils/bazel/llvm-project-overlay/libc/test/src/stdlib/BUILD.bazel @@ -174,6 +174,7 @@ libc_test_library( deps = [ "//libc:__support_cpp_type_traits", "//libc:__support_fputil_fp_bits", + "//libc:__support_macros_properties_architectures", "//libc/test/UnitTest:LibcUnitTest", ], ) From 6deb50dc7c7f0467381a20ccab3efd9db0f8993e Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 18:18:15 +0300 Subject: [PATCH 06/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (11/N) (#167128) --- .../modernize/UseDefaultMemberInitCheck.cpp | 10 ++-- .../UseDesignatedInitializersCheck.cpp | 2 +- .../modernize/UseEqualsDefaultCheck.cpp | 10 ++-- .../modernize/UseEqualsDeleteCheck.cpp | 2 +- .../UseIntegerSignComparisonCheck.cpp | 2 +- .../modernize/UseNodiscardCheck.cpp | 4 +- .../clang-tidy/modernize/UseNoexceptCheck.cpp | 6 +-- .../clang-tidy/modernize/UseNullptrCheck.cpp | 27 +++++----- .../clang-tidy/modernize/UseOverrideCheck.cpp | 31 +++++------ .../modernize/UseScopedLockCheck.cpp | 5 +- .../modernize/UseStdNumbersCheck.cpp | 2 +- .../modernize/UseTrailingReturnTypeCheck.cpp | 51 ++++++++++--------- .../modernize/UseTransparentFunctorsCheck.cpp | 6 +-- .../modernize/UseUncaughtExceptionsCheck.cpp | 4 +- .../clang-tidy/modernize/UseUsingCheck.cpp | 7 +-- 15 files changed, 87 insertions(+), 82 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 0d2c3a79b9ece..cc6b7bfd4fd5b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -163,7 +163,7 @@ static bool isZero(const Expr *E) { case Stmt::IntegerLiteralClass: return !cast(E)->getValue(); case Stmt::FloatingLiteralClass: { - llvm::APFloat Value = cast(E)->getValue(); + const llvm::APFloat Value = cast(E)->getValue(); return Value.isZero() && !Value.isNegative(); } default: @@ -297,16 +297,16 @@ void UseDefaultMemberInitCheck::checkDefaultInit( }) > 1) return; - SourceLocation StartLoc = Field->getBeginLoc(); + const SourceLocation StartLoc = Field->getBeginLoc(); if (StartLoc.isMacroID() && IgnoreMacros) return; - SourceLocation FieldEnd = + const SourceLocation FieldEnd = Lexer::getLocForEndOfToken(Field->getSourceRange().getEnd(), 0, *Result.SourceManager, getLangOpts()); - SourceLocation LParenEnd = Lexer::getLocForEndOfToken( + const SourceLocation LParenEnd = Lexer::getLocForEndOfToken( Init->getLParenLoc(), 0, *Result.SourceManager, getLangOpts()); - CharSourceRange InitRange = + const CharSourceRange InitRange = CharSourceRange::getCharRange(LParenEnd, Init->getRParenLoc()); const Expr *InitExpression = Init->getInit(); diff --git a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp index c1094b1fc194a..2cc3ce1f7a686 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp @@ -152,7 +152,7 @@ void UseDesignatedInitializersCheck::check( if (IgnoreMacros && InitList->getBeginLoc().isMacroID()) return; { - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(InitList->getLBraceLoc(), "use designated initializer list to initialize %0"); Diag << InitList->getType() << InitList->getSourceRange(); diff --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp index d6ddbb69f7b0d..fde9c7323ce3c 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp @@ -200,7 +200,7 @@ static bool isCopyAssignmentAndCanBeDefaulted(ASTContext *Context, /// Returns false if the body has any non-whitespace character. static bool bodyEmpty(const ASTContext *Context, const CompoundStmt *Body) { bool Invalid = false; - StringRef Text = Lexer::getSourceText( + const StringRef Text = Lexer::getSourceText( CharSourceRange::getCharRange(Body->getLBracLoc().getLocWithOffset(1), Body->getRBracLoc()), Context->getSourceManager(), Context->getLangOpts(), &Invalid); @@ -306,8 +306,8 @@ void UseEqualsDefaultCheck::check(const MatchFinder::MatchResult &Result) { return; // If there are comments inside the body, don't do the change. - bool ApplyFix = SpecialFunctionDecl->isCopyAssignmentOperator() || - bodyEmpty(Result.Context, Body); + const bool ApplyFix = SpecialFunctionDecl->isCopyAssignmentOperator() || + bodyEmpty(Result.Context, Body); std::vector RemoveInitializers; unsigned MemberType = 0; @@ -345,14 +345,14 @@ void UseEqualsDefaultCheck::check(const MatchFinder::MatchResult &Result) { Diag << MemberType; if (ApplyFix) { - SourceLocation UnifiedEnd = utils::lexer::getUnifiedEndLoc( + const SourceLocation UnifiedEnd = utils::lexer::getUnifiedEndLoc( *Body, Result.Context->getSourceManager(), Result.Context->getLangOpts()); // Skipping comments, check for a semicolon after Body->getSourceRange() std::optional Token = utils::lexer::findNextTokenSkippingComments( UnifiedEnd, Result.Context->getSourceManager(), Result.Context->getLangOpts()); - StringRef Replacement = + const StringRef Replacement = Token && Token->is(tok::semi) ? "= default" : "= default;"; Diag << FixItHint::CreateReplacement(Body->getSourceRange(), Replacement) << RemoveInitializers; diff --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.cpp index ab2d41a52040e..a19d2ecdad88d 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.cpp @@ -74,7 +74,7 @@ void UseEqualsDeleteCheck::registerMatchers(MatchFinder *Finder) { void UseEqualsDeleteCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *Func = Result.Nodes.getNodeAs(SpecialFunction)) { - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Func->getEndLoc(), 0, *Result.SourceManager, getLangOpts()); if (IgnoreMacros && Func->getLocation().isMacroID()) diff --git a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp index 35320e83c5d4b..574cbea46124b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseIntegerSignComparisonCheck.cpp @@ -146,7 +146,7 @@ void UseIntegerSignComparisonCheck::check( R3.setBegin(Lexer::getLocForEndOfToken( SubExprRHS->getEndLoc(), 0, *Result.SourceManager, getLangOpts())); } - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(BinaryOp->getBeginLoc(), "comparison between 'signed' and 'unsigned' integers"); StringRef CmpNamespace; diff --git a/clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp index d22c99335d9bb..7e8d98241118a 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp @@ -110,11 +110,11 @@ void UseNodiscardCheck::registerMatchers(MatchFinder *Finder) { void UseNodiscardCheck::check(const MatchFinder::MatchResult &Result) { const auto *MatchedDecl = Result.Nodes.getNodeAs("no_discard"); // Don't make replacements if the location is invalid or in a macro. - SourceLocation Loc = MatchedDecl->getLocation(); + const SourceLocation Loc = MatchedDecl->getLocation(); if (Loc.isInvalid() || Loc.isMacroID()) return; - SourceLocation RetLoc = MatchedDecl->getInnerLocStart(); + const SourceLocation RetLoc = MatchedDecl->getInnerLocStart(); ASTContext &Context = *Result.Context; diff --git a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp index d1388dc6298e4..6bd5485abbac9 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp @@ -81,12 +81,12 @@ void UseNoexceptCheck::check(const MatchFinder::MatchResult &Result) { assert(Range.isValid() && "Exception Source Range is invalid."); - CharSourceRange CRange = Lexer::makeFileCharRange( + const CharSourceRange CRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(Range), *Result.SourceManager, Result.Context->getLangOpts()); - bool IsNoThrow = FnTy->isNothrow(); - StringRef ReplacementStr = + const bool IsNoThrow = FnTy->isNothrow(); + const StringRef ReplacementStr = IsNoThrow ? NoexceptMacro.empty() ? "noexcept" : NoexceptMacro : NoexceptMacro.empty() ? (DtorOrOperatorDel || UseNoexceptFalse) ? "noexcept(false)" : "" diff --git a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp index b6834c69204c2..928a00775fe12 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp @@ -92,12 +92,13 @@ static bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc, /// Returns true if and only if a replacement was made. static void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLoc) { - CharSourceRange Range(SourceRange(StartLoc, EndLoc), true); + const CharSourceRange Range(SourceRange(StartLoc, EndLoc), true); // Add a space if nullptr follows an alphanumeric character. This happens // whenever there is an c-style explicit cast to nullptr not surrounded by // parentheses and right beside a return statement. - SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1); - bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation)); + const SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1); + const bool NeedsSpace = + isAlphanumeric(*SM.getCharacterData(PreviousLocation)); Check.diag(Range.getBegin(), "use nullptr") << FixItHint::CreateReplacement( Range, NeedsSpace ? " nullptr" : "nullptr"); } @@ -136,7 +137,7 @@ class MacroArgUsageVisitor : public RecursiveASTVisitor { } bool TraverseStmt(Stmt *S) { - bool VisitedPreviously = Visited; + const bool VisitedPreviously = Visited; if (!RecursiveASTVisitor::TraverseStmt(S)) return false; @@ -258,8 +259,8 @@ class CastSequenceVisitor : public RecursiveASTVisitor { // If the location comes from a macro body expansion, check to see if its // coming from one of the allowed 'NULL' macros. if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) { - SourceLocation FileLocStart = SM.getFileLoc(StartLoc), - FileLocEnd = SM.getFileLoc(EndLoc); + const SourceLocation FileLocStart = SM.getFileLoc(StartLoc), + FileLocEnd = SM.getFileLoc(EndLoc); SourceLocation ImmediateMacroArgLoc, MacroLoc; // Skip NULL macros used in macro. if (!getMacroAndArgLocations(StartLoc, ImmediateMacroArgLoc, MacroLoc) || @@ -274,7 +275,7 @@ class CastSequenceVisitor : public RecursiveASTVisitor { } if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) { - StringRef OutermostMacroName = + const StringRef OutermostMacroName = getOutermostMacroName(StartLoc, SM, Context.getLangOpts()); // Check to see if the user wants to replace the macro being expanded. @@ -302,7 +303,7 @@ class CastSequenceVisitor : public RecursiveASTVisitor { /// Tests that all expansions of a macro arg, one of which expands to /// result in \p CE, yield NullTo(Member)Pointer casts. bool allArgUsesValid(const CastExpr *CE) { - SourceLocation CastLoc = CE->getBeginLoc(); + const SourceLocation CastLoc = CE->getBeginLoc(); // Step 1: Get location of macro arg and location of the macro the arg was // provided to. @@ -348,17 +349,17 @@ class CastSequenceVisitor : public RecursiveASTVisitor { // Find the location of the immediate macro expansion. while (true) { - std::pair LocInfo = SM.getDecomposedLoc(ArgLoc); + const std::pair LocInfo = SM.getDecomposedLoc(ArgLoc); const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first); const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); - SourceLocation OldArgLoc = ArgLoc; + const SourceLocation OldArgLoc = ArgLoc; ArgLoc = Expansion.getExpansionLocStart(); if (!Expansion.isMacroArgExpansion()) { if (!MacroLoc.isFileID()) return false; - StringRef Name = + const StringRef Name = Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts()); return llvm::is_contained(NullMacros, Name); } @@ -371,7 +372,7 @@ class CastSequenceVisitor : public RecursiveASTVisitor { // If spelling location resides in the same FileID as macro expansion // location, it means there is no inner macro. - FileID MacroFID = SM.getFileID(MacroLoc); + const FileID MacroFID = SM.getFileID(MacroLoc); if (SM.isInFileID(ArgLoc, MacroFID)) { // Don't transform this case. If the characters that caused the // null-conversion come from within a macro, they can't be changed. @@ -401,7 +402,7 @@ class CastSequenceVisitor : public RecursiveASTVisitor { SourceLocation Loc = TestLoc, MacroLoc; while (true) { - std::pair LocInfo = SM.getDecomposedLoc(Loc); + const std::pair LocInfo = SM.getDecomposedLoc(Loc); const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first); const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); diff --git a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp index 6a19183737119..62a2de23147a7 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp @@ -55,9 +55,9 @@ void UseOverrideCheck::registerMatchers(MatchFinder *Finder) { static SmallVector parseTokens(CharSourceRange Range, const MatchFinder::MatchResult &Result) { const SourceManager &Sources = *Result.SourceManager; - std::pair LocInfo = + const std::pair LocInfo = Sources.getDecomposedLoc(Range.getBegin()); - StringRef File = Sources.getBufferData(LocInfo.first); + const StringRef File = Sources.getBufferData(LocInfo.first); const char *TokenBegin = File.data() + LocInfo.second; Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first), Result.Context->getLangOpts(), File.begin(), TokenBegin, @@ -103,12 +103,12 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { Method->isOutOfLine()) return; - bool HasVirtual = Method->isVirtualAsWritten(); - bool HasOverride = Method->getAttr(); - bool HasFinal = Method->getAttr(); + const bool HasVirtual = Method->isVirtualAsWritten(); + const bool HasOverride = Method->getAttr(); + const bool HasFinal = Method->getAttr(); - bool OnlyVirtualSpecified = HasVirtual && !HasOverride && !HasFinal; - unsigned KeywordCount = HasVirtual + HasOverride + HasFinal; + const bool OnlyVirtualSpecified = HasVirtual && !HasOverride && !HasFinal; + const unsigned KeywordCount = HasVirtual + HasOverride + HasFinal; if ((!OnlyVirtualSpecified && KeywordCount == 1) || (!HasVirtual && HasOverride && HasFinal && AllowOverrideAndFinal)) @@ -120,12 +120,12 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { } else if (KeywordCount == 0) { Message = "annotate this function with '%0' or (rarely) '%1'"; } else { - StringRef Redundant = + const StringRef Redundant = HasVirtual ? (HasOverride && HasFinal && !AllowOverrideAndFinal ? "'virtual' and '%0' are" : "'virtual' is") : "'%0' is"; - StringRef Correct = HasFinal ? "'%1'" : "'%0'"; + const StringRef Correct = HasFinal ? "'%1'" : "'%0'"; Message = (llvm::Twine(Redundant) + " redundant since the function is already declared " + Correct) @@ -135,7 +135,7 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { auto Diag = diag(Method->getLocation(), Message) << OverrideSpelling << FinalSpelling; - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(Method->getSourceRange()), Sources, getLangOpts()); @@ -151,9 +151,9 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { if (!HasFinal && !HasOverride) { SourceLocation InsertLoc; std::string ReplacementText = (OverrideSpelling + " ").str(); - SourceLocation MethodLoc = Method->getLocation(); + const SourceLocation MethodLoc = Method->getLocation(); - for (Token T : Tokens) { + for (const Token T : Tokens) { if (T.is(tok::kw___attribute) && !Sources.isBeforeInTranslationUnit(T.getLocation(), MethodLoc)) { InsertLoc = T.getLocation(); @@ -164,7 +164,7 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { if (Method->hasAttrs()) { for (const clang::Attr *A : Method->getAttrs()) { if (!A->isImplicit() && !A->isInherited()) { - SourceLocation Loc = + const SourceLocation Loc = Sources.getExpansionLoc(A->getRange().getBegin()); if ((!InsertLoc.isValid() || Sources.isBeforeInTranslationUnit(Loc, InsertLoc)) && @@ -221,13 +221,14 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult &Result) { } if (HasFinal && HasOverride && !AllowOverrideAndFinal) { - SourceLocation OverrideLoc = Method->getAttr()->getLocation(); + const SourceLocation OverrideLoc = + Method->getAttr()->getLocation(); Diag << FixItHint::CreateRemoval( CharSourceRange::getTokenRange(OverrideLoc, OverrideLoc)); } if (HasVirtual) { - for (Token Tok : Tokens) { + for (const Token Tok : Tokens) { if (Tok.is(tok::kw_virtual)) { std::optional NextToken = utils::lexer::findNextTokenIncludingComments( diff --git a/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp index 9bf316939e2d0..8849c331608f9 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp @@ -74,7 +74,8 @@ findLocksInCompoundStmt(const CompoundStmt *Block, for (const Stmt *Stmt : Block->body()) { if (const auto *DS = dyn_cast(Stmt)) { - llvm::SmallVector LockGuards = getLockGuardsFromDecl(DS); + const llvm::SmallVector LockGuards = + getLockGuardsFromDecl(DS); if (!LockGuards.empty()) { CurrentLockGuardGroup.append(LockGuards); @@ -176,7 +177,7 @@ void UseScopedLockCheck::registerMatchers(MatchFinder *Finder) { void UseScopedLockCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *DS = Result.Nodes.getNodeAs("lock-decl-single")) { - llvm::SmallVector Decls = getLockGuardsFromDecl(DS); + const llvm::SmallVector Decls = getLockGuardsFromDecl(DS); diagOnMultipleLocks({Decls}, Result); return; } diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp index 414aa86c5fbd2..47ff9ffd3f7b7 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp @@ -307,7 +307,7 @@ UseStdNumbersCheck::UseStdNumbersCheck(const StringRef Name, void UseStdNumbersCheck::registerMatchers(MatchFinder *const Finder) { const auto Matches = MatchBuilder{DiffThreshold}; - std::vector> ConstantMatchers = { + const std::vector> ConstantMatchers = { Matches.matchLog2Euler(), Matches.matchLog10Euler(), Matches.matchEulerTopLevel(), Matches.matchEgamma(), Matches.matchInvSqrtPi(), Matches.matchInvPi(), diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index d623ec402179b..3c828c4c37fe1 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -55,7 +55,7 @@ struct UnqualNameVisitor : public RecursiveASTVisitor { bool visitUnqualName(StringRef UnqualName) { // Check for collisions with function arguments. - for (ParmVarDecl *Param : F.parameters()) + for (const ParmVarDecl *Param : F.parameters()) if (const IdentifierInfo *Ident = Param->getIdentifier()) if (Ident->getName() == UnqualName) { Collision = true; @@ -126,7 +126,7 @@ struct UnqualNameVisitor : public RecursiveASTVisitor { } bool VisitDeclRefExpr(DeclRefExpr *S) { - DeclarationName Name = S->getNameInfo().getName(); + const DeclarationName Name = S->getNameInfo().getName(); return S->getQualifierLoc() || Name.isEmpty() || !Name.isIdentifier() || !visitUnqualName(Name.getAsIdentifierInfo()->getName()); } @@ -159,14 +159,14 @@ static SourceLocation findTrailingReturnTypeSourceLocation( const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts) { // We start with the location of the closing parenthesis. - SourceRange ExceptionSpecRange = F.getExceptionSpecSourceRange(); + const SourceRange ExceptionSpecRange = F.getExceptionSpecSourceRange(); if (ExceptionSpecRange.isValid()) return Lexer::getLocForEndOfToken(ExceptionSpecRange.getEnd(), 0, SM, LangOpts); // If the function argument list ends inside of a macro, it is dangerous to // start lexing from here - bail out. - SourceLocation ClosingParen = FTL.getRParenLoc(); + const SourceLocation ClosingParen = FTL.getRParenLoc(); if (ClosingParen.isMacroID()) return {}; @@ -174,8 +174,8 @@ static SourceLocation findTrailingReturnTypeSourceLocation( Lexer::getLocForEndOfToken(ClosingParen, 0, SM, LangOpts); // Skip subsequent CV and ref qualifiers. - std::pair Loc = SM.getDecomposedLoc(Result); - StringRef File = SM.getBufferData(Loc.first); + const std::pair Loc = SM.getDecomposedLoc(Result); + const StringRef File = SM.getBufferData(Loc.first); const char *TokenBegin = File.data() + Loc.second; Lexer Lexer(SM.getLocForStartOfFile(Loc.first), LangOpts, File.begin(), TokenBegin, File.end()); @@ -220,7 +220,7 @@ classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) { Token End; End.startToken(); End.setKind(tok::eof); - SmallVector Stream{Tok, End}; + const SmallVector Stream{Tok, End}; // FIXME: do not report these token to Preprocessor.TokenWatcher. PP.EnterTokenStream(Stream, false, /*IsReinject=*/false); @@ -230,8 +230,8 @@ classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) { if (T.is(tok::eof)) break; - bool Qual = isCvr(T); - bool Spec = isSpecifier(T); + const bool Qual = isCvr(T); + const bool Spec = isSpecifier(T); CT.IsQualifier &= Qual; CT.IsSpecifier &= Spec; ContainsQualifiers |= Qual; @@ -252,12 +252,12 @@ classifyTokensBeforeFunctionName(const FunctionDecl &F, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts, Preprocessor *PP) { - SourceLocation BeginF = expandIfMacroId(F.getBeginLoc(), SM); - SourceLocation BeginNameF = expandIfMacroId(F.getLocation(), SM); + const SourceLocation BeginF = expandIfMacroId(F.getBeginLoc(), SM); + const SourceLocation BeginNameF = expandIfMacroId(F.getLocation(), SM); // Create tokens for everything before the name of the function. - std::pair Loc = SM.getDecomposedLoc(BeginF); - StringRef File = SM.getBufferData(Loc.first); + const std::pair Loc = SM.getDecomposedLoc(BeginF); + const StringRef File = SM.getBufferData(Loc.first); const char *TokenBegin = File.data() + Loc.second; Lexer Lexer(SM.getLocForStartOfFile(Loc.first), LangOpts, File.begin(), TokenBegin, File.end()); @@ -369,9 +369,9 @@ static SourceLocation findLambdaTrailingReturnInsertLoc( else ParamEndLoc = Method->getParametersSourceRange().getEnd(); - std::pair ParamEndLocInfo = + const std::pair ParamEndLocInfo = SM.getDecomposedLoc(ParamEndLoc); - StringRef Buffer = SM.getBufferData(ParamEndLocInfo.first); + const StringRef Buffer = SM.getBufferData(ParamEndLocInfo.first); Lexer Lexer(SM.getLocForStartOfFile(ParamEndLocInfo.first), LangOpts, Buffer.begin(), Buffer.data() + ParamEndLocInfo.second, @@ -421,11 +421,11 @@ static void keepSpecifiers(std::string &ReturnType, std::string &Auto, return; // Find specifiers, remove them from the return type, add them to 'auto'. - unsigned int ReturnTypeBeginOffset = + const unsigned int ReturnTypeBeginOffset = SM.getDecomposedLoc(ReturnTypeCVRange.getBegin()).second; - size_t InitialAutoLength = Auto.size(); + const size_t InitialAutoLength = Auto.size(); unsigned int DeletedChars = 0; - for (ClassifiedToken CT : *MaybeTokens) { + for (const ClassifiedToken CT : *MaybeTokens) { if (SM.isBeforeInTranslationUnit(CT.T.getLocation(), ReturnTypeCVRange.getBegin()) || SM.isBeforeInTranslationUnit(ReturnTypeCVRange.getEnd(), @@ -436,10 +436,11 @@ static void keepSpecifiers(std::string &ReturnType, std::string &Auto, // Add the token to 'auto' and remove it from the return type, including // any whitespace following the token. - unsigned int TOffset = SM.getDecomposedLoc(CT.T.getLocation()).second; + const unsigned int TOffset = SM.getDecomposedLoc(CT.T.getLocation()).second; assert(TOffset >= ReturnTypeBeginOffset && "Token location must be after the beginning of the return type"); - unsigned int TOffsetInRT = TOffset - ReturnTypeBeginOffset - DeletedChars; + const unsigned int TOffsetInRT = + TOffset - ReturnTypeBeginOffset - DeletedChars; unsigned int TLengthWithWS = CT.T.getLength(); while (TOffsetInRT + TLengthWithWS < ReturnType.size() && llvm::isSpace(ReturnType[TOffsetInRT + TLengthWithWS])) @@ -548,7 +549,7 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { return; } - SourceLocation InsertionLoc = + const SourceLocation InsertionLoc = findTrailingReturnTypeSourceLocation(*F, FTL, Ctx, SM, LangOpts); if (InsertionLoc.isInvalid()) { diag(F->getLocation(), ErrorMessageOnFunction); @@ -558,7 +559,7 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { // Using the declared return type via F->getDeclaredReturnType().getAsString() // discards user formatting and order of const, volatile, type, whitespace, // space before & ... . - SourceRange ReturnTypeCVRange = findReturnTypeAndCVSourceRange( + const SourceRange ReturnTypeCVRange = findReturnTypeAndCVSourceRange( *F, FTL.getReturnLoc(), Ctx, SM, LangOpts, PP); if (ReturnTypeCVRange.isInvalid()) { diag(F->getLocation(), ErrorMessageOnFunction); @@ -580,13 +581,13 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { return; } - SourceLocation ReturnTypeEnd = + const SourceLocation ReturnTypeEnd = Lexer::getLocForEndOfToken(ReturnTypeCVRange.getEnd(), 0, SM, LangOpts); - StringRef CharAfterReturnType = Lexer::getSourceText( + const StringRef CharAfterReturnType = Lexer::getSourceText( CharSourceRange::getCharRange(ReturnTypeEnd, ReturnTypeEnd.getLocWithOffset(1)), SM, LangOpts); - bool NeedSpaceAfterAuto = + const bool NeedSpaceAfterAuto = CharAfterReturnType.empty() || !llvm::isSpace(CharAfterReturnType[0]); std::string Auto = NeedSpaceAfterAuto ? "auto " : "auto"; diff --git a/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp index 03ecec9bd175b..e3672f84a3a5c 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp @@ -96,7 +96,7 @@ void UseTransparentFunctorsCheck::check( FunctorParentType->template_arguments()[ArgNum]; if (Arg.getKind() != TemplateArgument::Type) continue; - QualType ParentArgType = Arg.getAsType(); + const QualType ParentArgType = Arg.getAsType(); if (ParentArgType->isRecordType() && ParentArgType->getAsCXXRecordDecl() == Functor->getAsType()->getAsCXXRecordDecl()) @@ -105,13 +105,13 @@ void UseTransparentFunctorsCheck::check( // Functor is a default template argument. if (ArgNum == FunctorParentType->template_arguments().size()) return; - TemplateArgumentLoc FunctorLoc = FunctorParentLoc.getArgLoc(ArgNum); + const TemplateArgumentLoc FunctorLoc = FunctorParentLoc.getArgLoc(ArgNum); auto FunctorTypeLoc = getInnerTypeLocAs( FunctorLoc.getTypeSourceInfo()->getTypeLoc()); if (FunctorTypeLoc.isNull()) return; - SourceLocation ReportLoc = FunctorLoc.getLocation(); + const SourceLocation ReportLoc = FunctorLoc.getLocation(); if (ReportLoc.isInvalid()) return; diag(ReportLoc, Message) << FuncClass->getName() diff --git a/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp index eef9d39800360..08c40d4554488 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp @@ -15,7 +15,7 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { void UseUncaughtExceptionsCheck::registerMatchers(MatchFinder *Finder) { - std::string MatchText = "::std::uncaught_exception"; + const std::string MatchText = "::std::uncaught_exception"; // Using declaration: warning and fix-it. Finder->addMatcher( @@ -78,7 +78,7 @@ void UseUncaughtExceptionsCheck::check(const MatchFinder::MatchResult &Result) { *Result.SourceManager, getLangOpts()); Text.consume_back("()"); - int TextLength = Text.size(); + const int TextLength = Text.size(); if (WarnOnly) { return; diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp index 72673753e6c60..38b368957c5d5 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp @@ -114,7 +114,7 @@ void UseUsingCheck::check(const MatchFinder::MatchResult &Result) { if (ExternCDecl && IgnoreExternC) return; - SourceLocation StartLoc = MatchedDecl->getBeginLoc(); + const SourceLocation StartLoc = MatchedDecl->getBeginLoc(); if (StartLoc.isMacroID() && IgnoreMacros) return; @@ -172,7 +172,7 @@ void UseUsingCheck::check(const MatchFinder::MatchResult &Result) { .str(), ExtraReference.str()}; }(); - StringRef Name = MatchedDecl->getName(); + const StringRef Name = MatchedDecl->getName(); SourceRange ReplaceRange = MatchedDecl->getSourceRange(); // typedefs with multiple comma-separated definitions produce multiple @@ -223,7 +223,8 @@ void UseUsingCheck::check(const MatchFinder::MatchResult &Result) { return; } - std::string Replacement = (Using + Name + " = " + Type + QualifierStr).str(); + const std::string Replacement = + (Using + Name + " = " + Type + QualifierStr).str(); Diag << FixItHint::CreateReplacement(ReplaceRange, Replacement); } } // namespace clang::tidy::modernize From c6ffc93130cb66c95a5d14ce52168031e680c688 Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 18:18:33 +0300 Subject: [PATCH 07/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (14/N) (#167131) --- .../bugprone/StringIntegerAssignmentCheck.cpp | 6 +-- .../bugprone/SuspiciousEnumUsageCheck.cpp | 8 ++-- .../bugprone/SuspiciousIncludeCheck.cpp | 4 +- .../SuspiciousMemoryComparisonCheck.cpp | 6 +-- .../bugprone/SuspiciousMemsetUsageCheck.cpp | 12 +++--- .../bugprone/SuspiciousMissingCommaCheck.cpp | 20 +++++----- .../bugprone/SuspiciousReallocUsageCheck.cpp | 4 +- .../bugprone/SuspiciousSemicolonCheck.cpp | 18 +++++---- .../bugprone/SuspiciousStringCompareCheck.cpp | 8 ++-- .../bugprone/SwappedArgumentsCheck.cpp | 2 +- .../ThrowingStaticInitializationCheck.cpp | 2 +- .../bugprone/TooSmallLoopVariableCheck.cpp | 32 +++++++-------- ...UncheckedStringToNumberConversionCheck.cpp | 5 ++- .../bugprone/UnhandledExceptionAtNewCheck.cpp | 5 ++- .../UnintendedCharOstreamOutputCheck.cpp | 6 +-- .../bugprone/UnsafeFunctionsCheck.cpp | 4 +- .../bugprone/UnusedReturnValueCheck.cpp | 3 +- .../clang-tidy/bugprone/UseAfterMoveCheck.cpp | 6 +-- .../bugprone/VirtualNearMissCheck.cpp | 40 +++++++++---------- 19 files changed, 99 insertions(+), 92 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/StringIntegerAssignmentCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StringIntegerAssignmentCheck.cpp index 93a55ef549896..8454fd1045673 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StringIntegerAssignmentCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StringIntegerAssignmentCheck.cpp @@ -129,7 +129,7 @@ void StringIntegerAssignmentCheck::check( const auto *Argument = Result.Nodes.getNodeAs("expr"); const auto CharType = Result.Nodes.getNodeAs("type")->getCanonicalType(); - SourceLocation Loc = Argument->getBeginLoc(); + const SourceLocation Loc = Argument->getBeginLoc(); // Try to detect a few common expressions to reduce false positives. if (CharExpressionDetector(CharType, *Result.Context) @@ -145,7 +145,7 @@ void StringIntegerAssignmentCheck::check( if (Loc.isMacroID()) return; - bool IsWideCharType = CharType->isWideCharType(); + const bool IsWideCharType = CharType->isWideCharType(); if (!CharType->isCharType() && !IsWideCharType) return; bool IsOneDigit = false; @@ -155,7 +155,7 @@ void StringIntegerAssignmentCheck::check( IsLiteral = true; } - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Argument->getEndLoc(), 0, *Result.SourceManager, getLangOpts()); if (IsOneDigit) { Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "L'" : "'") diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp index 8dbe1c0153f35..ef7f0b5b54eb3 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp @@ -54,7 +54,7 @@ static int enumLength(const EnumDecl *EnumDec) { static bool hasDisjointValueRange(const EnumDecl *Enum1, const EnumDecl *Enum2) { - ValueRange Range1(Enum1), Range2(Enum2); + const ValueRange Range1(Enum1), Range2(Enum2); return llvm::APSInt::compareValues(Range1.MaxVal, Range2.MinVal) < 0 || llvm::APSInt::compareValues(Range2.MaxVal, Range1.MinVal) < 0; } @@ -94,9 +94,9 @@ static int countNonPowOfTwoLiteralNum(const EnumDecl *EnumDec) { /// last enumerator is the sum of the lesser values (and initialized by a /// literal) or when it could contain consecutive values. static bool isPossiblyBitMask(const EnumDecl *EnumDec) { - ValueRange VR(EnumDec); - int EnumLen = enumLength(EnumDec); - int NonPowOfTwoCounter = countNonPowOfTwoLiteralNum(EnumDec); + const ValueRange VR(EnumDec); + const int EnumLen = enumLength(EnumDec); + const int NonPowOfTwoCounter = countNonPowOfTwoLiteralNum(EnumDec); return NonPowOfTwoCounter >= 1 && NonPowOfTwoCounter <= 2 && NonPowOfTwoCounter < EnumLen / 2 && (VR.MaxVal - VR.MinVal != EnumLen - 1) && diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp index aaf0594a02dfc..5abbadafc0d63 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp @@ -66,7 +66,7 @@ void SuspiciousIncludePPCallbacks::InclusionDirective( if (!Check.IgnoredRegexString.empty() && Check.IgnoredRegex.match(FileName)) return; - SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1); + const SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1); const std::optional IFE = utils::getFileExtension(FileName, Check.ImplementationFileExtensions); @@ -81,7 +81,7 @@ void SuspiciousIncludePPCallbacks::InclusionDirective( llvm::sys::path::replace_extension(GuessedFileName, (!HFE.empty() ? "." : "") + HFE); - OptionalFileEntryRef File = + const OptionalFileEntryRef File = PP->LookupFile(DiagLoc, GuessedFileName, IsAngled, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (File) { diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp index d1df2a8634035..7890afb41addb 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp @@ -44,10 +44,10 @@ void SuspiciousMemoryComparisonCheck::check( for (unsigned int ArgIndex = 0; ArgIndex < 2; ++ArgIndex) { const Expr *ArgExpr = CE->getArg(ArgIndex); - QualType ArgType = ArgExpr->IgnoreImplicit()->getType(); + const QualType ArgType = ArgExpr->IgnoreImplicit()->getType(); const Type *PointeeType = ArgType->getPointeeOrArrayElementType(); assert(PointeeType != nullptr && "PointeeType should always be available."); - QualType PointeeQualifiedType(PointeeType, 0); + const QualType PointeeQualifiedType(PointeeType, 0); if (PointeeType->isRecordType()) { if (const RecordDecl *RD = @@ -65,7 +65,7 @@ void SuspiciousMemoryComparisonCheck::check( } if (!PointeeType->isIncompleteType()) { - uint64_t PointeeSize = Ctx.getTypeSize(PointeeType); + const uint64_t PointeeSize = Ctx.getTypeSize(PointeeType); if (ComparedBits && *ComparedBits >= PointeeSize && !Ctx.hasUniqueObjectRepresentations(PointeeQualifiedType)) { diag(CE->getBeginLoc(), diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp index b1d12ba306814..51ae132ce38a6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp @@ -60,7 +60,7 @@ void SuspiciousMemsetUsageCheck::check(const MatchFinder::MatchResult &Result) { // Case 1: fill_char of memset() is a character '0'. Probably an // integer zero was intended. - SourceRange CharRange = CharZeroFill->getSourceRange(); + const SourceRange CharRange = CharZeroFill->getSourceRange(); auto Diag = diag(CharZeroFill->getBeginLoc(), "memset fill value is char '0', " "potentially mistaken for int 0"); @@ -82,7 +82,7 @@ void SuspiciousMemsetUsageCheck::check(const MatchFinder::MatchResult &Result) { if (!NumFill->EvaluateAsInt(EVResult, *Result.Context)) return; - llvm::APSInt NumValue = EVResult.Val.getInt(); + const llvm::APSInt NumValue = EVResult.Val.getInt(); if (NumValue >= 0 && NumValue <= UCharMax) return; @@ -110,7 +110,7 @@ void SuspiciousMemsetUsageCheck::check(const MatchFinder::MatchResult &Result) { Expr::EvalResult EVResult; if (!FillChar->isValueDependent() && FillChar->EvaluateAsInt(EVResult, *Result.Context)) { - llvm::APSInt Value1 = EVResult.Val.getInt(); + const llvm::APSInt Value1 = EVResult.Val.getInt(); if (Value1 == 0 || Value1.isNegative()) return; } @@ -120,8 +120,10 @@ void SuspiciousMemsetUsageCheck::check(const MatchFinder::MatchResult &Result) { // and fix-its to swap the arguments. auto D = diag(Call->getBeginLoc(), "memset of size zero, potentially swapped arguments"); - StringRef RHSString = tooling::fixit::getText(*ByteCount, *Result.Context); - StringRef LHSString = tooling::fixit::getText(*FillChar, *Result.Context); + const StringRef RHSString = + tooling::fixit::getText(*ByteCount, *Result.Context); + const StringRef LHSString = + tooling::fixit::getText(*FillChar, *Result.Context); if (LHSString.empty() || RHSString.empty()) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp index a41f65083653a..cf8bc9794d9ce 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp @@ -19,7 +19,7 @@ static bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, // String literals surrounded by parentheses are assumed to be on purpose. // i.e.: const char* Array[] = { ("a" "b" "c"), "d", [...] }; - TraversalKindScope RAII(*Ctx, TK_AsIs); + const TraversalKindScope RAII(*Ctx, TK_AsIs); auto Parents = Ctx->getParents(*Lit); if (Parents.size() == 1 && Parents[0].get() != nullptr) return true; @@ -35,15 +35,15 @@ static bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, // }; const SourceManager &SM = Ctx->getSourceManager(); bool IndentedCorrectly = true; - SourceLocation FirstToken = Lit->getStrTokenLoc(0); - FileID BaseFID = SM.getFileID(FirstToken); - unsigned int BaseIndent = SM.getSpellingColumnNumber(FirstToken); - unsigned int BaseLine = SM.getSpellingLineNumber(FirstToken); + const SourceLocation FirstToken = Lit->getStrTokenLoc(0); + const FileID BaseFID = SM.getFileID(FirstToken); + const unsigned int BaseIndent = SM.getSpellingColumnNumber(FirstToken); + const unsigned int BaseLine = SM.getSpellingLineNumber(FirstToken); for (unsigned int TokNum = 1; TokNum < Lit->getNumConcatenated(); ++TokNum) { - SourceLocation Token = Lit->getStrTokenLoc(TokNum); - FileID FID = SM.getFileID(Token); - unsigned int Indent = SM.getSpellingColumnNumber(Token); - unsigned int Line = SM.getSpellingLineNumber(Token); + const SourceLocation Token = Lit->getStrTokenLoc(TokNum); + const FileID FID = SM.getFileID(Token); + const unsigned int Indent = SM.getSpellingColumnNumber(Token); + const unsigned int Line = SM.getSpellingLineNumber(Token); if (FID != BaseFID || Line != BaseLine + TokNum || Indent <= BaseIndent) { IndentedCorrectly = false; break; @@ -100,7 +100,7 @@ void SuspiciousMissingCommaCheck::check( assert(InitializerList && ConcatenatedLiteral); // Skip small arrays as they often generate false-positive. - unsigned int Size = InitializerList->getNumInits(); + const unsigned int Size = InitializerList->getNumInits(); if (Size < SizeThreshold) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousReallocUsageCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousReallocUsageCheck.cpp index b5da8016f2cc8..7cc3630204e63 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousReallocUsageCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousReallocUsageCheck.cpp @@ -44,7 +44,7 @@ class IsSamePtrExpr : public StmtVisitor { return false; if (!check(E1->getBase(), E2->getBase())) return false; - DeclAccessPair FD = E1->getFoundDecl(); + const DeclAccessPair FD = E1->getFoundDecl(); return isa(FD.getDecl()) && FD == E2->getFoundDecl(); } @@ -145,7 +145,7 @@ void SuspiciousReallocUsageCheck::check( if (FindAssignToVarBefore{Var, DeclRef, SM}.Visit(Func->getBody())) return; - StringRef CodeOfAssignedExpr = Lexer::getSourceText( + const StringRef CodeOfAssignedExpr = Lexer::getSourceText( CharSourceRange::getTokenRange(PtrResultExpr->getSourceRange()), SM, getLangOpts()); diag(Call->getBeginLoc(), "'%0' may be set to null if 'realloc' fails, which " diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp index 543d31285af8c..9d37fc1e8728e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp @@ -31,7 +31,7 @@ void SuspiciousSemicolonCheck::check(const MatchFinder::MatchResult &Result) { return; const auto *Semicolon = Result.Nodes.getNodeAs("semi"); - SourceLocation LocStart = Semicolon->getBeginLoc(); + const SourceLocation LocStart = Semicolon->getBeginLoc(); if (LocStart.isMacroID()) return; @@ -40,7 +40,7 @@ void SuspiciousSemicolonCheck::check(const MatchFinder::MatchResult &Result) { auto Token = utils::lexer::getPreviousToken(LocStart, Ctxt.getSourceManager(), Ctxt.getLangOpts()); auto &SM = *Result.SourceManager; - unsigned SemicolonLine = SM.getSpellingLineNumber(LocStart); + const unsigned SemicolonLine = SM.getSpellingLineNumber(LocStart); const auto *Statement = Result.Nodes.getNodeAs("stmt"); const bool IsIfStmt = isa(Statement); @@ -49,18 +49,20 @@ void SuspiciousSemicolonCheck::check(const MatchFinder::MatchResult &Result) { SM.getSpellingLineNumber(Token.getLocation()) != SemicolonLine) return; - SourceLocation LocEnd = Semicolon->getEndLoc(); - FileID FID = SM.getFileID(LocEnd); - llvm::MemoryBufferRef Buffer = SM.getBufferOrFake(FID, LocEnd); + const SourceLocation LocEnd = Semicolon->getEndLoc(); + const FileID FID = SM.getFileID(LocEnd); + const llvm::MemoryBufferRef Buffer = SM.getBufferOrFake(FID, LocEnd); Lexer Lexer(SM.getLocForStartOfFile(FID), Ctxt.getLangOpts(), Buffer.getBufferStart(), SM.getCharacterData(LocEnd) + 1, Buffer.getBufferEnd()); if (Lexer.LexFromRawLexer(Token)) return; - unsigned BaseIndent = SM.getSpellingColumnNumber(Statement->getBeginLoc()); - unsigned NewTokenIndent = SM.getSpellingColumnNumber(Token.getLocation()); - unsigned NewTokenLine = SM.getSpellingLineNumber(Token.getLocation()); + const unsigned BaseIndent = + SM.getSpellingColumnNumber(Statement->getBeginLoc()); + const unsigned NewTokenIndent = + SM.getSpellingColumnNumber(Token.getLocation()); + const unsigned NewTokenLine = SM.getSpellingLineNumber(Token.getLocation()); if (!IsIfStmt && NewTokenIndent <= BaseIndent && Token.getKind() != tok::l_brace && NewTokenLine != SemicolonLine) diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp index 7519685418c8c..5da9240de74dc 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp @@ -88,7 +88,7 @@ void SuspiciousStringCompareCheck::registerMatchers(MatchFinder *Finder) { // Add the list of known string compare-like functions and add user-defined // functions. - std::vector FunctionNames = utils::options::parseListPair( + const std::vector FunctionNames = utils::options::parseListPair( KnownStringCompareFunctions, StringCompareLikeFunctions); // Match a call to a string compare functions. @@ -163,7 +163,7 @@ void SuspiciousStringCompareCheck::check( assert(Decl != nullptr && Call != nullptr); if (Result.Nodes.getNodeAs("missing-comparison")) { - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Call->getRParenLoc(), 0, Result.Context->getSourceManager(), getLangOpts()); @@ -173,10 +173,10 @@ void SuspiciousStringCompareCheck::check( } if (const auto *E = Result.Nodes.getNodeAs("logical-not-comparison")) { - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Call->getRParenLoc(), 0, Result.Context->getSourceManager(), getLangOpts()); - SourceLocation NotLoc = E->getBeginLoc(); + const SourceLocation NotLoc = E->getBeginLoc(); diag(Call->getBeginLoc(), "function %0 is compared using logical not operator") diff --git a/clang-tools-extra/clang-tidy/bugprone/SwappedArgumentsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SwappedArgumentsCheck.cpp index bcedff5ef5aa2..152c0cbd106f5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SwappedArgumentsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SwappedArgumentsCheck.cpp @@ -70,7 +70,7 @@ static bool areArgumentsPotentiallySwapped(const QualType LTo, if (LTo == RFrom && REq) return true; - bool LEq = areTypesSemiEqual(LTo, RFrom); + const bool LEq = areTypesSemiEqual(LTo, RFrom); if (RTo == LFrom && LEq) return true; diff --git a/clang-tools-extra/clang-tidy/bugprone/ThrowingStaticInitializationCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ThrowingStaticInitializationCheck.cpp index 56ec5a5af182e..80905e260d5d4 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ThrowingStaticInitializationCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ThrowingStaticInitializationCheck.cpp @@ -44,7 +44,7 @@ void ThrowingStaticInitializationCheck::check( "duration may throw an exception that cannot be caught") << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1); - SourceLocation FuncLocation = Func->getLocation(); + const SourceLocation FuncLocation = Func->getLocation(); if (FuncLocation.isValid()) { diag(FuncLocation, "possibly throwing %select{constructor|function}0 declared here", diff --git a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp index 536b6806c66e6..71b785f1c04f1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp @@ -67,21 +67,21 @@ void TooSmallLoopVariableCheck::storeOptions( /// LoopName: The entire for loop (as a ForStmt) /// void TooSmallLoopVariableCheck::registerMatchers(MatchFinder *Finder) { - StatementMatcher LoopVarMatcher = + const StatementMatcher LoopVarMatcher = expr(ignoringParenImpCasts( anyOf(declRefExpr(to(varDecl(hasType(isInteger())))), memberExpr(member(fieldDecl(hasType(isInteger()))))))) .bind(LoopVarName); // We need to catch only those comparisons which contain any integer cast. - StatementMatcher LoopVarConversionMatcher = traverse( + const StatementMatcher LoopVarConversionMatcher = traverse( TK_AsIs, implicitCastExpr(hasImplicitDestinationType(isInteger()), has(ignoringParenImpCasts(LoopVarMatcher))) .bind(LoopVarCastName)); // We are interested in only those cases when the loop bound is a variable // value (not const, enum, etc.). - StatementMatcher LoopBoundMatcher = + const StatementMatcher LoopBoundMatcher = expr(ignoringParenImpCasts(allOf( hasType(isInteger()), unless(integerLiteral()), unless(allOf( @@ -94,7 +94,7 @@ void TooSmallLoopVariableCheck::registerMatchers(MatchFinder *Finder) { // We use the loop increment expression only to make sure we found the right // loop variable. - StatementMatcher IncrementMatcher = + const StatementMatcher IncrementMatcher = expr(ignoringParenImpCasts(hasType(isInteger()))).bind(LoopIncrementName); Finder->addMatcher( @@ -121,14 +121,14 @@ static MagnitudeBits calcMagnitudeBits(const ASTContext &Context, const Expr *IntExpr) { assert(IntExprType->isIntegerType()); - unsigned SignedBits = IntExprType->isUnsignedIntegerType() ? 0U : 1U; + const unsigned SignedBits = IntExprType->isUnsignedIntegerType() ? 0U : 1U; if (const auto *BitField = IntExpr->getSourceBitField()) { - unsigned BitFieldWidth = BitField->getBitWidthValue(); + const unsigned BitFieldWidth = BitField->getBitWidthValue(); return {BitFieldWidth - SignedBits, BitFieldWidth}; } - unsigned IntWidth = Context.getIntWidth(IntExprType); + const unsigned IntWidth = Context.getIntWidth(IntExprType); return {IntWidth - SignedBits, 0U}; } @@ -143,18 +143,18 @@ calcUpperBoundMagnitudeBits(const ASTContext &Context, const Expr *UpperBound, const Expr *RHSE = BinOperator->getRHS()->IgnoreParenImpCasts(); const Expr *LHSE = BinOperator->getLHS()->IgnoreParenImpCasts(); - QualType RHSEType = RHSE->getType(); - QualType LHSEType = LHSE->getType(); + const QualType RHSEType = RHSE->getType(); + const QualType LHSEType = LHSE->getType(); if (!RHSEType->isIntegerType() || !LHSEType->isIntegerType()) return {}; - bool RHSEIsConstantValue = RHSEType->isEnumeralType() || - RHSEType.isConstQualified() || - isa(RHSE); - bool LHSEIsConstantValue = LHSEType->isEnumeralType() || - LHSEType.isConstQualified() || - isa(LHSE); + const bool RHSEIsConstantValue = RHSEType->isEnumeralType() || + RHSEType.isConstQualified() || + isa(RHSE); + const bool LHSEIsConstantValue = LHSEType->isEnumeralType() || + LHSEType.isConstQualified() || + isa(LHSE); // Avoid false positives produced by two constant values. if (RHSEIsConstantValue && LHSEIsConstantValue) @@ -193,7 +193,7 @@ void TooSmallLoopVariableCheck::check(const MatchFinder::MatchResult &Result) { if (LoopVar->getType() != LoopIncrement->getType()) return; - ASTContext &Context = *Result.Context; + const ASTContext &Context = *Result.Context; const QualType LoopVarType = LoopVar->getType(); const MagnitudeBits LoopVarMagnitudeBits = diff --git a/clang-tools-extra/clang-tidy/bugprone/UncheckedStringToNumberConversionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UncheckedStringToNumberConversionCheck.cpp index d0bf72b35ba8f..b82c9d3ffc55b 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UncheckedStringToNumberConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UncheckedStringToNumberConversionCheck.cpp @@ -76,7 +76,8 @@ static ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO, // Get the conversion specifier and use it to determine the conversion // kind. - analyze_scanf::ScanfConversionSpecifier SCS = FS.getConversionSpecifier(); + const analyze_scanf::ScanfConversionSpecifier SCS = + FS.getConversionSpecifier(); if (SCS.isIntArg()) { switch (FS.getLengthModifier().getKind()) { case analyze_scanf::LengthModifier::AsLongLong: @@ -194,7 +195,7 @@ void UncheckedStringToNumberConversionCheck::check( // The format string comes from the call expression and depends on which // flavor of scanf is called. // Index 0: scanf, vscanf, Index 1: fscanf, sscanf, vfscanf, vsscanf. - unsigned Idx = + const unsigned Idx = (FFD->getName() == "scanf" || FFD->getName() == "vscanf") ? 0 : 1; // Given the index, see if the call expression argument at that index is diff --git a/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp index bf30753f0e5ef..340b136700c5f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp @@ -16,7 +16,8 @@ namespace { AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { - for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { + const unsigned NH = Node.getNumHandlers(); + for (unsigned I = 0; I < NH; ++I) { const CXXCatchStmt *CatchS = Node.getHandler(I); // Check for generic catch handler (match anything). if (CatchS->getCaughtType().isNull()) @@ -31,7 +32,7 @@ AST_MATCHER_P(CXXTryStmt, hasHandlerFor, } AST_MATCHER(CXXNewExpr, mayThrow) { - FunctionDecl *OperatorNew = Node.getOperatorNew(); + const FunctionDecl *OperatorNew = Node.getOperatorNew(); if (!OperatorNew) return false; return !OperatorNew->getType()->castAs()->isNothrow(); diff --git a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp index bce46572bdeb9..e10b17ca20753 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp @@ -80,17 +80,17 @@ void UnintendedCharOstreamOutputCheck::check( const Expr *Value = Call->getArg(1); const SourceRange SourceRange = Value->getSourceRange(); - DiagnosticBuilder Builder = + const DiagnosticBuilder Builder = diag(Call->getOperatorLoc(), "%0 passed to 'operator<<' outputs as character instead of integer. " "cast to 'unsigned int' to print numeric value or cast to 'char' to " "print as character") << Value->getType() << SourceRange; - QualType T = Value->getType(); + const QualType T = Value->getType(); const Type *UnqualifiedDesugaredType = T->getUnqualifiedDesugaredType(); - llvm::StringRef CastType = CastTypeName.value_or( + const llvm::StringRef CastType = CastTypeName.value_or( UnqualifiedDesugaredType->isSpecificBuiltinType(BuiltinType::SChar) ? "int" : "unsigned int"); diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp index 61ccd26e48c1e..5524c4b484be1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp @@ -141,7 +141,7 @@ parseCheckedFunctions(StringRef Option, ClangTidyContext *Context) { std::vector Result; Result.reserve(Functions.size()); - for (StringRef Function : Functions) { + for (const StringRef Function : Functions) { if (Function.empty()) continue; @@ -301,7 +301,7 @@ void UnsafeFunctionsCheck::check(const MatchFinder::MatchResult &Result) { if (Custom) { for (const auto &Entry : CustomFunctions) { if (Entry.Pattern.match(*FuncDecl)) { - StringRef Reason = + const StringRef Reason = Entry.Reason.empty() ? "is marked as unsafe" : Entry.Reason.c_str(); if (Entry.Replacement.empty()) { diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp index c2fc4af86391d..6fbd3922b532d 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp @@ -25,7 +25,8 @@ namespace { // member function are matched directly with InnerMatcher. AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, Matcher, InnerMatcher) { - FunctionDecl *InstantiatedFrom = Node.getInstantiatedFromMemberFunction(); + const FunctionDecl *InstantiatedFrom = + Node.getInstantiatedFromMemberFunction(); return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node, Finder, Builder); } diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp index efb5ec64689cf..6d134a0e896a0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp @@ -255,7 +255,7 @@ static bool isStandardSmartPointer(const ValueDecl *VD) { if (!ID) return false; - StringRef Name = ID->getName(); + const StringRef Name = ID->getName(); if (Name != "unique_ptr" && Name != "shared_ptr" && Name != "weak_ptr") return false; @@ -369,7 +369,7 @@ void UseAfterMoveFinder::getReinits( if (!S) continue; - SmallVector Matches = + const SmallVector Matches = match(findAll(ReinitMatcher), *S->getStmt(), *Context); for (const auto &Match : Matches) { @@ -506,7 +506,7 @@ void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) { if (ContainingCtorInit) { // Collect the constructor initializer expressions. bool BeforeMove{true}; - for (CXXCtorInitializer *Init : ContainingCtor->inits()) { + for (const CXXCtorInitializer *Init : ContainingCtor->inits()) { if (BeforeMove && Init->getInit()->IgnoreImplicit() == ContainingCtorInit->IgnoreImplicit()) BeforeMove = false; diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp index cef8b4da7fc17..0d69b9fd88213 100644 --- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp @@ -37,14 +37,14 @@ static bool isOverrideMethod(const CXXMethodDecl *MD) { static bool checkOverridingFunctionReturnType(const ASTContext *Context, const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD) { - QualType BaseReturnTy = BaseMD->getType() - ->castAs() - ->getReturnType() - .getCanonicalType(); - QualType DerivedReturnTy = DerivedMD->getType() - ->castAs() - ->getReturnType() - .getCanonicalType(); + const QualType BaseReturnTy = BaseMD->getType() + ->castAs() + ->getReturnType() + .getCanonicalType(); + const QualType DerivedReturnTy = DerivedMD->getType() + ->castAs() + ->getReturnType() + .getCanonicalType(); if (DerivedReturnTy->isDependentType() || BaseReturnTy->isDependentType()) return false; @@ -63,8 +63,8 @@ static bool checkOverridingFunctionReturnType(const ASTContext *Context, /// BTy is the class type in return type of BaseMD. For example, /// B* Base::md() /// While BRD is the declaration of B. - QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType(); - QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType(); + const QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType(); + const QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType(); const CXXRecordDecl *DRD = DTy->getAsCXXRecordDecl(); const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl(); @@ -94,7 +94,7 @@ static bool checkOverridingFunctionReturnType(const ASTContext *Context, // Check accessibility. // FIXME: We currently only support checking if B is accessible base class // of D, or D is the same class which DerivedMD is in. - bool IsItself = + const bool IsItself = DRD->getCanonicalDecl() == DerivedMD->getParent()->getCanonicalDecl(); bool HasPublicAccess = false; for (const auto &Path : Paths) { @@ -129,8 +129,8 @@ static QualType getDecayedType(QualType Type) { /// \returns true if the param types are the same. static bool checkParamTypes(const CXXMethodDecl *BaseMD, const CXXMethodDecl *DerivedMD) { - unsigned NumParamA = BaseMD->getNumParams(); - unsigned NumParamB = DerivedMD->getNumParams(); + const unsigned NumParamA = BaseMD->getNumParams(); + const unsigned NumParamB = DerivedMD->getNumParams(); if (NumParamA != NumParamB) return false; @@ -184,10 +184,10 @@ bool VirtualNearMissCheck::isPossibleToBeOverridden( if (!Inserted) return Iter->second; - bool IsPossible = !BaseMD->isImplicit() && !isa(BaseMD) && - !isa(BaseMD) && BaseMD->isVirtual() && - !BaseMD->isOverloadedOperator() && - !isa(BaseMD); + const bool IsPossible = + !BaseMD->isImplicit() && !isa(BaseMD) && + !isa(BaseMD) && BaseMD->isVirtual() && + !BaseMD->isOverloadedOperator() && !isa(BaseMD); Iter->second = IsPossible; return IsPossible; } @@ -241,7 +241,7 @@ void VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) { if (isOverriddenByDerivedClass(BaseMD, DerivedRD)) continue; - unsigned EditDistance = BaseMD->getName().edit_distance( + const unsigned EditDistance = BaseMD->getName().edit_distance( DerivedMD->getName(), EditDistanceThreshold); if (EditDistance > 0 && EditDistance <= EditDistanceThreshold) { if (checkOverrideWithoutName(Context, BaseMD, DerivedMD)) { @@ -249,8 +249,8 @@ void VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) { auto Range = CharSourceRange::getTokenRange( SourceRange(DerivedMD->getLocation())); - bool ApplyFix = !BaseMD->isTemplateInstantiation() && - !DerivedMD->isTemplateInstantiation(); + const bool ApplyFix = !BaseMD->isTemplateInstantiation() && + !DerivedMD->isTemplateInstantiation(); auto Diag = diag(DerivedMD->getBeginLoc(), "method '%0' has a similar name and the same signature as " From 6313830d07147665c8a43b42110dae7c12e60186 Mon Sep 17 00:00:00 2001 From: Walter Lee <49250218+googlewalt@users.noreply.github.com> Date: Sat, 8 Nov 2025 10:32:39 -0500 Subject: [PATCH 08/18] Fix missing include from #166664 --- lldb/include/lldb/lldb-private-interfaces.h | 1 + 1 file changed, 1 insertion(+) diff --git a/lldb/include/lldb/lldb-private-interfaces.h b/lldb/include/lldb/lldb-private-interfaces.h index 2fe3af7c62e00..5fc5c14c52f9e 100644 --- a/lldb/include/lldb/lldb-private-interfaces.h +++ b/lldb/include/lldb/lldb-private-interfaces.h @@ -15,6 +15,7 @@ #include "lldb/lldb-types.h" #include #include +#include namespace llvm { namespace json { From d838ca21cade5c5a473c4dbb0433e84a20d95c46 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 8 Nov 2025 07:40:52 -0800 Subject: [PATCH 09/18] [clang-doc] Remove an unused local variable (NFC) (#167104) Identified with bugprone-unused-local-non-trivial-variable. --- clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp b/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp index 3650f66ec39bd..1e757101549c6 100644 --- a/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp +++ b/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp @@ -156,7 +156,6 @@ Error MustacheHTMLGenerator::generateDocs( SmallString<128> JSONPath; sys::path::native(RootDir.str() + "/json", JSONPath); - StringMap JSONFileMap; { llvm::TimeTraceScope TS("Iterate JSON files"); std::error_code EC; From ee0652b4da980785f34a35d6a3aedf1c4cb30668 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 8 Nov 2025 07:40:59 -0800 Subject: [PATCH 10/18] [flang] Remove unused local variables (NFC) (#167105) Identified with bugprone-unused-local-non-trivial-variable. --- flang/lib/Optimizer/CodeGen/LowerRepackArrays.cpp | 1 - flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp | 3 --- flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp | 1 - 3 files changed, 5 deletions(-) diff --git a/flang/lib/Optimizer/CodeGen/LowerRepackArrays.cpp b/flang/lib/Optimizer/CodeGen/LowerRepackArrays.cpp index ac432c74f0147..81488d75d0ab6 100644 --- a/flang/lib/Optimizer/CodeGen/LowerRepackArrays.cpp +++ b/flang/lib/Optimizer/CodeGen/LowerRepackArrays.cpp @@ -289,7 +289,6 @@ PackArrayConversion::genRepackedBox(fir::FirOpBuilder &builder, fir::factory::genDimInfoFromBox(builder, loc, box, &lbounds, &extents, /*strides=*/nullptr); // Get the type parameters from the box, if needed. - llvm::SmallVector assumedTypeParams; if (numTypeParams != 0) { if (auto charType = mlir::dyn_cast(boxType.unwrapInnerType())) diff --git a/flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp b/flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp index 1229018bd9b3e..9aad8cddc60a1 100644 --- a/flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp +++ b/flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp @@ -692,9 +692,6 @@ class DoConcurrentConversion if (!targetShapeCreationInfo.isShapedValue()) return {}; - llvm::SmallVector extentOperands; - llvm::SmallVector startIndexOperands; - if (targetShapeCreationInfo.isShapeShiftedValue()) { llvm::SmallVector shapeShiftOperands; diff --git a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp index 49a085ee3b336..49ae189d0b758 100644 --- a/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp +++ b/flang/lib/Optimizer/Transforms/SimplifyIntrinsics.cpp @@ -730,7 +730,6 @@ static void genRuntimeMinMaxlocBody(fir::FirOpBuilder &builder, mlir::Value ifCompatElem = fir::ConvertOp::create(builder, loc, ifCompatType, maskElem); - llvm::SmallVector resultsTy = {elementType, elementType}; fir::IfOp ifOp = fir::IfOp::create(builder, loc, elementType, ifCompatElem, /*withElseRegion=*/true); From 0028ef667a87af0ff6265d855da0bb24e845baf3 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 8 Nov 2025 07:41:07 -0800 Subject: [PATCH 11/18] [llvm] Remove unused local variables (NFC) (#167106) Identified with bugprone-unused-local-non-trivial-variable. --- llvm/lib/CAS/UnifiedOnDiskCache.cpp | 2 -- llvm/lib/CodeGen/WindowsSecureHotPatching.cpp | 2 -- llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp | 1 - llvm/lib/Transforms/IPO/SampleProfile.cpp | 1 - llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp | 2 -- 5 files changed, 8 deletions(-) diff --git a/llvm/lib/CAS/UnifiedOnDiskCache.cpp b/llvm/lib/CAS/UnifiedOnDiskCache.cpp index 7b790bb005ce9..e6b676accb0fe 100644 --- a/llvm/lib/CAS/UnifiedOnDiskCache.cpp +++ b/llvm/lib/CAS/UnifiedOnDiskCache.cpp @@ -331,8 +331,6 @@ Expected UnifiedOnDiskCache::validateIfNeeded( if (Error E = getBootTime().moveInto(BootTime)) return std::move(E); - std::string LogValidationError; - if (ValidationBootTime == BootTime && !ForceValidation) return ValidationResult::Skipped; diff --git a/llvm/lib/CodeGen/WindowsSecureHotPatching.cpp b/llvm/lib/CodeGen/WindowsSecureHotPatching.cpp index fd54190b04468..dab1416d254a2 100644 --- a/llvm/lib/CodeGen/WindowsSecureHotPatching.cpp +++ b/llvm/lib/CodeGen/WindowsSecureHotPatching.cpp @@ -461,8 +461,6 @@ static bool searchConstantExprForGlobalVariables( Value *V, SmallDenseMap &GVLoadMap, SmallVector &GVUses) { - SmallVector ReplacedOperands; - if (GlobalVariable *GV = dyn_cast(V)) { if (globalVariableNeedsRedirect(GV)) { GVLoadMap[GV] = nullptr; diff --git a/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp b/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp index 597d311989b2f..1719165fb6717 100644 --- a/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp +++ b/llvm/lib/Target/ARM/ARMLowOverheadLoops.cpp @@ -1051,7 +1051,6 @@ bool LowOverheadLoop::ValidateLiveOuts() { // check where it gets its false lanes from, if any. int InactiveIdx = findVPTInactiveOperandIdx(*MI); if (InactiveIdx != -1) { - SmallPtrSet Defs; MachineInstr *FalseSrc = RDI.getUniqueReachingMIDef( MI, MI->getOperand(InactiveIdx).getReg()); if (FalseSrc) { diff --git a/llvm/lib/Transforms/IPO/SampleProfile.cpp b/llvm/lib/Transforms/IPO/SampleProfile.cpp index e39e311dd795f..bd74388aaf217 100644 --- a/llvm/lib/Transforms/IPO/SampleProfile.cpp +++ b/llvm/lib/Transforms/IPO/SampleProfile.cpp @@ -2293,7 +2293,6 @@ bool SampleProfileLoader::runOnFunction(Function &F, // count value. if (!F.getEntryCount()) F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); - std::unique_ptr OwnedORE; auto &FAM = AM.getResult(*F.getParent()) .getManager(); ORE = &FAM.getResult(F); diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp index df835a077f2a0..c27d1ac99dd80 100644 --- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp +++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp @@ -5368,7 +5368,6 @@ class BoUpSLP { Lane = P.first->ReorderIndices[Lane]; assert(Lane < static_cast(P.first->Scalars.size()) && "Couldn't find extract lane"); - SmallVector OpIndices; for (unsigned OpIdx : seq(::getNumberOfPotentiallyCommutativeOps( P.first->getMainOp()))) { @@ -8815,7 +8814,6 @@ void BoUpSLP::buildExternalUses( const ExtraValueToDebugLocsMap &ExternallyUsedValues) { const size_t NumVectScalars = ScalarToTreeEntries.size() + 1; DenseMap ScalarToExtUses; - SmallPtrSet ExternalUsers; // Collect the values that we need to extract from the tree. for (auto &TEPtr : VectorizableTree) { TreeEntry *Entry = TEPtr.get(); From 2844d867340a1f4a0d4c4e09ec67f9de5213228e Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 8 Nov 2025 07:41:15 -0800 Subject: [PATCH 12/18] [mlir] Remove unused local variables (NFC) (#167107) Identified with bugprone-unused-local-non-trivial-variable. --- mlir/lib/Dialect/Affine/Utils/Utils.cpp | 3 --- mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp | 2 -- mlir/lib/Dialect/OpenACC/Transforms/ACCImplicitData.cpp | 1 - mlir/lib/Dialect/SCF/Transforms/ParallelForToNestedFors.cpp | 1 - 4 files changed, 7 deletions(-) diff --git a/mlir/lib/Dialect/Affine/Utils/Utils.cpp b/mlir/lib/Dialect/Affine/Utils/Utils.cpp index 845be20d15b69..deba1600e28a0 100644 --- a/mlir/lib/Dialect/Affine/Utils/Utils.cpp +++ b/mlir/lib/Dialect/Affine/Utils/Utils.cpp @@ -1327,9 +1327,6 @@ LogicalResult mlir::affine::replaceAllMemRefUsesWith( assert(cast(oldMemRef.getType()).getElementType() == cast(newMemRef.getType()).getElementType()); - std::unique_ptr domInfo; - std::unique_ptr postDomInfo; - // Walk all uses of old memref; collect ops to perform replacement. We use a // DenseSet since an operation could potentially have multiple uses of a // memref (although rare), and the replacement later is going to erase ops. diff --git a/mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp b/mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp index 57b610b31e964..8a0440bcc6fb9 100644 --- a/mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp +++ b/mlir/lib/Dialect/Linalg/Transforms/TilingInterfaceImpl.cpp @@ -216,8 +216,6 @@ struct LinalgOpTilingInterface SmallVectorImpl &iterDomainSizes) const { auto linalgOp = cast(op); - std::optional> iterationSpaceOffsets, - iterationSpaceSizes; SmallVector indexingMaps = llvm::map_to_vector(operandNumbers, [&](unsigned operandNumber) { OpOperand &opOperand = linalgOp->getOpOperand(operandNumber); diff --git a/mlir/lib/Dialect/OpenACC/Transforms/ACCImplicitData.cpp b/mlir/lib/Dialect/OpenACC/Transforms/ACCImplicitData.cpp index a99e4846eea20..91262bd76ca31 100644 --- a/mlir/lib/Dialect/OpenACC/Transforms/ACCImplicitData.cpp +++ b/mlir/lib/Dialect/OpenACC/Transforms/ACCImplicitData.cpp @@ -571,7 +571,6 @@ Operation *ACCImplicitData::generateDataClauseOpForCandidate( /*structured=*/true, /*implicit=*/true, accSupport.getVariableName(var)); } else { - SmallVector bounds; auto copyinOp = acc::CopyinOp::create(builder, loc, var, /*structured=*/true, /*implicit=*/true, diff --git a/mlir/lib/Dialect/SCF/Transforms/ParallelForToNestedFors.cpp b/mlir/lib/Dialect/SCF/Transforms/ParallelForToNestedFors.cpp index 8f7d5e308f433..c469a991fff64 100644 --- a/mlir/lib/Dialect/SCF/Transforms/ParallelForToNestedFors.cpp +++ b/mlir/lib/Dialect/SCF/Transforms/ParallelForToNestedFors.cpp @@ -44,7 +44,6 @@ mlir::scf::parallelForToNestedFors(RewriterBase &rewriter, lowerBounds.size() == steps.size() && "Mismatched parallel loop bounds"); - SmallVector ivs; scf::LoopNest loopNest = scf::buildLoopNest(rewriter, loc, lowerBounds, upperBounds, steps); From ce7f9f9ccde9c09b0aed3dc9bccee325fca766e0 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 8 Nov 2025 07:41:23 -0800 Subject: [PATCH 13/18] [llvm] Proofread *.rst (#167108) This patch is limited to single-word replacements to fix spelling and/or grammar to ease the review process. Punctuation and markdown fixes are specifically excluded. --- llvm/docs/AMDGPUUsage.rst | 10 +++++----- llvm/docs/AddingConstrainedIntrinsics.rst | 2 +- llvm/docs/Atomics.rst | 2 +- llvm/docs/BranchWeightMetadata.rst | 4 ++-- llvm/docs/CIBestPractices.rst | 2 +- llvm/docs/CompileCudaWithLLVM.rst | 4 ++-- llvm/docs/Coroutines.rst | 12 ++++++------ llvm/docs/Docker.rst | 4 ++-- llvm/docs/Extensions.rst | 4 ++-- llvm/docs/FatLTO.rst | 2 +- llvm/docs/FaultMaps.rst | 4 ++-- llvm/docs/GarbageCollection.rst | 2 +- llvm/docs/GetElementPtr.rst | 4 ++-- llvm/docs/GettingInvolved.rst | 2 +- llvm/docs/GettingStartedVS.rst | 2 +- llvm/docs/GwpAsan.rst | 2 +- llvm/docs/HowToBuildWindowsItaniumPrograms.rst | 2 +- 17 files changed, 32 insertions(+), 32 deletions(-) diff --git a/llvm/docs/AMDGPUUsage.rst b/llvm/docs/AMDGPUUsage.rst index 30b24b2f6f033..ba0e53bceade8 100644 --- a/llvm/docs/AMDGPUUsage.rst +++ b/llvm/docs/AMDGPUUsage.rst @@ -2690,7 +2690,7 @@ are deprecated and should not be used. ``vendor_name_size`` and ``architecture_name_size`` are the length of the vendor and architecture names respectively, including the NUL character. - ``vendor_and_architecture_name`` contains the NUL terminates string for the + ``vendor_and_architecture_name`` contains the NUL terminated string for the vendor, immediately followed by the NUL terminated string for the architecture. @@ -3382,7 +3382,7 @@ location. If the lane is inactive, but was active on entry to the subprogram, then this is the program location in the subprogram at which execution of the lane is -conceptual positioned. +conceptually positioned. If the lane was not active on entry to the subprogram, then this will be the undefined location. A client debugger can check if the lane is part of a valid @@ -4754,7 +4754,7 @@ same *vendor-name*. "image", or "pipe". This may be more restrictive than indicated by ".access" to reflect what the - kernel actual does. If not + kernel actually does. If not present then the runtime must assume what is implied by ".access" and ".is_const" . Values @@ -5133,7 +5133,7 @@ supported except by flat and scratch instructions in GFX9-GFX11. The generic address space uses the hardware flat address support available in GFX7-GFX11. This uses two fixed ranges of virtual addresses (the private and -local apertures), that are outside the range of addressible global memory, to +local apertures), that are outside the range of addressable global memory, to map from a flat address to a private or local address. FLAT instructions can take a flat address and access global, private (scratch) @@ -6586,7 +6586,7 @@ Acquire memory ordering is not meaningful on store atomic instructions and is treated as non-atomic. Release memory ordering is not meaningful on load atomic instructions and is -treated a non-atomic. +treated as non-atomic. Acquire-release memory ordering is not meaningful on load or store atomic instructions and is treated as acquire and release respectively. diff --git a/llvm/docs/AddingConstrainedIntrinsics.rst b/llvm/docs/AddingConstrainedIntrinsics.rst index bd14f121144ca..41e7dece6dd8b 100644 --- a/llvm/docs/AddingConstrainedIntrinsics.rst +++ b/llvm/docs/AddingConstrainedIntrinsics.rst @@ -31,7 +31,7 @@ node ``FADD`` must be ``STRICT_FADD``. Update mappings =============== -Add new record to the mapping of instructions to constrained intrinsic and +Add new record to the mapping of instructions to constrained intrinsics and DAG nodes:: include/llvm/IR/ConstrainedOps.def diff --git a/llvm/docs/Atomics.rst b/llvm/docs/Atomics.rst index 522aed150bf62..1bcd864dd15bf 100644 --- a/llvm/docs/Atomics.rst +++ b/llvm/docs/Atomics.rst @@ -408,7 +408,7 @@ operations: MemoryDependencyAnalysis (which is also used by other passes like GVN). * Folding a load: Any atomic load from a constant global can be constant-folded, - because it cannot be observed. Similar reasoning allows sroa with + because it cannot be observed. Similar reasoning allows SROA with atomic loads and stores. Atomics and Codegen diff --git a/llvm/docs/BranchWeightMetadata.rst b/llvm/docs/BranchWeightMetadata.rst index 3fa21720d25fc..71d7a7d3a6c05 100644 --- a/llvm/docs/BranchWeightMetadata.rst +++ b/llvm/docs/BranchWeightMetadata.rst @@ -92,7 +92,7 @@ The second weight is optional and corresponds to the unwind branch. If only one weight is set, then it contains the execution count of the call and used in SamplePGO mode only as described for the call instruction. If both weights are specified then the second weight contains the count of unwind branch -taken and the first weights contains the execution count of the call minus +taken and the first weight contains the execution count of the call minus the count of unwind branch taken. Both weights specified are used to calculate BranchProbability as for BranchInst and for SamplePGO the sum of both weights is used. @@ -223,7 +223,7 @@ indicates that it was called 2,590 times at runtime. !1 = !{!"function_entry_count", i64 2590} If "function_entry_count" has more than 2 operands, the subsequent operands are -the GUID of the functions that needs to be imported by ThinLTO. This is only +the GUID of the functions that need to be imported by ThinLTO. This is only set by sampling-based profile. It is needed because the sampling-based profile was collected on a binary that had already imported and inlined these functions, and we need to ensure the IR matches in the ThinLTO backends for profile diff --git a/llvm/docs/CIBestPractices.rst b/llvm/docs/CIBestPractices.rst index 855e2ccac8ece..a2270daf6cded 100644 --- a/llvm/docs/CIBestPractices.rst +++ b/llvm/docs/CIBestPractices.rst @@ -146,7 +146,7 @@ for LLVM infrastructure. Using Fully Qualified Container Names ------------------------------------- -When referencing container images from a registry, such as in Github Actions +When referencing container images from a registry, such as in GitHub Actions workflows, or in ``Dockerfile`` files used for building images, prefer fully qualified names (i.e., including the registry domain) over just the image. For example, prefer ``docker.io/ubuntu:24.04`` over ``ubuntu:24.04``. This diff --git a/llvm/docs/CompileCudaWithLLVM.rst b/llvm/docs/CompileCudaWithLLVM.rst index 376d8ee550c99..0bd121a895028 100644 --- a/llvm/docs/CompileCudaWithLLVM.rst +++ b/llvm/docs/CompileCudaWithLLVM.rst @@ -36,7 +36,7 @@ CUDA installation on a handful of common Linux distributions, but in general the most reliable way to make it work is to install CUDA in a single directory from NVIDIA's `.run` package and specify its location via `--cuda-path=...` argument. -CUDA compilation is supported on Linux. Compilation on MacOS and Windows may or +CUDA compilation is supported on Linux. Compilation on macOS and Windows may or may not work and currently have no maintainers. Invoking clang @@ -64,7 +64,7 @@ brackets as described below: y[2] = 6 y[3] = 8 -On MacOS, replace `-lcudart_static` with `-lcudart`; otherwise, you may get +On macOS, replace `-lcudart_static` with `-lcudart`; otherwise, you may get "CUDA driver version is insufficient for CUDA runtime version" errors when you run your program. diff --git a/llvm/docs/Coroutines.rst b/llvm/docs/Coroutines.rst index 13d2da42eaca7..0e6b49c84acee 100644 --- a/llvm/docs/Coroutines.rst +++ b/llvm/docs/Coroutines.rst @@ -193,7 +193,7 @@ Values live across a suspend point need to be stored in the coroutine frame to be available in the continuation function. This frame is stored as a tail to the `async context`. -Every suspend point takes an `context projection function` argument which +Every suspend point takes a `context projection function` argument which describes how-to obtain the continuations `async context` and every suspend point has an associated `resume function` denoted by the `llvm.coro.async.resume` intrinsic. The coroutine is resumed by calling this @@ -221,7 +221,7 @@ a parameter to the `llvm.coro.suspend.async` intrinsic. ptr %resume_func_ptr, ptr %context_projection_function -The frontend should provide a `async function pointer` struct associated with +The frontend should provide an `async function pointer` struct associated with each async coroutine by `llvm.coro.id.async`'s argument. The initial size and alignment of the `async context` must be provided as arguments to the `llvm.coro.id.async` intrinsic. Lowering will update the size entry with the @@ -314,7 +314,7 @@ coroutine handle. The second parameter of `coro.begin` is given a block of memor to be used if the coroutine frame needs to be allocated dynamically. The `coro.id`_ intrinsic serves as coroutine identity useful in cases when the -`coro.begin`_ intrinsic get duplicated by optimization passes such as +`coro.begin`_ intrinsic gets duplicated by optimization passes such as jump-threading. The `cleanup` block destroys the coroutine frame. The `coro.free`_ intrinsic, @@ -2149,7 +2149,7 @@ CoroEarly The CoroEarly pass ensures later middle end passes correctly interpret coroutine semantics and lowers coroutine intrinsics that not needed to be preserved to help later coroutine passes. This pass lowers `coro.promise`_, `coro.frame`_ and -`coro.done`_ intrinsics. Afterwards, it replace uses of promise alloca with +`coro.done`_ intrinsics. Afterwards, it replaces uses of promise alloca with `coro.promise`_ intrinsic. .. _CoroSplit: @@ -2188,7 +2188,7 @@ Attributes coro_only_destroy_when_complete ------------------------------- -When the coroutine are marked with coro_only_destroy_when_complete, it indicates +When the coroutine is marked with coro_only_destroy_when_complete, it indicates the coroutine must reach the final suspend point when it get destroyed. This attribute only works for switched-resume coroutines now. @@ -2199,7 +2199,7 @@ coro_elide_safe When a Call or Invoke instruction to switch ABI coroutine `f` is marked with `coro_elide_safe`, CoroSplitPass generates a `f.noalloc` ramp function. `f.noalloc` has one more argument than its original ramp function `f`, which is -the pointer to the allocated frame. `f.noalloc` also suppressed any allocations +the pointer to the allocated frame. `f.noalloc` also suppresses any allocations or deallocations that may be guarded by `@llvm.coro.alloc` and `@llvm.coro.free`. CoroAnnotationElidePass performs the heap elision when possible. Note that for diff --git a/llvm/docs/Docker.rst b/llvm/docs/Docker.rst index 5f8e619d8b5eb..29078d1f79fdb 100644 --- a/llvm/docs/Docker.rst +++ b/llvm/docs/Docker.rst @@ -16,7 +16,7 @@ to fill out in order to produce Dockerfiles for a new docker image. Why? ---- Docker images provide a way to produce binary distributions of -software inside a controlled environment. Having Dockerfiles to builds docker images +software inside a controlled environment. Having Dockerfiles to build docker images inside LLVM repo makes them much more discoverable than putting them into any other place. @@ -35,7 +35,7 @@ A snapshot of a docker container filesystem is called a *docker image*. One can start a container from a prebuilt docker image. Docker images are built from a so-called *Dockerfile*, a source file written in -a specialized language that defines instructions to be used when build +a specialized language that defines instructions to be used when building the docker image (see `official documentation `_ for more details). A minimal Dockerfile typically contains a base image and a number diff --git a/llvm/docs/Extensions.rst b/llvm/docs/Extensions.rst index 4bff111327248..0d7f599548fb7 100644 --- a/llvm/docs/Extensions.rst +++ b/llvm/docs/Extensions.rst @@ -792,7 +792,7 @@ emission of Variable Length Arrays (VLAs). The Windows ARM Itanium ABI extends the base ABI by adding support for emitting a dynamic stack allocation. When emitting a variable stack allocation, a call to ``__chkstk`` is emitted unconditionally to ensure that guard pages are setup -properly. The emission of this stack probe emission is handled similar to the +properly. The emission of this stack probe emission is handled similarly to the standard stack probe emission. The MSVC environment does not emit code for VLAs currently. @@ -813,7 +813,7 @@ in the following fashion: sub sp, sp, x15, lsl #4 However, this has the limitation of 256 MiB (±128MiB). In order to accommodate -larger binaries, LLVM supports the use of ``-mcmodel=large`` to allow a 8GiB +larger binaries, LLVM supports the use of ``-mcmodel=large`` to allow an 8GiB (±4GiB) range via a slight deviation. It will generate an indirect jump as follows: diff --git a/llvm/docs/FatLTO.rst b/llvm/docs/FatLTO.rst index 5864944332fc0..c883513feb6ba 100644 --- a/llvm/docs/FatLTO.rst +++ b/llvm/docs/FatLTO.rst @@ -38,7 +38,7 @@ This pipeline will: Previously, we conservatively ran independent pipelines on separate copies of the LLVM module to generate the bitcode section and the object code, - which happen to be identical to those used outside of FatLTO. While that + which happened to be identical to those used outside of FatLTO. While that resulted in compiled artifacts that were identical to those produced by the default and (Thin)LTO pipelines, module cloning led to some cases of miscompilation, and we have moved away from trying to keep bitcode diff --git a/llvm/docs/FaultMaps.rst b/llvm/docs/FaultMaps.rst index a089a38fcb30c..5dc5e574fd2fa 100644 --- a/llvm/docs/FaultMaps.rst +++ b/llvm/docs/FaultMaps.rst @@ -9,7 +9,7 @@ FaultMaps and implicit checks Motivation ========== -Code generated by managed language runtimes tend to have checks that +Code generated by managed language runtimes tends to have checks that are required for safety but never fail in practice. In such cases, it is profitable to make the non-failing case cheaper even if it makes the failing case significantly more expensive. This asymmetry can be @@ -28,7 +28,7 @@ the same memory location. The Fault Map Section ===================== -Information about implicit checks generated by LLVM are put in a +Information about implicit checks generated by LLVM is put in a special "fault map" section. On Darwin this section is named ``__llvm_faultmaps``. diff --git a/llvm/docs/GarbageCollection.rst b/llvm/docs/GarbageCollection.rst index 67be080db1310..d5fdfbbb03f90 100644 --- a/llvm/docs/GarbageCollection.rst +++ b/llvm/docs/GarbageCollection.rst @@ -487,7 +487,7 @@ The 'Erlang' and 'OCaml' GCs LLVM ships with two example collectors which leverage the ``gcroot`` mechanisms. To our knowledge, these are not actually used by any language runtime, but they do provide a reasonable starting point for someone interested -in writing an ``gcroot`` compatible GC plugin. In particular, these are the +in writing a ``gcroot`` compatible GC plugin. In particular, these are the only in-tree examples of how to produce a custom binary stack map format using a ``gcroot`` strategy. diff --git a/llvm/docs/GetElementPtr.rst b/llvm/docs/GetElementPtr.rst index 6831a8e6e81eb..09389a0af751f 100644 --- a/llvm/docs/GetElementPtr.rst +++ b/llvm/docs/GetElementPtr.rst @@ -496,10 +496,10 @@ primitive integer expressions, which allows them to be combined with other integer expressions and/or split into multiple separate integer expressions. If they've made non-trivial changes, translating back into LLVM IR can involve reverse-engineering the structure of the addressing in order to fit it into the -static type of the original first operand. It isn't always possibly to fully +static type of the original first operand. It isn't always possible to fully reconstruct this structure; sometimes the underlying addressing doesn't correspond with the static type at all. In such cases the optimizer instead will -emit a GEP with the base pointer casted to a simple address-unit pointer, using +emit a GEP with the base pointer cast to a simple address-unit pointer, using the name "uglygep". This isn't pretty, but it's just as valid, and it's sufficient to preserve the pointer aliasing guarantees that GEP provides. diff --git a/llvm/docs/GettingInvolved.rst b/llvm/docs/GettingInvolved.rst index 0dba9412564d4..ad544342de329 100644 --- a/llvm/docs/GettingInvolved.rst +++ b/llvm/docs/GettingInvolved.rst @@ -562,7 +562,7 @@ An example invite looks as follows .. code-block:: none This event is a meetup for all developers of LLDB. Meeting agendas are posted - on discourse before the event. + on Discourse before the event. Attendees must adhere to the LLVM Code of Conduct (https://llvm.org/docs/CodeOfConduct.html). For any Code of Conduct reports, diff --git a/llvm/docs/GettingStartedVS.rst b/llvm/docs/GettingStartedVS.rst index e65fd8fde829d..b82a4a05b5213 100644 --- a/llvm/docs/GettingStartedVS.rst +++ b/llvm/docs/GettingStartedVS.rst @@ -244,7 +244,7 @@ Build the LLVM Suite: * The Fibonacci project is a sample program that uses the JIT. Modify the project's debugging properties to provide a numeric command-line argument or run it from the command line. The program will print the - corresponding fibonacci value. + corresponding Fibonacci value. Links diff --git a/llvm/docs/GwpAsan.rst b/llvm/docs/GwpAsan.rst index 675a61de00983..937956fdabea7 100644 --- a/llvm/docs/GwpAsan.rst +++ b/llvm/docs/GwpAsan.rst @@ -31,7 +31,7 @@ Unlike `AddressSanitizer `_, GWP-ASan does not induce a significant performance overhead. ASan often requires the use of dedicated canaries to be viable in production environments, and as such is often impractical. Moreover, ASan's runtime is not developed with -security consideration in mind, making compiled binaries more vulnerable to +security considerations in mind, making compiled binaries more vulnerable to exploits. However, GWP-ASan is only capable of finding a subset of the memory issues diff --git a/llvm/docs/HowToBuildWindowsItaniumPrograms.rst b/llvm/docs/HowToBuildWindowsItaniumPrograms.rst index 48ca7b25b11ef..d932d9dd00bfd 100644 --- a/llvm/docs/HowToBuildWindowsItaniumPrograms.rst +++ b/llvm/docs/HowToBuildWindowsItaniumPrograms.rst @@ -8,7 +8,7 @@ Introduction This document contains information describing how to create a Windows Itanium toolchain. Windows Itanium allows you to deploy Itanium C++ ABI applications on top of the MS VS CRT. -This environment can use the Windows SDK headers directly and does not required additional +This environment can use the Windows SDK headers directly and does not require additional headers or additional runtime machinery (such as is used by mingw). Windows Itanium Stack: From 01bea27b73279b1d4d445397c3395f1078d2d4d0 Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 18:54:34 +0300 Subject: [PATCH 14/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (10/N) (#167127) --- .../clang-tidy/modernize/AvoidBindCheck.cpp | 20 ++++---- .../modernize/ConcatNestedNamespacesCheck.cpp | 18 +++---- .../modernize/DeprecatedHeadersCheck.cpp | 2 +- .../DeprecatedIosBaseAliasesCheck.cpp | 7 +-- .../IntegralLiteralExpressionMatcher.cpp | 2 +- .../clang-tidy/modernize/LoopConvertCheck.cpp | 47 ++++++++++--------- .../clang-tidy/modernize/LoopConvertUtils.cpp | 19 ++++---- .../clang-tidy/modernize/MacroToEnumCheck.cpp | 36 +++++++------- .../modernize/MakeSmartPtrCheck.cpp | 38 +++++++-------- .../clang-tidy/modernize/PassByValueCheck.cpp | 15 +++--- .../modernize/RawStringLiteralCheck.cpp | 10 ++-- .../modernize/RedundantVoidArgCheck.cpp | 24 +++++----- .../modernize/ReplaceAutoPtrCheck.cpp | 7 +-- ...ReplaceDisallowCopyAndAssignMacroCheck.cpp | 6 +-- .../modernize/ReplaceRandomShuffleCheck.cpp | 2 +- .../modernize/ReturnBracedInitListCheck.cpp | 4 +- .../clang-tidy/modernize/TypeTraitsCheck.cpp | 4 +- .../modernize/UnaryStaticAssertCheck.cpp | 2 +- .../clang-tidy/modernize/UseAutoCheck.cpp | 43 +++++++++-------- .../modernize/UseBoolLiteralsCheck.cpp | 4 +- .../modernize/UseConstraintsCheck.cpp | 32 ++++++------- 21 files changed, 177 insertions(+), 165 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp index 1c0043b423361..531311e732290 100644 --- a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp @@ -252,7 +252,7 @@ static SmallVector buildBindArguments(const MatchFinder::MatchResult &Result, const CallableInfo &Callable) { SmallVector BindArguments; - static llvm::Regex MatchPlaceholder("^_([0-9]+)$"); + static const llvm::Regex MatchPlaceholder("^_([0-9]+)$"); const auto *BindCall = Result.Nodes.getNodeAs("bind"); @@ -267,7 +267,7 @@ buildBindArguments(const MatchFinder::MatchResult &Result, if (Callable.Type == CT_MemberFunction) --ArgIndex; - bool IsObjectPtr = (I == 1 && Callable.Type == CT_MemberFunction); + const bool IsObjectPtr = (I == 1 && Callable.Type == CT_MemberFunction); B.E = E; B.SourceTokens = getSourceTextForExpr(Result, E); @@ -340,13 +340,13 @@ static void addPlaceholderArgs(const LambdaProperties &LP, MaxPlaceholderIt->PlaceHolderIndex == 0)) return; - size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex; + const size_t PlaceholderCount = MaxPlaceholderIt->PlaceHolderIndex; Stream << "("; StringRef Delimiter = ""; for (size_t I = 1; I <= PlaceholderCount; ++I) { Stream << Delimiter << "auto &&"; - int ArgIndex = findPositionOfPlaceholderUse(Args, I); + const int ArgIndex = findPositionOfPlaceholderUse(Args, I); if (ArgIndex != -1 && Args[ArgIndex].IsUsed) Stream << " " << Args[ArgIndex].UsageIdentifier; @@ -392,7 +392,7 @@ findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) { std::vector Candidates; for (const clang::CXXMethodDecl *Method : RecordDecl->methods()) { - OverloadedOperatorKind OOK = Method->getOverloadedOperator(); + const OverloadedOperatorKind OOK = Method->getOverloadedOperator(); if (OOK != OverloadedOperatorKind::OO_Call) continue; @@ -410,7 +410,7 @@ findCandidateCallOperators(const CXXRecordDecl *RecordDecl, size_t NumArgs) { continue; const FunctionDecl *FD = FTD->getTemplatedDecl(); - OverloadedOperatorKind OOK = FD->getOverloadedOperator(); + const OverloadedOperatorKind OOK = FD->getOverloadedOperator(); if (OOK != OverloadedOperatorKind::OO_Call) continue; @@ -471,7 +471,7 @@ getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type, if (Type == CT_Object) { const auto *BindCall = Result.Nodes.getNodeAs("bind"); - size_t NumArgs = BindCall->getNumArgs() - 1; + const size_t NumArgs = BindCall->getNumArgs() - 1; return getCallOperator(Callee->getType()->getAsCXXRecordDecl(), NumArgs); } @@ -488,7 +488,7 @@ getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type, static CallableType getCallableType(const MatchFinder::MatchResult &Result) { const auto *CallableExpr = Result.Nodes.getNodeAs("ref"); - QualType QT = CallableExpr->getType(); + const QualType QT = CallableExpr->getType(); if (QT->isMemberFunctionPointerType()) return CT_MemberFunction; @@ -614,7 +614,7 @@ static void emitCaptureList(const LambdaProperties &LP, if (B.CM == CM_None || !B.IsUsed) continue; - StringRef Delimiter = AnyCapturesEmitted ? ", " : ""; + const StringRef Delimiter = AnyCapturesEmitted ? ", " : ""; if (emitCapture(CaptureSet, Delimiter, B.CM, B.CE, B.CaptureIdentifier, B.SourceTokens, Stream)) @@ -669,7 +669,7 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult &Result) { emitCaptureList(LP, Result, Stream); Stream << "]"; - ArrayRef FunctionCallArgs = ArrayRef(LP.BindArguments); + const ArrayRef FunctionCallArgs = ArrayRef(LP.BindArguments); addPlaceholderArgs(LP, Stream, PermissiveParameterList); diff --git a/clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp index 6e28cb223370a..7c82e9ef029ba 100644 --- a/clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp @@ -25,7 +25,8 @@ static bool locationsInSameFile(const SourceManager &Sources, static StringRef getRawStringRef(const SourceRange &Range, const SourceManager &Sources, const LangOptions &LangOpts) { - CharSourceRange TextRange = Lexer::getAsCharRange(Range, Sources, LangOpts); + const CharSourceRange TextRange = + Lexer::getAsCharRange(Range, Sources, LangOpts); return Lexer::getSourceText(TextRange, Sources, LangOpts); } @@ -56,15 +57,16 @@ SourceRange NS::getDefaultNamespaceBackRange() const { SourceRange NS::getNamespaceBackRange(const SourceManager &SM, const LangOptions &LangOpts) const { // Back from '}' to conditional '// namespace xxx' - SourceLocation Loc = front()->getRBraceLoc(); + const SourceLocation Loc = front()->getRBraceLoc(); std::optional Tok = utils::lexer::findNextTokenIncludingComments(Loc, SM, LangOpts); if (!Tok) return getDefaultNamespaceBackRange(); if (Tok->getKind() != tok::TokenKind::comment) return getDefaultNamespaceBackRange(); - SourceRange TokRange = SourceRange{Tok->getLocation(), Tok->getEndLoc()}; - StringRef TokText = getRawStringRef(TokRange, SM, LangOpts); + const SourceRange TokRange = + SourceRange{Tok->getLocation(), Tok->getEndLoc()}; + const StringRef TokText = getRawStringRef(TokRange, SM, LangOpts); NamespaceName CloseComment{"namespace "}; appendCloseComment(CloseComment); // current fix hint in readability/NamespaceCommentCheck.cpp use single line @@ -98,7 +100,7 @@ bool ConcatNestedNamespacesCheck::unsupportedNamespace(const NamespaceDecl &ND, return true; if (getLangOpts().CPlusPlus20) { // C++20 support inline nested namespace - bool IsFirstNS = IsChild || !Namespaces.empty(); + const bool IsFirstNS = IsChild || !Namespaces.empty(); return ND.isInlineNamespace() && !IsFirstNS; } return ND.isInlineNamespace(); @@ -106,7 +108,7 @@ bool ConcatNestedNamespacesCheck::unsupportedNamespace(const NamespaceDecl &ND, bool ConcatNestedNamespacesCheck::singleNamedNamespaceChild( const NamespaceDecl &ND) const { - NamespaceDecl::decl_range Decls = ND.decls(); + const NamespaceDecl::decl_range Decls = ND.decls(); if (std::distance(Decls.begin(), Decls.end()) != 1) return false; @@ -121,7 +123,7 @@ void ConcatNestedNamespacesCheck::registerMatchers( void ConcatNestedNamespacesCheck::reportDiagnostic( const SourceManager &SM, const LangOptions &LangOpts) { - DiagnosticBuilder DB = + const DiagnosticBuilder DB = diag(Namespaces.front().front()->getBeginLoc(), "nested namespaces can be concatenated", DiagnosticIDs::Warning); @@ -143,7 +145,7 @@ void ConcatNestedNamespacesCheck::reportDiagnostic( // the last one should be handled specially Fronts.pop_back(); - SourceRange LastRBrace = Backs.pop_back_val(); + const SourceRange LastRBrace = Backs.pop_back_val(); NamespaceName ConcatNameSpace{"namespace "}; for (const NS &NS : Namespaces) { diff --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp index 1de9e136c5719..21eefab843af9 100644 --- a/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedHeadersCheck.cpp @@ -184,7 +184,7 @@ void IncludeModernizePPCallbacks::InclusionDirective( // 1. Insert std prefix for every such symbol occurrence. // 2. Insert `using namespace std;` to the beginning of TU. // 3. Do nothing and let the user deal with the migration himself. - SourceLocation DiagLoc = FilenameRange.getBegin(); + const SourceLocation DiagLoc = FilenameRange.getBegin(); if (auto It = CStyledHeaderToCxx.find(FileName); It != CStyledHeaderToCxx.end()) { IncludesToBeProcessed.emplace_back(IncludeMarker{ diff --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp index 5e254376c9796..7e43165fb09f1 100644 --- a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp @@ -36,10 +36,10 @@ void DeprecatedIosBaseAliasesCheck::registerMatchers(MatchFinder *Finder) { void DeprecatedIosBaseAliasesCheck::check( const MatchFinder::MatchResult &Result) { - SourceManager &SM = *Result.SourceManager; + const SourceManager &SM = *Result.SourceManager; const auto *Typedef = Result.Nodes.getNodeAs("TypeDecl"); - StringRef TypeName = Typedef->getName(); + const StringRef TypeName = Typedef->getName(); auto Replacement = getReplacementType(TypeName); TypeLoc TL = *Result.Nodes.getNodeAs("TypeLoc"); @@ -55,7 +55,8 @@ void DeprecatedIosBaseAliasesCheck::check( Fix = false; } - SourceLocation EndLoc = IoStateLoc.getLocWithOffset(TypeName.size() - 1); + const SourceLocation EndLoc = + IoStateLoc.getLocWithOffset(TypeName.size() - 1); if (Replacement) { const char *FixName = *Replacement; diff --git a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp index 05cf51a430f3f..862ca184ecd97 100644 --- a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp +++ b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp @@ -95,7 +95,7 @@ bool IntegralLiteralExpressionMatcher::unaryOperator() { } static LiteralSize literalTokenSize(const Token &Tok) { - unsigned int Length = Tok.getLength(); + const unsigned int Length = Tok.getLength(); if (Length <= 1) return LiteralSize::Int; diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp index fea5ac6f29eff..30e2d4fe0a372 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -115,7 +115,7 @@ arrayConditionMatcher(internal::Matcher LimitExpr) { /// - The index variable is only used as an array index. /// - All arrays indexed by the loop are the same. static StatementMatcher makeArrayLoopMatcher() { - StatementMatcher ArrayBoundMatcher = + const StatementMatcher ArrayBoundMatcher = expr(hasType(isInteger())).bind(ConditionBoundName); return forStmt(unless(isInTemplateInstantiation()), @@ -168,7 +168,7 @@ static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { auto EndNameMatcherStd = IsReverse ? hasAnyName("::std::rend", "::std::crend") : hasAnyName("::std::end", "::std::cend"); - StatementMatcher BeginCallMatcher = + const StatementMatcher BeginCallMatcher = expr(anyOf(cxxMemberCallExpr(argumentCountIs(0), callee(cxxMethodDecl(BeginNameMatcher))), callExpr(argumentCountIs(1), @@ -177,37 +177,37 @@ static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { callee(functionDecl(BeginNameMatcherStd))))) .bind(BeginCallName); - DeclarationMatcher InitDeclMatcher = + const DeclarationMatcher InitDeclMatcher = varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher), materializeTemporaryExpr( ignoringParenImpCasts(BeginCallMatcher)), hasDescendant(BeginCallMatcher)))) .bind(InitVarName); - DeclarationMatcher EndDeclMatcher = + const DeclarationMatcher EndDeclMatcher = varDecl(hasInitializer(anything())).bind(EndVarName); - StatementMatcher EndCallMatcher = expr(anyOf( + const StatementMatcher EndCallMatcher = expr(anyOf( cxxMemberCallExpr(argumentCountIs(0), callee(cxxMethodDecl(EndNameMatcher))), callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)), usesADL()), callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd))))); - StatementMatcher IteratorBoundMatcher = + const StatementMatcher IteratorBoundMatcher = expr(anyOf(ignoringParenImpCasts( declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))), ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)), materializeTemporaryExpr(ignoringParenImpCasts( expr(EndCallMatcher).bind(EndCallName))))); - StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts( + const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts( declRefExpr(to(varDecl(equalsBoundNode(InitVarName)))))); // This matcher tests that a declaration is a CXXRecordDecl that has an // overloaded operator*(). If the operator*() returns by value instead of by // reference then the return type is tagged with DerefByValueResultName. - internal::Matcher TestDerefReturnsByValue = + const internal::Matcher TestDerefReturnsByValue = hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl( hasOverloadedOperatorName("*"), @@ -280,7 +280,7 @@ static StatementMatcher makePseudoArrayLoopMatcher() { // FIXME: Also, a record doesn't necessarily need begin() and end(). Free // functions called begin() and end() taking the container as an argument // are also allowed. - TypeMatcher RecordWithBeginEnd = qualType(anyOf( + const TypeMatcher RecordWithBeginEnd = qualType(anyOf( qualType(isConstQualified(), hasUnqualifiedDesugaredType(recordType(hasDeclaration( cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl( @@ -295,7 +295,7 @@ static StatementMatcher makePseudoArrayLoopMatcher() { hasMethod(hasName("end"))))))))) // qualType )); - StatementMatcher SizeCallMatcher = expr(anyOf( + const StatementMatcher SizeCallMatcher = expr(anyOf( cxxMemberCallExpr(argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("size", "length"))), on(anyOf(hasType(pointsTo(RecordWithBeginEnd)), @@ -310,10 +310,10 @@ static StatementMatcher makePseudoArrayLoopMatcher() { explicitCastExpr(hasSourceExpression(ignoringParenImpCasts( expr(SizeCallMatcher).bind(EndCallName)))))); - DeclarationMatcher EndDeclMatcher = + const DeclarationMatcher EndDeclMatcher = varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName); - StatementMatcher IndexBoundMatcher = + const StatementMatcher IndexBoundMatcher = expr(anyOf(ignoringParenImpCasts( declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))), EndInitMatcher)); @@ -620,7 +620,7 @@ void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) { SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid); if (Invalid) return; - unsigned Offset = std::strspn(TextAfter, " \t\r\n"); + const unsigned Offset = std::strspn(TextAfter, " \t\r\n"); Range = SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset)); } @@ -633,7 +633,7 @@ void LoopConvertCheck::doConversion( const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit, const ForStmt *Loop, RangeDescriptor Descriptor) { std::string VarNameOrStructuredBinding; - bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; + const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; bool AliasVarIsRef = false; bool CanCopy = true; std::vector FixIts; @@ -743,7 +743,7 @@ void LoopConvertCheck::doConversion( } // Now, we need to construct the new range expression. - SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); + const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); QualType Type = Context->getAutoDeductType(); if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType()) @@ -753,14 +753,15 @@ void LoopConvertCheck::doConversion( // If the new variable name is from the aliased variable, then the reference // type for the new variable should only be used if the aliased variable was // declared as a reference. - bool IsCheapToCopy = + const bool IsCheapToCopy = !Descriptor.ElemType.isNull() && Descriptor.ElemType.isTriviallyCopyableType(*Context) && !Descriptor.ElemType->isDependentSizedArrayType() && // TypeInfo::Width is in bits. Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize; - bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || - (Descriptor.DerefByConstRef && IsCheapToCopy)); + const bool UseCopy = + CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || + (Descriptor.DerefByConstRef && IsCheapToCopy)); if (!UseCopy) { if (Descriptor.DerefByConstRef) { @@ -866,7 +867,7 @@ void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context, // The matchers for iterator loops provide bound nodes to obtain this // information. const auto *InitVar = Nodes.getNodeAs(InitVarName); - QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); + const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); const auto *DerefByValueType = Nodes.getNodeAs(DerefByValueResultName); Descriptor.DerefByValue = DerefByValueType; @@ -934,12 +935,12 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context, // FIXME: Try to put most of this logic inside a matcher. if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) { - QualType InitVarType = InitVar->getType(); - QualType CanonicalInitVarType = InitVarType.getCanonicalType(); + const QualType InitVarType = InitVar->getType(); + const QualType CanonicalInitVarType = InitVarType.getCanonicalType(); const auto *BeginCall = Nodes.getNodeAs(BeginCallName); assert(BeginCall && "Bad Callback. No begin call expression"); - QualType CanonicalBeginType = + const QualType CanonicalBeginType = BeginCall->getDirectCallee()->getReturnType().getCanonicalType(); if (CanonicalBeginType->isPointerType() && CanonicalInitVarType->isPointerType()) { @@ -1054,7 +1055,7 @@ void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) { } // Find out which qualifiers we have to use in the loop range. - TraversalKindScope RAII(*Context, TK_AsIs); + const TraversalKindScope RAII(*Context, TK_AsIs); const UsageResult &Usages = Finder.getUsages(); determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, Usages, Descriptor); diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp index 6fb780844f2b6..170a4f6d8731f 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp @@ -101,7 +101,8 @@ bool DependencyFinderASTVisitor::VisitVarDecl(VarDecl *V) { /// If we already created a variable for TheLoop, check to make sure /// that the name was not already taken. bool DeclFinderASTVisitor::VisitForStmt(ForStmt *TheLoop) { - StmtGeneratedVarNameMap::const_iterator I = GeneratedDecls->find(TheLoop); + const StmtGeneratedVarNameMap::const_iterator I = + GeneratedDecls->find(TheLoop); if (I != GeneratedDecls->end() && I->second == Name) { Found = true; return false; @@ -131,7 +132,7 @@ bool DeclFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *DeclRef) { /// If the new variable name conflicts with any type used in the loop, /// then we mark that variable name as taken. bool DeclFinderASTVisitor::VisitTypeLoc(TypeLoc TL) { - QualType QType = TL.getType(); + const QualType QType = TL.getType(); // Check if our name conflicts with a type, to handle for typedefs. if (QType.getAsString() == Name) { @@ -364,7 +365,7 @@ static bool isAliasDecl(ASTContext *Context, const Decl *TheDecl, // Check that the declared type is the same as (or a reference to) the // container type. if (!OnlyCasts) { - QualType InitType = Init->getType(); + const QualType InitType = Init->getType(); QualType DeclarationType = VDecl->getType(); if (!DeclarationType.isNull() && DeclarationType->isReferenceType()) DeclarationType = DeclarationType.getNonReferenceType(); @@ -440,7 +441,7 @@ static bool arrayMatchesBoundExpr(ASTContext *Context, ConditionExpr->getIntegerConstantExpr(*Context); if (!ConditionSize) return false; - llvm::APSInt ArraySize(ConstType->getSize()); + const llvm::APSInt ArraySize(ConstType->getSize()); return llvm::APSInt::isSameValue(*ConditionSize, ArraySize); } @@ -571,7 +572,7 @@ bool ForLoopIndexUseVisitor::TraverseMemberExpr(MemberExpr *Member) { // FIXME: This works around not having the location of the arrow operator. // Consider adding OperatorLoc to MemberExpr? - SourceLocation ArrowLoc = Lexer::getLocForEndOfToken( + const SourceLocation ArrowLoc = Lexer::getLocForEndOfToken( Base->getExprLoc(), 0, Context->getSourceManager(), Context->getLangOpts()); // If something complicated is happening (i.e. the next token isn't an @@ -821,7 +822,7 @@ bool ForLoopIndexUseVisitor::traverseStmtImpl(Stmt *S) { const Stmt *OldNextParent = NextStmtParent; CurrStmtParent = NextStmtParent; NextStmtParent = S; - bool Result = VisitorBase::TraverseStmt(S); + const bool Result = VisitorBase::TraverseStmt(S); NextStmtParent = OldNextParent; return Result; } @@ -850,7 +851,7 @@ std::string VariableNamer::createIndexName() { if (TheContainer) ContainerName = TheContainer->getName(); - size_t Len = ContainerName.size(); + const size_t Len = ContainerName.size(); if (Len > 1 && ContainerName.ends_with(Style == NS_UpperCase ? "S" : "s")) { IteratorName = std::string(ContainerName.substr(0, Len - 1)); // E.g.: (auto thing : things) @@ -876,7 +877,7 @@ std::string VariableNamer::createIndexName() { /// converter in a loop nested within SourceStmt. bool VariableNamer::declarationExists(StringRef Symbol) { assert(Context != nullptr && "Expected an ASTContext"); - IdentifierInfo &Ident = Context->Idents.get(Symbol); + const IdentifierInfo &Ident = Context->Idents.get(Symbol); // Check if the symbol is not an identifier (ie. is a keyword or alias). if (!isAnyIdentifier(Ident.getTokenID())) @@ -888,7 +889,7 @@ bool VariableNamer::declarationExists(StringRef Symbol) { // Determine if the symbol was generated in a parent context. for (const Stmt *S = SourceStmt; S != nullptr; S = ReverseAST->lookup(S)) { - StmtGeneratedVarNameMap::const_iterator I = GeneratedDecls->find(S); + const StmtGeneratedVarNameMap::const_iterator I = GeneratedDecls->find(S); if (I != GeneratedDecls->end() && I->second == Symbol) return true; } diff --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp index 2669aa2361ea1..098d46cae5df4 100644 --- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp @@ -23,7 +23,7 @@ static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options, StringRef Text) { // Use a lexer to look for tokens; if we find something other than a single // hash, then there were intervening tokens between macro definitions. - std::string Buffer{Text}; + const std::string Buffer{Text}; Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(), Buffer.c_str() + Buffer.size()); Token Tok; @@ -47,7 +47,7 @@ static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options, }; WhiteSpace State = WhiteSpace::Nothing; - for (char C : Text) { + for (const char C : Text) { switch (C) { case '\r': if (State == WhiteSpace::CR) @@ -227,17 +227,17 @@ bool MacroToEnumCallbacks::isConsecutiveMacro(const MacroDirective *MD) const { if (CurrentFile->LastMacroLocation.isInvalid()) return false; - SourceLocation Loc = MD->getLocation(); + const SourceLocation Loc = MD->getLocation(); if (CurrentFile->LastLine + 1 == SM.getSpellingLineNumber(Loc)) return true; - SourceLocation Define = + const SourceLocation Define = SM.translateLineCol(SM.getFileID(Loc), SM.getSpellingLineNumber(Loc), 1); - CharSourceRange BetweenMacros{ + const CharSourceRange BetweenMacros{ SourceRange{CurrentFile->LastMacroLocation, Define}, true}; - CharSourceRange CharRange = + const CharSourceRange CharRange = Lexer::makeFileCharRange(BetweenMacros, SM, LangOpts); - StringRef BetweenText = Lexer::getSourceText(CharRange, SM, LangOpts); + const StringRef BetweenText = Lexer::getSourceText(CharRange, SM, LangOpts); return hasOnlyComments(Define, LangOpts, BetweenText); } @@ -258,7 +258,7 @@ void MacroToEnumCallbacks::conditionStart(const SourceLocation &Loc) { } void MacroToEnumCallbacks::checkCondition(SourceRange Range) { - CharSourceRange CharRange = Lexer::makeFileCharRange( + const CharSourceRange CharRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(Range), SM, LangOpts); std::string Text = Lexer::getSourceText(CharRange, SM, LangOpts).str(); Lexer Lex(CharRange.getBegin(), LangOpts, Text.data(), Text.data(), @@ -285,7 +285,7 @@ void MacroToEnumCallbacks::checkName(const Token &MacroNameTok) { } void MacroToEnumCallbacks::rememberExpressionName(const Token &Tok) { - std::string Id = getTokenName(Tok).str(); + const std::string Id = getTokenName(Tok).str(); auto Pos = llvm::lower_bound(ExpressionNames, Id); if (Pos == ExpressionNames.end() || *Pos != Id) { ExpressionNames.insert(Pos, Id); @@ -294,7 +294,7 @@ void MacroToEnumCallbacks::rememberExpressionName(const Token &Tok) { void MacroToEnumCallbacks::rememberExpressionTokens( ArrayRef MacroTokens) { - for (Token Tok : MacroTokens) { + for (const Token Tok : MacroTokens) { if (Tok.isAnyIdentifier()) rememberExpressionName(Tok); } @@ -318,8 +318,8 @@ void MacroToEnumCallbacks::FileChanged(SourceLocation Loc, bool MacroToEnumCallbacks::isInitializer(ArrayRef MacroTokens) { IntegralLiteralExpressionMatcher Matcher(MacroTokens, LangOpts.C99 == 0); - bool Matched = Matcher.match(); - bool IsC = !LangOpts.CPlusPlus; + const bool Matched = Matcher.match(); + const bool IsC = !LangOpts.CPlusPlus; if (IsC && (Matcher.largestLiteralSize() != LiteralSize::Int && Matcher.largestLiteralSize() != LiteralSize::UnsignedInt)) return false; @@ -344,7 +344,7 @@ void MacroToEnumCallbacks::MacroDefined(const Token &MacroNameTok, return; const MacroInfo *Info = MD->getMacroInfo(); - ArrayRef MacroTokens = Info->tokens(); + const ArrayRef MacroTokens = Info->tokens(); if (Info->isBuiltinMacro() || MacroTokens.empty()) return; if (Info->isFunctionLike()) { @@ -474,26 +474,26 @@ void MacroToEnumCallbacks::fixEnumMacro(const MacroList &MacroList) const { MacroList.front().Directive->getMacroInfo()->getDefinitionLoc(); Begin = SM.translateLineCol(SM.getFileID(Begin), SM.getSpellingLineNumber(Begin), 1); - DiagnosticBuilder Diagnostic = + const DiagnosticBuilder Diagnostic = Check->diag(Begin, "replace macro with enum") << FixItHint::CreateInsertion(Begin, "enum {\n"); for (size_t I = 0U; I < MacroList.size(); ++I) { const EnumMacro &Macro = MacroList[I]; - SourceLocation DefineEnd = + const SourceLocation DefineEnd = Macro.Directive->getMacroInfo()->getDefinitionLoc(); - SourceLocation DefineBegin = SM.translateLineCol( + const SourceLocation DefineBegin = SM.translateLineCol( SM.getFileID(DefineEnd), SM.getSpellingLineNumber(DefineEnd), 1); CharSourceRange DefineRange; DefineRange.setBegin(DefineBegin); DefineRange.setEnd(DefineEnd); Diagnostic << FixItHint::CreateRemoval(DefineRange); - SourceLocation NameEnd = Lexer::getLocForEndOfToken( + const SourceLocation NameEnd = Lexer::getLocForEndOfToken( Macro.Directive->getMacroInfo()->getDefinitionLoc(), 0, SM, LangOpts); Diagnostic << FixItHint::CreateInsertion(NameEnd, " ="); - SourceLocation ValueEnd = Lexer::getLocForEndOfToken( + const SourceLocation ValueEnd = Lexer::getLocForEndOfToken( Macro.Directive->getMacroInfo()->getDefinitionEndLoc(), 0, SM, LangOpts); if (I < MacroList.size() - 1) diff --git a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp index 9d01e27fbab9c..7940939eb21a5 100644 --- a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp @@ -24,7 +24,7 @@ static constexpr char NewExpression[] = "newExpression"; static std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM, const LangOptions &Lang) { - StringRef WrittenName = Lexer::getSourceText( + const StringRef WrittenName = Lexer::getSourceText( CharSourceRange::getTokenRange( NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()), SM, Lang); @@ -134,9 +134,9 @@ void MakeSmartPtrCheck::check(const MatchFinder::MatchResult &Result) { // // The fix of the check has side effect, it introduces value initialization // which maybe unexpected and cause performance regression. - bool Initializes = New->hasInitializer() || - !utils::type_traits::isTriviallyDefaultConstructible( - New->getAllocatedType(), *Result.Context); + const bool Initializes = New->hasInitializer() || + !utils::type_traits::isTriviallyDefaultConstructible( + New->getAllocatedType(), *Result.Context); if (!Initializes && IgnoreDefaultInitialization) return; if (Construct) @@ -150,15 +150,15 @@ void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx, const VarDecl *DVar, const QualType *Type, const CXXNewExpr *New) { - SourceLocation ConstructCallStart = Construct->getExprLoc(); - bool InMacro = ConstructCallStart.isMacroID(); + const SourceLocation ConstructCallStart = Construct->getExprLoc(); + const bool InMacro = ConstructCallStart.isMacroID(); if (InMacro && IgnoreMacros) { return; } bool Invalid = false; - StringRef ExprStr = Lexer::getSourceText( + const StringRef ExprStr = Lexer::getSourceText( CharSourceRange::getCharRange( ConstructCallStart, Construct->getParenOrBraceRange().getBegin()), SM, getLangOpts(), &Invalid); @@ -178,7 +178,7 @@ void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx, } // Find the location of the template's left angle. - size_t LAngle = ExprStr.find('<'); + const size_t LAngle = ExprStr.find('<'); SourceLocation ConstructCallEnd; if (LAngle == StringRef::npos) { // If the template argument is missing (because it is part of the alias) @@ -202,7 +202,7 @@ void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx, // If the smart_ptr is built with brace enclosed direct initialization, use // parenthesis instead. if (Construct->isListInitialization()) { - SourceRange BraceRange = Construct->getParenOrBraceRange(); + const SourceRange BraceRange = Construct->getParenOrBraceRange(); Diag << FixItHint::CreateReplacement( CharSourceRange::getCharRange( BraceRange.getBegin(), BraceRange.getBegin().getLocWithOffset(1)), @@ -220,13 +220,13 @@ void MakeSmartPtrCheck::checkReset(SourceManager &SM, ASTContext *Ctx, const CXXMemberCallExpr *Reset, const CXXNewExpr *New) { const auto *Expr = cast(Reset->getCallee()); - SourceLocation OperatorLoc = Expr->getOperatorLoc(); - SourceLocation ResetCallStart = Reset->getExprLoc(); - SourceLocation ExprStart = Expr->getBeginLoc(); - SourceLocation ExprEnd = + const SourceLocation OperatorLoc = Expr->getOperatorLoc(); + const SourceLocation ResetCallStart = Reset->getExprLoc(); + const SourceLocation ExprStart = Expr->getBeginLoc(); + const SourceLocation ExprEnd = Lexer::getLocForEndOfToken(Expr->getEndLoc(), 0, SM, getLangOpts()); - bool InMacro = ExprStart.isMacroID(); + const bool InMacro = ExprStart.isMacroID(); if (InMacro && IgnoreMacros) { return; @@ -267,7 +267,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag, const CXXNewExpr *New, SourceManager &SM, ASTContext *Ctx) { auto SkipParensParents = [&](const Expr *E) { - TraversalKindScope RAII(*Ctx, TK_AsIs); + const TraversalKindScope RAII(*Ctx, TK_AsIs); for (const Expr *OldE = nullptr; E != OldE;) { OldE = E; @@ -281,9 +281,9 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag, return E; }; - SourceRange NewRange = SkipParensParents(New)->getSourceRange(); - SourceLocation NewStart = NewRange.getBegin(); - SourceLocation NewEnd = NewRange.getEnd(); + const SourceRange NewRange = SkipParensParents(New)->getSourceRange(); + const SourceLocation NewStart = NewRange.getBegin(); + const SourceLocation NewEnd = NewRange.getEnd(); // Skip when the source location of the new expression is invalid. if (NewStart.isInvalid() || NewEnd.isInvalid()) @@ -362,7 +362,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag, return false; } if (ArraySizeExpr.empty()) { - SourceRange InitRange = New->getDirectInitRange(); + const SourceRange InitRange = New->getDirectInitRange(); Diag << FixItHint::CreateRemoval( SourceRange(NewStart, InitRange.getBegin())); Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd)); diff --git a/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp b/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp index d5ccbb73735ec..a257f5325f780 100644 --- a/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp @@ -24,7 +24,8 @@ static bool isFirstFriendOfSecond(const CXXRecordDecl *Friend, const CXXRecordDecl *Class) { return llvm::any_of( Class->friends(), [Friend](FriendDecl *FriendDecl) -> bool { - if (TypeSourceInfo *FriendTypeSource = FriendDecl->getFriendType()) { + if (const TypeSourceInfo *FriendTypeSource = + FriendDecl->getFriendType()) { const QualType FriendType = FriendTypeSource->getType(); return FriendType->getAsCXXRecordDecl() == Friend; } @@ -208,7 +209,7 @@ static SmallVector collectParamDecls(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl) { SmallVector Results; - unsigned ParamIdx = ParamDecl->getFunctionScopeIndex(); + const unsigned ParamIdx = ParamDecl->getFunctionScopeIndex(); for (const FunctionDecl *Redecl : Ctor->redecls()) Results.push_back(Redecl->getParamDecl(ParamIdx)); @@ -275,7 +276,7 @@ void PassByValueCheck::check(const MatchFinder::MatchResult &Result) { const auto *ParamDecl = Result.Nodes.getNodeAs("Param"); const auto *Initializer = Result.Nodes.getNodeAs("Initializer"); - SourceManager &SM = *Result.SourceManager; + const SourceManager &SM = *Result.SourceManager; // If the parameter is used or anything other than the copy, do not apply // the changes. @@ -299,7 +300,7 @@ void PassByValueCheck::check(const MatchFinder::MatchResult &Result) { if (ParamDecl->getType()->isLValueReferenceType()) { // Check if we can succesfully rewrite all declarations of the constructor. for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) { - TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc(); + const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc(); auto RefTL = ParamTL.getAs(); if (RefTL.isNull()) { // We cannot rewrite this instance. The type is probably hidden behind @@ -309,11 +310,11 @@ void PassByValueCheck::check(const MatchFinder::MatchResult &Result) { } // Rewrite all declarations. for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) { - TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc(); + const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc(); auto RefTL = ParamTL.getAs(); - TypeLoc ValueTL = RefTL.getPointeeLoc(); - CharSourceRange TypeRange = CharSourceRange::getTokenRange( + const TypeLoc ValueTL = RefTL.getPointeeLoc(); + const CharSourceRange TypeRange = CharSourceRange::getTokenRange( ParmDecl->getBeginLoc(), ParamTL.getEndLoc()); std::string ValueStr = Lexer::getSourceText( diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp index 8e514e4bc9893..2c4bddf262721 100644 --- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp @@ -51,11 +51,11 @@ static bool containsEscapedCharacters(const MatchFinder::MatchResult &Result, if (DisallowedChars.test(C)) return false; - CharSourceRange CharRange = Lexer::makeFileCharRange( + const CharSourceRange CharRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(Literal->getSourceRange()), *Result.SourceManager, Result.Context->getLangOpts()); - StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager, - Result.Context->getLangOpts()); + const StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager, + Result.Context->getLangOpts()); if (Text.empty() || isRawStringLiteral(Text)) return false; @@ -116,7 +116,7 @@ createUserDefinedSuffix(const StringLiteral *Literal, const SourceManager &SM, const CharSourceRange CharRange = Lexer::makeFileCharRange(TokenRange, SM, LangOpts); if (T.hasUDSuffix()) { - StringRef Text = Lexer::getSourceText(CharRange, SM, LangOpts); + const StringRef Text = Lexer::getSourceText(CharRange, SM, LangOpts); const size_t UDSuffixPos = Text.find_last_of('"'); if (UDSuffixPos == StringRef::npos) return std::nullopt; @@ -135,7 +135,7 @@ static std::string createRawStringLiteral(const StringLiteral *Literal, Delimiter = (I == 0) ? DelimiterStem : DelimiterStem + std::to_string(I); } - std::optional UserDefinedSuffix = + const std::optional UserDefinedSuffix = createUserDefinedSuffix(Literal, SM, LangOpts); if (Delimiter.empty()) diff --git a/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp b/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp index 38b30f7994ff3..aa2db2146475b 100644 --- a/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp @@ -89,9 +89,9 @@ void RedundantVoidArgCheck::check(const MatchFinder::MatchResult &Result) { void RedundantVoidArgCheck::processFunctionDecl( const MatchFinder::MatchResult &Result, const FunctionDecl *Function) { const auto *Method = dyn_cast(Function); - SourceLocation Start = Method && Method->getParent()->isLambda() - ? Method->getBeginLoc() - : Function->getLocation(); + const SourceLocation Start = Method && Method->getParent()->isLambda() + ? Method->getBeginLoc() + : Function->getLocation(); SourceLocation End = Function->getEndLoc(); if (Function->isThisDeclarationADefinition()) { if (const Stmt *Body = Function->getBody()) { @@ -113,7 +113,8 @@ static bool isMacroIdentifier(const IdentifierTable &Idents, if (!ProtoToken.is(tok::TokenKind::raw_identifier)) return false; - IdentifierTable::iterator It = Idents.find(ProtoToken.getRawIdentifier()); + const IdentifierTable::iterator It = + Idents.find(ProtoToken.getRawIdentifier()); if (It == Idents.end()) return false; @@ -123,7 +124,7 @@ static bool isMacroIdentifier(const IdentifierTable &Idents, void RedundantVoidArgCheck::removeVoidArgumentTokens( const ast_matchers::MatchFinder::MatchResult &Result, SourceRange Range, StringRef GrammarLocation) { - CharSourceRange CharRange = + const CharSourceRange CharRange = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(Range), *Result.SourceManager, getLangOpts()); @@ -145,7 +146,7 @@ void RedundantVoidArgCheck::removeVoidArgumentTokens( Token ProtoToken; const IdentifierTable &Idents = Result.Context->Idents; int MacroLevel = 0; - std::string Diagnostic = + const std::string Diagnostic = ("redundant void argument list in " + GrammarLocation).str(); while (!PrototypeLexer.LexFromRawLexer(ProtoToken)) { @@ -216,7 +217,7 @@ void RedundantVoidArgCheck::removeVoidArgumentTokens( void RedundantVoidArgCheck::removeVoidToken(Token VoidToken, StringRef Diagnostic) { - SourceLocation VoidLoc = VoidToken.getLocation(); + const SourceLocation VoidLoc = VoidToken.getLocation(); diag(VoidLoc, Diagnostic) << FixItHint::CreateRemoval(VoidLoc); } @@ -239,9 +240,9 @@ void RedundantVoidArgCheck::processFieldDecl( void RedundantVoidArgCheck::processVarDecl( const MatchFinder::MatchResult &Result, const VarDecl *Var) { if (protoTypeHasNoParms(Var->getType())) { - SourceLocation Begin = Var->getBeginLoc(); + const SourceLocation Begin = Var->getBeginLoc(); if (Var->hasInit()) { - SourceLocation InitStart = + const SourceLocation InitStart = Result.SourceManager->getExpansionLoc(Var->getInit()->getBeginLoc()) .getLocWithOffset(-1); removeVoidArgumentTokens(Result, SourceRange(Begin, InitStart), @@ -273,8 +274,9 @@ void RedundantVoidArgCheck::processLambdaExpr( const MatchFinder::MatchResult &Result, const LambdaExpr *Lambda) { if (Lambda->getLambdaClass()->getLambdaCallOperator()->getNumParams() == 0 && Lambda->hasExplicitParameters()) { - SourceManager *SM = Result.SourceManager; - TypeLoc TL = Lambda->getLambdaClass()->getLambdaTypeInfo()->getTypeLoc(); + const SourceManager *SM = Result.SourceManager; + const TypeLoc TL = + Lambda->getLambdaClass()->getLambdaTypeInfo()->getTypeLoc(); removeVoidArgumentTokens(Result, {SM->getSpellingLoc(TL.getBeginLoc()), SM->getSpellingLoc(TL.getEndLoc())}, diff --git a/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp index b562ae85aa266..d0577aeccd2f1 100644 --- a/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp @@ -96,10 +96,10 @@ void ReplaceAutoPtrCheck::registerPPCallbacks(const SourceManager &SM, } void ReplaceAutoPtrCheck::check(const MatchFinder::MatchResult &Result) { - SourceManager &SM = *Result.SourceManager; + const SourceManager &SM = *Result.SourceManager; if (const auto *E = Result.Nodes.getNodeAs(AutoPtrOwnershipTransferId)) { - CharSourceRange Range = Lexer::makeFileCharRange( + const CharSourceRange Range = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(E->getSourceRange()), SM, LangOptions()); if (Range.isInvalid()) @@ -140,7 +140,8 @@ void ReplaceAutoPtrCheck::check(const MatchFinder::MatchResult &Result) { "auto_ptr") return; - SourceLocation EndLoc = AutoPtrLoc.getLocWithOffset(strlen("auto_ptr") - 1); + const SourceLocation EndLoc = + AutoPtrLoc.getLocWithOffset(strlen("auto_ptr") - 1); diag(AutoPtrLoc, "auto_ptr is deprecated, use unique_ptr instead") << FixItHint::CreateReplacement(SourceRange(AutoPtrLoc, EndLoc), "unique_ptr"); diff --git a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp index 64b0029fc0e37..be5e21dce3ba1 100644 --- a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp @@ -26,7 +26,7 @@ class ReplaceDisallowCopyAndAssignMacroCallbacks : public PPCallbacks { void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override { - IdentifierInfo *Info = MacroNameTok.getIdentifierInfo(); + const IdentifierInfo *Info = MacroNameTok.getIdentifierInfo(); if (!Info || !Args || Args->getNumMacroArguments() != 1) return; if (Info->getName() != Check.getMacroName()) @@ -38,11 +38,11 @@ class ReplaceDisallowCopyAndAssignMacroCallbacks : public PPCallbacks { // For now we only support simple argument that don't need to be // pre-expanded. return; - clang::IdentifierInfo *ClassIdent = ClassNameTok->getIdentifierInfo(); + const clang::IdentifierInfo *ClassIdent = ClassNameTok->getIdentifierInfo(); if (!ClassIdent) return; - std::string Replacement = llvm::formatv( + const std::string Replacement = llvm::formatv( R"cpp({0}(const {0} &) = delete; const {0} &operator=(const {0} &) = delete{1})cpp", ClassIdent->getName(), shouldAppendSemi(Range) ? ";" : ""); diff --git a/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp index 3d7b3eae544b6..cfc546a06b40c 100644 --- a/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp @@ -78,7 +78,7 @@ void ReplaceRandomShuffleCheck::check(const MatchFinder::MatchResult &Result) { }(); std::string NewName = "shuffle"; - StringRef ContainerText = Lexer::getSourceText( + const StringRef ContainerText = Lexer::getSourceText( CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()), *Result.SourceManager, getLangOpts()); if (ContainerText.starts_with("std::")) diff --git a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp index eba2445c0aaea..15b64bc413be8 100644 --- a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp @@ -54,7 +54,7 @@ void ReturnBracedInitListCheck::check(const MatchFinder::MatchResult &Result) { Result.Nodes.getNodeAs("ctor"); // Don't make replacements in macro. - SourceLocation Loc = MatchedConstructExpr->getExprLoc(); + const SourceLocation Loc = MatchedConstructExpr->getExprLoc(); if (Loc.isMacroID()) return; @@ -88,7 +88,7 @@ void ReturnBracedInitListCheck::check(const MatchFinder::MatchResult &Result) { } // Range for constructor name and opening brace. - CharSourceRange CtorCallSourceRange = CharSourceRange::getTokenRange( + const CharSourceRange CtorCallSourceRange = CharSourceRange::getTokenRange( Loc, CallParensRange.getBegin().getLocWithOffset(-1)); Diag << FixItHint::CreateRemoval(CtorCallSourceRange) diff --git a/clang-tools-extra/clang-tidy/modernize/TypeTraitsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/TypeTraitsCheck.cpp index 6078013166d46..06982b8698e0c 100644 --- a/clang-tools-extra/clang-tidy/modernize/TypeTraitsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/TypeTraitsCheck.cpp @@ -286,7 +286,7 @@ void TypeTraitsCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *TL = Result.Nodes.getNodeAs(Bind)) { const NestedNameSpecifierLoc QualLoc = TL->getQualifierLoc(); - NestedNameSpecifier NNS = QualLoc.getNestedNameSpecifier(); + const NestedNameSpecifier NNS = QualLoc.getNestedNameSpecifier(); if (const auto *CTSD = dyn_cast_if_present( NNS.getAsRecordDecl())) { if (isNamedDeclInStdTraitsSet(CTSD, TypeTraits)) @@ -304,7 +304,7 @@ void TypeTraitsCheck::check(const MatchFinder::MatchResult &Result) { } if (const auto *DNTL = Result.Nodes.getNodeAs(Bind)) { - NestedNameSpecifierLoc QualLoc = DNTL->getQualifierLoc(); + const NestedNameSpecifierLoc QualLoc = DNTL->getQualifierLoc(); if (checkTemplatedDecl(QualLoc.getNestedNameSpecifier(), TypeTraits)) EmitTypeWarning(QualLoc, DNTL->getEndLoc(), DNTL->getElaboratedKeywordLoc()); diff --git a/clang-tools-extra/clang-tidy/modernize/UnaryStaticAssertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UnaryStaticAssertCheck.cpp index 4e4817f2ec2e6..28d8f7572d32b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UnaryStaticAssertCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UnaryStaticAssertCheck.cpp @@ -23,7 +23,7 @@ void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) { const auto *AssertMessage = dyn_cast_if_present(MatchedDecl->getMessage()); - SourceLocation Loc = MatchedDecl->getLocation(); + const SourceLocation Loc = MatchedDecl->getLocation(); if (!AssertMessage || AssertMessage->getLength() || AssertMessage->getBeginLoc().isMacroID() || Loc.isMacroID()) diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp index 084349be7b609..977ade12e2c3a 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp @@ -101,7 +101,8 @@ AST_MATCHER_P(QualType, isSugarFor, Matcher, SugarMatcher) { if (SugarMatcher.matches(QT, Finder, Builder)) return true; - QualType NewQT = QT.getSingleStepDesugaredType(Finder->getASTContext()); + const QualType NewQT = + QT.getSingleStepDesugaredType(Finder->getASTContext()); if (NewQT == QT) return false; QT = NewQT; @@ -147,18 +148,19 @@ static Matcher hasStdIteratorName() { /// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list /// but not \c my_vec. static Matcher hasStdContainerName() { - static StringRef ContainerNames[] = {"array", "deque", - "forward_list", "list", - "vector", + static const StringRef ContainerNames[] = { + "array", "deque", + "forward_list", "list", + "vector", - "map", "multimap", - "set", "multiset", + "map", "multimap", + "set", "multiset", - "unordered_map", "unordered_multimap", - "unordered_set", "unordered_multiset", + "unordered_map", "unordered_multimap", + "unordered_set", "unordered_multiset", - "queue", "priority_queue", - "stack"}; + "queue", "priority_queue", + "stack"}; return hasAnyName(ContainerNames); } @@ -326,7 +328,8 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) { // like function pointers. Not a concern since this action only works with // iterators but something to keep in mind in the future. - SourceRange Range(V->getTypeSourceInfo()->getTypeLoc().getSourceRange()); + const SourceRange Range( + V->getTypeSourceInfo()->getTypeLoc().getSourceRange()); diag(Range.getBegin(), "use auto when declaring iterators") << FixItHint::CreateReplacement(Range, "auto"); } @@ -342,7 +345,7 @@ static bool isMultiLevelPointerToTypeLocClasses( TypeLoc Loc, const std::initializer_list &LocClasses) { ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified}); - TypeLoc::TypeLocClass TLC = Loc.getTypeLocClass(); + const TypeLoc::TypeLocClass TLC = Loc.getTypeLocClass(); if (TLC != TypeLoc::Pointer && TLC != TypeLoc::MemberPointer) return false; ignoreTypeLocClasses(Loc, {TypeLoc::Paren, TypeLoc::Qualified, @@ -359,7 +362,7 @@ void UseAutoCheck::replaceExpr( return; const QualType FirstDeclType = FirstDecl->getType().getCanonicalType(); - TypeSourceInfo *TSI = FirstDecl->getTypeSourceInfo(); + const TypeSourceInfo *TSI = FirstDecl->getTypeSourceInfo(); if (TSI == nullptr) return; @@ -409,7 +412,7 @@ void UseAutoCheck::replaceExpr( ignoreTypeLocClasses(Loc, {TypeLoc::Pointer, TypeLoc::Qualified}); ignoreTypeLocClasses(Loc, {TypeLoc::LValueReference, TypeLoc::RValueReference, TypeLoc::Qualified}); - SourceRange Range(Loc.getSourceRange()); + const SourceRange Range(Loc.getSourceRange()); if (MinTypeNameLength != 0 && getTypeNameLength(RemoveStars, @@ -420,17 +423,17 @@ void UseAutoCheck::replaceExpr( auto Diag = diag(Range.getBegin(), Message); - bool ShouldReplenishVariableName = isMultiLevelPointerToTypeLocClasses( + const bool ShouldReplenishVariableName = isMultiLevelPointerToTypeLocClasses( TSI->getTypeLoc(), {TypeLoc::FunctionProto, TypeLoc::ConstantArray}); // Space after 'auto' to handle cases where the '*' in the pointer type is // next to the identifier. This avoids changing 'int *p' into 'autop'. - llvm::StringRef Auto = ShouldReplenishVariableName - ? (RemoveStars ? "auto " : "auto *") - : (RemoveStars ? "auto " : "auto"); - std::string ReplenishedVariableName = + const llvm::StringRef Auto = ShouldReplenishVariableName + ? (RemoveStars ? "auto " : "auto *") + : (RemoveStars ? "auto " : "auto"); + const std::string ReplenishedVariableName = ShouldReplenishVariableName ? FirstDecl->getQualifiedNameAsString() : ""; - std::string Replacement = + const std::string Replacement = (Auto + llvm::StringRef{ReplenishedVariableName}).str(); Diag << FixItHint::CreateReplacement(Range, Replacement) << StarRemovals; } diff --git a/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp index 8b5ffe86b1839..6e2118787f9b4 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp @@ -50,14 +50,14 @@ void UseBoolLiteralsCheck::registerMatchers(MatchFinder *Finder) { void UseBoolLiteralsCheck::check(const MatchFinder::MatchResult &Result) { const auto *Literal = Result.Nodes.getNodeAs("literal"); const auto *Cast = Result.Nodes.getNodeAs("cast"); - bool LiteralBooleanValue = Literal->getValue().getBoolValue(); + const bool LiteralBooleanValue = Literal->getValue().getBoolValue(); if (Literal->isInstantiationDependent()) return; const Expr *Expression = Cast ? Cast : Literal; - bool InMacro = Expression->getBeginLoc().isMacroID(); + const bool InMacro = Expression->getBeginLoc().isMacroID(); if (InMacro && IgnoreMacros) return; diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp index d5342a1664153..fdb088fe44be2 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp @@ -55,7 +55,7 @@ static std::optional matchEnableIfSpecializationImplTypename(TypeLoc TheType) { if (const auto Dep = TheType.getAs()) { const IdentifierInfo *Identifier = Dep.getTypePtr()->getIdentifier(); - ElaboratedTypeKeyword Keyword = Dep.getTypePtr()->getKeyword(); + const ElaboratedTypeKeyword Keyword = Dep.getTypePtr()->getKeyword(); if (!Identifier || Identifier->getName() != "type" || (Keyword != ElaboratedTypeKeyword::Typename && Keyword != ElaboratedTypeKeyword::None)) { @@ -88,7 +88,7 @@ matchEnableIfSpecializationImplTypename(TypeLoc TheType) { if (!FirstParam || !FirstParam->getType()->isBooleanType()) return std::nullopt; - int NumArgs = SpecializationLoc.getNumArgs(); + const int NumArgs = SpecializationLoc.getNumArgs(); if (NumArgs != 1 && NumArgs != 2) return std::nullopt; @@ -124,7 +124,7 @@ matchEnableIfSpecializationImplTrait(TypeLoc TheType) { if (const auto *AliasedType = dyn_cast(Specialization->getAliasedType())) { - ElaboratedTypeKeyword Keyword = AliasedType->getKeyword(); + const ElaboratedTypeKeyword Keyword = AliasedType->getKeyword(); if (AliasedType->getIdentifier()->getName() != "type" || (Keyword != ElaboratedTypeKeyword::Typename && Keyword != ElaboratedTypeKeyword::None)) { @@ -133,7 +133,7 @@ matchEnableIfSpecializationImplTrait(TypeLoc TheType) { } else { return std::nullopt; } - int NumArgs = SpecializationLoc.getNumArgs(); + const int NumArgs = SpecializationLoc.getNumArgs(); if (NumArgs != 1 && NumArgs != 2) return std::nullopt; @@ -223,7 +223,7 @@ getConditionRange(ASTContext &Context, const LangOptions &LangOpts = Context.getLangOpts(); const SourceManager &SM = Context.getSourceManager(); if (EnableIf.getNumArgs() > 1) { - TemplateArgumentLoc NextArg = EnableIf.getArgLoc(1); + const TemplateArgumentLoc NextArg = EnableIf.getArgLoc(1); return {EnableIf.getLAngleLoc().getLocWithOffset(1), utils::lexer::findPreviousTokenKind( NextArg.getSourceRange().getBegin(), SM, LangOpts, tok::comma)}; @@ -235,7 +235,7 @@ getConditionRange(ASTContext &Context, static SourceRange getTypeRange(ASTContext &Context, const TemplateSpecializationTypeLoc &EnableIf) { - TemplateArgumentLoc Arg = EnableIf.getArgLoc(1); + const TemplateArgumentLoc Arg = EnableIf.getArgLoc(1); const LangOptions &LangOpts = Context.getLangOpts(); const SourceManager &SM = Context.getSourceManager(); return {utils::lexer::findPreviousTokenKind(Arg.getSourceRange().getBegin(), @@ -269,7 +269,7 @@ getTypeText(ASTContext &Context, static std::optional findInsertionForConstraint(const FunctionDecl *Function, ASTContext &Context) { - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); const LangOptions &LangOpts = Context.getLangOpts(); if (const auto *Constructor = dyn_cast(Function)) { @@ -282,7 +282,7 @@ findInsertionForConstraint(const FunctionDecl *Function, ASTContext &Context) { return std::nullopt; } if (Function->isDeleted()) { - SourceLocation FunctionEnd = Function->getSourceRange().getEnd(); + const SourceLocation FunctionEnd = Function->getSourceRange().getEnd(); return utils::lexer::findNextAnyTokenKind(FunctionEnd, SM, LangOpts, tok::equal, tok::equal); } @@ -314,7 +314,7 @@ static bool isPrimaryExpression(const Expr *Expression) { static std::optional getConditionText(const Expr *ConditionExpr, SourceRange ConditionRange, ASTContext &Context) { - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); const LangOptions &LangOpts = Context.getLangOpts(); SourceLocation PrevTokenLoc = ConditionRange.getEnd(); @@ -325,14 +325,14 @@ static std::optional getConditionText(const Expr *ConditionExpr, Token PrevToken; std::tie(PrevToken, PrevTokenLoc) = utils::lexer::getPreviousTokenAndStart( PrevTokenLoc, SM, LangOpts, SkipComments); - bool EndsWithDoubleSlash = + const bool EndsWithDoubleSlash = PrevToken.is(tok::comment) && Lexer::getSourceText(CharSourceRange::getCharRange( PrevTokenLoc, PrevTokenLoc.getLocWithOffset(2)), SM, LangOpts) == "//"; bool Invalid = false; - llvm::StringRef ConditionText = Lexer::getSourceText( + const llvm::StringRef ConditionText = Lexer::getSourceText( CharSourceRange::getCharRange(ConditionRange), SM, LangOpts, &Invalid); if (Invalid) return std::nullopt; @@ -361,9 +361,9 @@ static std::vector handleReturnType(const FunctionDecl *Function, const TypeLoc &ReturnType, const EnableIfData &EnableIf, ASTContext &Context) { - TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0); + const TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0); - SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc); + const SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc); std::optional ConditionText = getConditionText( EnableCondition.getSourceExpression(), ConditionRange, Context); @@ -410,12 +410,12 @@ handleTrailingTemplateType(const FunctionTemplateDecl *FunctionTemplate, const FunctionDecl *Function, const Decl *LastTemplateParam, const EnableIfData &EnableIf, ASTContext &Context) { - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); const LangOptions &LangOpts = Context.getLangOpts(); - TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0); + const TemplateArgumentLoc EnableCondition = EnableIf.Loc.getArgLoc(0); - SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc); + const SourceRange ConditionRange = getConditionRange(Context, EnableIf.Loc); std::optional ConditionText = getConditionText( EnableCondition.getSourceExpression(), ConditionRange, Context); From 545c3022d28164f5040036a7b515a85f74dbd5cc Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 18:55:22 +0300 Subject: [PATCH 15/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (8/N) (#167123) --- .../AvoidConstParamsInDeclsCheck.cpp | 2 +- .../AvoidReturnWithVoidValueCheck.cpp | 6 +- .../AvoidUnconditionalPreprocessorIfCheck.cpp | 2 +- .../BracesAroundStatementsCheck.cpp | 18 ++-- .../readability/ConstReturnTypeCheck.cpp | 12 +-- .../readability/ContainerContainsCheck.cpp | 4 +- .../readability/ContainerDataPointerCheck.cpp | 4 +- .../ConvertMemberFunctionsToStaticCheck.cpp | 20 ++-- .../readability/DuplicateIncludeCheck.cpp | 4 +- .../readability/ElseAfterReturnCheck.cpp | 26 +++--- .../readability/EnumInitialValueCheck.cpp | 4 +- .../FunctionCognitiveComplexityCheck.cpp | 8 +- .../readability/FunctionSizeCheck.cpp | 4 +- .../readability/IdentifierLengthCheck.cpp | 8 +- .../readability/IdentifierNamingCheck.cpp | 91 ++++++++++--------- .../ImplicitBoolConversionCheck.cpp | 32 +++---- ...onsistentDeclarationParameterNameCheck.cpp | 12 +-- .../readability/IsolateDeclarationCheck.cpp | 16 ++-- .../readability/MagicNumbersCheck.cpp | 4 +- .../MakeMemberFunctionConstCheck.cpp | 4 +- .../MathMissingParenthesesCheck.cpp | 4 +- .../MisleadingIndentationCheck.cpp | 10 +- 22 files changed, 151 insertions(+), 144 deletions(-) diff --git a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp index 0e1c389d0d80a..affcea441ada7 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDeclsCheck.cpp @@ -27,7 +27,7 @@ static std::optional findConstToRemove(const ParmVarDecl &Param, const MatchFinder::MatchResult &Result) { - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getTokenRange(getTypeRange(Param)), *Result.SourceManager, Result.Context->getLangOpts()); diff --git a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp index 40a4fa114681e..2b31281bb4a63 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidReturnWithVoidValueCheck.cpp @@ -47,9 +47,9 @@ void AvoidReturnWithVoidValueCheck::check( Result.Nodes.getNodeAs("compound_parent"); if (!StrictMode && !SurroundingBlock) return; - DiagnosticBuilder Diag = diag(VoidReturn->getBeginLoc(), - "return statement within a void function " - "should not have a specified return value"); + const DiagnosticBuilder Diag = diag( + VoidReturn->getBeginLoc(), "return statement within a void function " + "should not have a specified return value"); const SourceLocation SemicolonPos = utils::lexer::findNextTerminator( VoidReturn->getEndLoc(), *Result.SourceManager, getLangOpts()); if (SemicolonPos.isInvalid()) diff --git a/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp b/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp index c53c70667dbbc..631bb14753163 100644 --- a/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/AvoidUnconditionalPreprocessorIfCheck.cpp @@ -40,7 +40,7 @@ struct AvoidUnconditionalPreprocessorIfPPCallbacks : public PPCallbacks { bool isImmutable(SourceManager &SM, const LangOptions &LangOpts, SourceRange ConditionRange) { - SourceLocation Loc = ConditionRange.getBegin(); + const SourceLocation Loc = ConditionRange.getBegin(); if (Loc.isMacroID()) return false; diff --git a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp index 1952e14d1fc3d..2b55bb819da9c 100644 --- a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp @@ -20,7 +20,8 @@ namespace clang::tidy::readability { static tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { Token Tok; - SourceLocation Beginning = Lexer::GetBeginningOfToken(Loc, SM, LangOpts); + const SourceLocation Beginning = + Lexer::GetBeginningOfToken(Loc, SM, LangOpts); const bool Invalid = Lexer::getRawToken(Beginning, Tok, SM, LangOpts); assert(!Invalid && "Expected a valid token."); @@ -38,7 +39,7 @@ forwardSkipWhitespaceAndComments(SourceLocation Loc, const SourceManager &SM, while (isWhitespace(*SM.getCharacterData(Loc))) Loc = Loc.getLocWithOffset(1); - tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts); + const tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts); if (TokKind != tok::comment) return Loc; @@ -80,7 +81,8 @@ void BracesAroundStatementsCheck::check( } else if (const auto *S = Result.Nodes.getNodeAs("do")) { checkStmt(Result, S->getBody(), S->getDoLoc(), S->getWhileLoc()); } else if (const auto *S = Result.Nodes.getNodeAs("while")) { - SourceLocation StartLoc = findRParenLoc(S, SM, Context->getLangOpts()); + const SourceLocation StartLoc = + findRParenLoc(S, SM, Context->getLangOpts()); if (StartLoc.isInvalid()) return; checkStmt(Result, S->getBody(), StartLoc); @@ -89,12 +91,14 @@ void BracesAroundStatementsCheck::check( if (S->isConsteval()) return; - SourceLocation StartLoc = findRParenLoc(S, SM, Context->getLangOpts()); + const SourceLocation StartLoc = + findRParenLoc(S, SM, Context->getLangOpts()); if (StartLoc.isInvalid()) return; if (ForceBracesStmts.erase(S)) ForceBracesStmts.insert(S->getThen()); - bool BracedIf = checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); + const bool BracedIf = + checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc()); const Stmt *Else = S->getElse(); if (Else && BracedIf) ForceBracesStmts.insert(Else); @@ -125,7 +129,7 @@ BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, return {}; } - SourceLocation PastCondEndLoc = + const SourceLocation PastCondEndLoc = Lexer::getLocForEndOfToken(CondEndLoc, 0, SM, LangOpts); if (PastCondEndLoc.isInvalid()) return {}; @@ -133,7 +137,7 @@ BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S, forwardSkipWhitespaceAndComments(PastCondEndLoc, SM, LangOpts); if (RParenLoc.isInvalid()) return {}; - tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, LangOpts); + const tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, LangOpts); if (TokKind != tok::r_paren) return {}; return RParenLoc; diff --git a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp index 6ccd933ff4c21..cfdf0e9c4a331 100644 --- a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp @@ -32,13 +32,13 @@ findConstToRemove(const FunctionDecl *Def, // written in the source (for out-of-line declarations). A FunctionDecl's // "location" is the start of its name, so, when the name is unqualified, we // use `getLocation()`. - SourceLocation NameBeginLoc = Def->getQualifier() - ? Def->getQualifierLoc().getBeginLoc() - : Def->getLocation(); + const SourceLocation NameBeginLoc = Def->getQualifier() + ? Def->getQualifierLoc().getBeginLoc() + : Def->getLocation(); // Since either of the locs can be in a macro, use `makeFileCharRange` to be // sure that we have a consistent `CharSourceRange`, located entirely in the // source file. - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getCharRange(Def->getBeginLoc(), NameBeginLoc), *Result.SourceManager, Result.Context->getLangOpts()); @@ -118,12 +118,12 @@ void ConstReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { (Def->getBeginLoc().isMacroID() || Def->getEndLoc().isMacroID())) return; - CheckResult CR = checkDef(Def, Result); + const CheckResult CR = checkDef(Def, Result); { // Clang only supports one in-flight diagnostic at a time. So, delimit the // scope of `Diagnostic` to allow further diagnostics after the scope. We // use `getInnerLocStart` to get the start of the return type. - DiagnosticBuilder Diagnostic = + const DiagnosticBuilder Diagnostic = diag(Def->getInnerLocStart(), "return type %0 is 'const'-qualified at the top level, which may " "reduce code readability without improving const correctness") diff --git a/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp b/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp index 850ef86c85b17..a3405524553d4 100644 --- a/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ContainerContainsCheck.cpp @@ -110,7 +110,7 @@ void ContainerContainsCheck::check(const MatchFinder::MatchResult &Result) { Result.Nodes.getNodeAs("negativeComparison"); assert((!PositiveComparison || !NegativeComparison) && "only one of PositiveComparison or NegativeComparison should be set"); - bool Negated = NegativeComparison != nullptr; + const bool Negated = NegativeComparison != nullptr; const auto *Comparison = Negated ? NegativeComparison : PositiveComparison; const StringRef ContainsFunName = Result.Nodes.getNodeAs("contains_fun")->getName(); @@ -121,7 +121,7 @@ void ContainerContainsCheck::check(const MatchFinder::MatchResult &Result) { << ContainsFunName; // Don't fix it if it's in a macro invocation. Leave fixing it to the user. - SourceLocation FuncCallLoc = Comparison->getEndLoc(); + const SourceLocation FuncCallLoc = Comparison->getEndLoc(); if (!FuncCallLoc.isValid() || FuncCallLoc.isMacroID()) return; diff --git a/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp b/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp index 11756d10a8221..a5a6e3ce7af01 100644 --- a/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ContainerDataPointerCheck.cpp @@ -101,7 +101,7 @@ void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) { else if (ACE) CE = ACE; - SourceRange SrcRange = CE->getSourceRange(); + const SourceRange SrcRange = CE->getSourceRange(); std::string ReplacementText{ Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), @@ -116,7 +116,7 @@ void ContainerDataPointerCheck::check(const MatchFinder::MatchResult &Result) { else ReplacementText += ".data()"; - FixItHint Hint = + const FixItHint Hint = FixItHint::CreateReplacement(UO->getSourceRange(), ReplacementText); diag(UO->getBeginLoc(), "'data' should be used for accessing the data pointer instead of taking " diff --git a/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp index 1383e3b0b77f6..e6276e317b3ff 100644 --- a/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStaticCheck.cpp @@ -119,16 +119,16 @@ static SourceRange getLocationOfConst(const TypeSourceInfo *TSI, const auto FTL = TSI->getTypeLoc().IgnoreParens().getAs(); assert(FTL); - SourceRange Range{FTL.getRParenLoc().getLocWithOffset(1), - FTL.getLocalRangeEnd()}; + const SourceRange Range{FTL.getRParenLoc().getLocWithOffset(1), + FTL.getLocalRangeEnd()}; // Inside Range, there might be other keywords and trailing return types. // Find the exact position of "const". - StringRef Text = getStringFromRange(SourceMgr, LangOpts, Range); - size_t Offset = Text.find("const"); + const StringRef Text = getStringFromRange(SourceMgr, LangOpts, Range); + const size_t Offset = Text.find("const"); if (Offset == StringRef::npos) return {}; - SourceLocation Start = Range.getBegin().getLocWithOffset(Offset); + const SourceLocation Start = Range.getBegin().getLocWithOffset(Offset); return {Start, Start.getLocWithOffset(strlen("const") - 1)}; } @@ -138,7 +138,7 @@ void ConvertMemberFunctionsToStaticCheck::check( // TODO: For out-of-line declarations, don't modify the source if the header // is excluded by the -header-filter option. - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(Definition->getLocation(), "method %0 can be made static") << Definition; @@ -153,15 +153,15 @@ void ConvertMemberFunctionsToStaticCheck::check( if (Definition->isConst()) { // Make sure that we either remove 'const' on both declaration and // definition or emit no fix-it at all. - SourceRange DefConst = getLocationOfConst(Definition->getTypeSourceInfo(), - *Result.SourceManager, - Result.Context->getLangOpts()); + const SourceRange DefConst = getLocationOfConst( + Definition->getTypeSourceInfo(), *Result.SourceManager, + Result.Context->getLangOpts()); if (DefConst.isInvalid()) return; if (Declaration != Definition) { - SourceRange DeclConst = getLocationOfConst( + const SourceRange DeclConst = getLocationOfConst( Declaration->getTypeSourceInfo(), *Result.SourceManager, Result.Context->getLangOpts()); diff --git a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp index 0237c057afed5..cc9ae471a926d 100644 --- a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp @@ -88,9 +88,9 @@ void DuplicateIncludeCallbacks::InclusionDirective( if (llvm::is_contained(Files.back(), FileName)) { // We want to delete the entire line, so make sure that [Start,End] covers // everything. - SourceLocation Start = + const SourceLocation Start = advanceBeyondCurrentLine(SM, HashLoc, -1).getLocWithOffset(-1); - SourceLocation End = + const SourceLocation End = advanceBeyondCurrentLine(SM, FilenameRange.getEnd(), 1); Check.diag(HashLoc, "duplicate include") << FixItHint::CreateRemoval(SourceRange{Start, End}); diff --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp index 6399e7d99a9c7..a420c5653cfe8 100644 --- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp @@ -124,21 +124,21 @@ static void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context, if (const auto *CS = dyn_cast(Else)) { Diag << tooling::fixit::createRemoval(ElseLoc); - SourceLocation LBrace = CS->getLBracLoc(); - SourceLocation RBrace = CS->getRBracLoc(); - SourceLocation RangeStart = + const SourceLocation LBrace = CS->getLBracLoc(); + const SourceLocation RBrace = CS->getRBracLoc(); + const SourceLocation RangeStart = Remap(LBrace).getLocWithOffset(TokLen(LBrace) + 1); - SourceLocation RangeEnd = Remap(RBrace).getLocWithOffset(-1); + const SourceLocation RangeEnd = Remap(RBrace).getLocWithOffset(-1); - llvm::StringRef Repl = Lexer::getSourceText( + const llvm::StringRef Repl = Lexer::getSourceText( CharSourceRange::getTokenRange(RangeStart, RangeEnd), Context.getSourceManager(), Context.getLangOpts()); Diag << tooling::fixit::createReplacement(CS->getSourceRange(), Repl); } else { - SourceLocation ElseExpandedLoc = Remap(ElseLoc); - SourceLocation EndLoc = Remap(Else->getEndLoc()); + const SourceLocation ElseExpandedLoc = Remap(ElseLoc); + const SourceLocation EndLoc = Remap(Else->getEndLoc()); - llvm::StringRef Repl = Lexer::getSourceText( + const llvm::StringRef Repl = Lexer::getSourceText( CharSourceRange::getTokenRange( ElseExpandedLoc.getLocWithOffset(TokLen(ElseLoc) + 1), EndLoc), Context.getSourceManager(), Context.getLangOpts()); @@ -186,8 +186,8 @@ static bool hasPreprocessorBranchEndBetweenLocations( const ElseAfterReturnCheck::ConditionalBranchMap &ConditionalBranchMap, const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLoc) { - SourceLocation ExpandedStartLoc = SM.getExpansionLoc(StartLoc); - SourceLocation ExpandedEndLoc = SM.getExpansionLoc(EndLoc); + const SourceLocation ExpandedStartLoc = SM.getExpansionLoc(StartLoc); + const SourceLocation ExpandedEndLoc = SM.getExpansionLoc(EndLoc); if (!SM.isWrittenInSameFile(ExpandedStartLoc, ExpandedEndLoc)) return false; @@ -239,14 +239,14 @@ void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) { const auto *Else = Result.Nodes.getNodeAs("else"); const auto *OuterScope = Result.Nodes.getNodeAs("cs"); const auto *Interrupt = Result.Nodes.getNodeAs(InterruptingStr); - SourceLocation ElseLoc = If->getElseLoc(); + const SourceLocation ElseLoc = If->getElseLoc(); if (hasPreprocessorBranchEndBetweenLocations( PPConditionals, *Result.SourceManager, Interrupt->getBeginLoc(), ElseLoc)) return; - bool IsLastInScope = OuterScope->body_back() == If; + const bool IsLastInScope = OuterScope->body_back() == If; const StringRef ControlFlowInterrupter = getControlFlowString(*Interrupt); if (!IsLastInScope && containsDeclInScope(Else)) { @@ -276,7 +276,7 @@ void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) { } const DeclStmt *VDeclStmt = If->getConditionVariableDeclStmt(); const VarDecl *VDecl = If->getConditionVariable(); - std::string Repl = + const std::string Repl = (tooling::fixit::getText(*VDeclStmt, *Result.Context) + llvm::StringRef(";\n") + tooling::fixit::getText(If->getIfLoc(), *Result.Context)) diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp index a2a5c3e10ee07..049ad759b834c 100644 --- a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp @@ -75,7 +75,7 @@ static void cleanInitialValue(DiagnosticBuilder &Diag, namespace { AST_MATCHER(EnumDecl, isMacro) { - SourceLocation Loc = Node.getBeginLoc(); + const SourceLocation Loc = Node.getBeginLoc(); return Loc.isMacroID(); } @@ -165,7 +165,7 @@ void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) { void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *Enum = Result.Nodes.getNodeAs("inconsistent")) { - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag( Enum->getBeginLoc(), "initial values in enum '%0' are not consistent, consider explicit " diff --git a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp index 4791df037d77d..ccac645892948 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp @@ -229,14 +229,14 @@ class FunctionASTVisitor final bool traverseStmtWithIncreasedNestingLevel(Stmt *Node) { ++CurrentNestingLevel; - bool ShouldContinue = Base::TraverseStmt(Node); + const bool ShouldContinue = Base::TraverseStmt(Node); --CurrentNestingLevel; return ShouldContinue; } bool traverseDeclWithIncreasedNestingLevel(Decl *Node) { ++CurrentNestingLevel; - bool ShouldContinue = Base::TraverseDecl(Node); + const bool ShouldContinue = Base::TraverseDecl(Node); --CurrentNestingLevel; return ShouldContinue; } @@ -336,7 +336,7 @@ class FunctionASTVisitor final // Record the operator that we are currently processing and traverse it. CurrentBinaryOperator = Op->getOpcode(); - bool ShouldContinue = Base::TraverseBinaryOperator(Op); + const bool ShouldContinue = Base::TraverseBinaryOperator(Op); // And restore the previous binary operator, which might be nonexistent. CurrentBinaryOperator = BinOpCopy; @@ -354,7 +354,7 @@ class FunctionASTVisitor final // Else, do add [uninitialized] frame to the stack, and traverse call. BinaryOperatorsStack.emplace(); - bool ShouldContinue = Base::TraverseCallExpr(Node); + const bool ShouldContinue = Base::TraverseCallExpr(Node); // And remove the top frame. BinaryOperatorsStack.pop(); diff --git a/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp index 8c58346ede3fa..2f0949c231844 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp @@ -181,14 +181,14 @@ void FunctionSizeCheck::check(const MatchFinder::MatchResult &Result) { // Count the lines including whitespace and comments. Really simple. if (const Stmt *Body = Func->getBody()) { - SourceManager *SM = Result.SourceManager; + const SourceManager *SM = Result.SourceManager; if (SM->isWrittenInSameFile(Body->getBeginLoc(), Body->getEndLoc())) { FI.Lines = SM->getSpellingLineNumber(Body->getEndLoc()) - SM->getSpellingLineNumber(Body->getBeginLoc()); } } - unsigned ActualNumberParameters = Func->getNumParams(); + const unsigned ActualNumberParameters = Func->getNumParams(); if ((LineThreshold && FI.Lines > LineThreshold) || (StatementThreshold && FI.Statements > StatementThreshold) || diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp index 877f0a45f9ea7..a6204de16224d 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierLengthCheck.cpp @@ -91,7 +91,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!StandaloneVar->getIdentifier()) return; - StringRef VarName = StandaloneVar->getName(); + const StringRef VarName = StandaloneVar->getName(); if (VarName.size() >= MinimumVariableNameLength || IgnoredVariableNames.match(VarName)) @@ -106,7 +106,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!ExceptionVarName->getIdentifier()) return; - StringRef VarName = ExceptionVarName->getName(); + const StringRef VarName = ExceptionVarName->getName(); if (VarName.size() >= MinimumExceptionNameLength || IgnoredExceptionVariableNames.match(VarName)) return; @@ -120,7 +120,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!LoopVar->getIdentifier()) return; - StringRef VarName = LoopVar->getName(); + const StringRef VarName = LoopVar->getName(); if (VarName.size() >= MinimumLoopCounterNameLength || IgnoredLoopCounterNames.match(VarName)) @@ -135,7 +135,7 @@ void IdentifierLengthCheck::check(const MatchFinder::MatchResult &Result) { if (!ParamVar->getIdentifier()) return; - StringRef VarName = ParamVar->getName(); + const StringRef VarName = ParamVar->getName(); if (VarName.size() >= MinimumParameterNameLength || IgnoredParameterNames.match(VarName)) diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp index ef3eac80301d3..890ce4074345d 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp @@ -261,7 +261,7 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( Styles.resize(SK_Count); SmallString<64> StyleString; for (unsigned I = 0; I < SK_Count; ++I) { - size_t StyleSize = StyleNames[I].size(); + const size_t StyleSize = StyleNames[I].size(); StyleString.assign({StyleNames[I], "HungarianPrefix"}); auto HPTOpt = @@ -271,13 +271,13 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13); StyleString.truncate(StyleSize + 13); - std::optional IgnoredRegexpStr = Options.get(StyleString); + const std::optional IgnoredRegexpStr = Options.get(StyleString); memcpy(&StyleString[StyleSize], "Prefix", 6); StyleString.truncate(StyleSize + 6); - std::optional Prefix(Options.get(StyleString)); + const std::optional Prefix(Options.get(StyleString)); // Fast replacement of [Pre]fix -> [Suf]fix. memcpy(&StyleString[StyleSize], "Suf", 3); - std::optional Postfix(Options.get(StyleString)); + const std::optional Postfix(Options.get(StyleString)); memcpy(&StyleString[StyleSize], "Case", 4); StyleString.pop_back_n(2); std::optional CaseOptional = @@ -288,8 +288,9 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions( Postfix.value_or(""), IgnoredRegexpStr.value_or(""), HPTOpt.value_or(IdentifierNamingCheck::HPT_Off)); } - bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false); - bool CheckAnonFieldInParent = Options.get("CheckAnonFieldInParent", false); + const bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false); + const bool CheckAnonFieldInParent = + Options.get("CheckAnonFieldInParent", false); return {std::move(Styles), std::move(HNOption), IgnoreMainLike, CheckAnonFieldInParent}; } @@ -340,7 +341,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( "virtual"}; // Remove keywords - for (StringRef Kw : Keywords) { + for (const StringRef Kw : Keywords) { for (size_t Pos = 0; (Pos = Type.find(Kw, Pos)) != std::string::npos;) { Type.replace(Pos, Kw.size(), ""); } @@ -376,7 +377,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( " int", " char", " double", " long", " short"}; bool RedundantRemoved = false; for (auto Kw : TailsOfMultiWordType) { - size_t Pos = Type.rfind(Kw); + const size_t Pos = Type.rfind(Kw); if (Pos != std::string::npos) { const size_t PtrCount = getAsteriskCount(Type, ND); Type = Type.substr(0, Pos + Kw.size() + PtrCount); @@ -387,14 +388,14 @@ std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName( TypeName = Type.erase(0, Type.find_first_not_of(' ')); if (!RedundantRemoved) { - std::size_t FoundSpace = Type.find(' '); + const std::size_t FoundSpace = Type.find(' '); if (FoundSpace != std::string::npos) Type = Type.substr(0, FoundSpace); } TypeName = Type.erase(0, Type.find_first_not_of(' ')); - QualType QT = VD->getType(); + const QualType QT = VD->getType(); if (!QT.isNull() && QT->isArrayType()) TypeName.append("[]"); } @@ -451,14 +452,14 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( static constexpr StringRef HNDerivedTypes[] = {"Array", "Pointer", "FunctionPointer"}; - StringRef Section = "HungarianNotation."; + const StringRef Section = "HungarianNotation."; SmallString<128> Buffer = {Section, "General."}; size_t DefSize = Buffer.size(); for (const auto &Opt : HNOpts) { Buffer.truncate(DefSize); Buffer.append(Opt); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.General[Opt] = Val.str(); } @@ -468,7 +469,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &Type : HNDerivedTypes) { Buffer.truncate(DefSize); Buffer.append(Type); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.DerivedType[Type] = Val.str(); } @@ -484,7 +485,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &CStr : HNCStrings) { Buffer.truncate(DefSize); Buffer.append(CStr.first); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.CString[CStr.second] = Val.str(); } @@ -494,7 +495,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &PrimType : HungarianNotationPrimitiveTypes) { Buffer.truncate(DefSize); Buffer.append(PrimType); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) { std::string Type = PrimType.str(); llvm::replace(Type, '-', ' '); @@ -507,7 +508,7 @@ void IdentifierNamingCheck::HungarianNotation::loadFileConfig( for (const auto &Type : HungarianNotationUserDefinedTypes) { Buffer.truncate(DefSize); Buffer.append(Type); - StringRef Val = Options.get(Buffer, ""); + const StringRef Val = Options.get(Buffer, ""); if (!Val.empty()) HNOption.UserDefinedType[Type] = Val.str(); } @@ -528,7 +529,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getPrefix( } else if (const auto *CRD = dyn_cast(ND)) { Prefix = getClassPrefix(CRD, HNOption); } else if (isa(ND)) { - std::string TypeName = getDeclTypeName(ND); + const std::string TypeName = getDeclTypeName(ND); if (!TypeName.empty()) Prefix = getDataTypePrefix(TypeName, ND, HNOption); } @@ -542,8 +543,8 @@ bool IdentifierNamingCheck::HungarianNotation::removeDuplicatedPrefix( if (Words.size() <= 1) return true; - std::string CorrectName = Words[0].str(); - std::vector> MapList = { + const std::string CorrectName = Words[0].str(); + const std::vector> MapList = { HNOption.CString, HNOption.DerivedType, HNOption.PrimitiveType, HNOption.UserDefinedType}; @@ -570,12 +571,12 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( // Derived types std::string PrefixStr; if (const auto *TD = dyn_cast(ND)) { - QualType QT = TD->getType(); + const QualType QT = TD->getType(); if (QT->isFunctionPointerType()) { PrefixStr = HNOption.DerivedType.lookup("FunctionPointer"); } else if (QT->isPointerType()) { for (const auto &CStr : HNOption.CString) { - std::string Key = CStr.getKey().str(); + const std::string Key = CStr.getKey().str(); if (ModifiedTypeName.find(Key) == 0) { PrefixStr = CStr.getValue(); ModifiedTypeName = ModifiedTypeName.substr( @@ -585,7 +586,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( } } else if (QT->isArrayType()) { for (const auto &CStr : HNOption.CString) { - std::string Key = CStr.getKey().str(); + const std::string Key = CStr.getKey().str(); if (ModifiedTypeName.find(Key) == 0) { PrefixStr = CStr.getValue(); break; @@ -594,14 +595,14 @@ std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix( if (PrefixStr.empty()) PrefixStr = HNOption.DerivedType.lookup("Array"); } else if (QT->isReferenceType()) { - size_t Pos = ModifiedTypeName.find_last_of('&'); + const size_t Pos = ModifiedTypeName.find_last_of('&'); if (Pos != std::string::npos) ModifiedTypeName = ModifiedTypeName.substr(0, Pos); } } // Pointers - size_t PtrCount = getAsteriskCount(ModifiedTypeName); + const size_t PtrCount = getAsteriskCount(ModifiedTypeName); if (PtrCount > 0) { ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) { size_t StartPos = 0; @@ -663,10 +664,10 @@ std::string IdentifierNamingCheck::HungarianNotation::getEnumPrefix( Name = Name.erase(0, Name.find_first_not_of(' ')); } - static llvm::Regex Splitter( + static const llvm::Regex Splitter( "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)"); - StringRef EnumName(Name); + const StringRef EnumName(Name); SmallVector Substrs; EnumName.split(Substrs, "_", -1, false); @@ -692,7 +693,7 @@ std::string IdentifierNamingCheck::HungarianNotation::getEnumPrefix( } std::string Initial; - for (StringRef Word : Words) + for (const StringRef Word : Words) Initial += tolower(Word[0]); return Initial; @@ -713,7 +714,7 @@ size_t IdentifierNamingCheck::HungarianNotation::getAsteriskCount( const std::string &TypeName, const NamedDecl *ND) const { size_t PtrCount = 0; if (const auto *TD = dyn_cast(ND)) { - QualType QT = TD->getType(); + const QualType QT = TD->getType(); if (QT->isPointerType()) PtrCount = getAsteriskCount(TypeName); } @@ -834,11 +835,12 @@ void IdentifierNamingCheck::HungarianNotation::loadDefaultConfig( void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { RenamerClangTidyCheck::storeOptions(Opts); SmallString<64> StyleString; - ArrayRef> Styles = MainFileStyle->getStyles(); + const ArrayRef> Styles = + MainFileStyle->getStyles(); for (size_t I = 0; I < SK_Count; ++I) { if (!Styles[I]) continue; - size_t StyleSize = StyleNames[I].size(); + const size_t StyleSize = StyleNames[I].size(); StyleString.assign({StyleNames[I], "HungarianPrefix"}); Options.store(Opts, StyleString, Styles[I]->HPType); @@ -871,7 +873,7 @@ bool IdentifierNamingCheck::matchesStyle( const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const NamedDecl *Decl) const { - static llvm::Regex Matchers[] = { + static const llvm::Regex Matchers[] = { llvm::Regex("^.*$"), llvm::Regex("^[a-z][a-z0-9_]*$"), llvm::Regex("^[a-z][a-zA-Z0-9]*$"), @@ -887,7 +889,7 @@ bool IdentifierNamingCheck::matchesStyle( if (!Name.consume_back(Style.Suffix)) return false; if (IdentifierNamingCheck::HungarianPrefixType::HPT_Off != Style.HPType) { - std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption); + const std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption); if (!HNPrefix.empty()) { if (!Name.consume_front(HNPrefix)) return false; @@ -914,7 +916,7 @@ std::string IdentifierNamingCheck::fixupWithCase( const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, IdentifierNamingCheck::CaseType Case) const { - static llvm::Regex Splitter( + static const llvm::Regex Splitter( "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)"); SmallVector Substrs; @@ -1070,7 +1072,7 @@ bool IdentifierNamingCheck::isParamInMainLikeFunction( return false; if (!IsIntType(FDecl->parameters()[0]->getType())) return false; - MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType()); + const MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType()); if (Type == None) return false; if (FDecl->getNumParams() == 3 && @@ -1078,13 +1080,14 @@ bool IdentifierNamingCheck::isParamInMainLikeFunction( return false; if (Type == Main) { - static llvm::Regex Matcher( + static const llvm::Regex Matcher( "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))"); assert(Matcher.isValid() && "Invalid Matcher for main like functions."); return Matcher.match(FDecl->getName()); } - static llvm::Regex Matcher("(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]" - "ain([_A-Z]|$))|(_wmain(_|$))"); + static const llvm::Regex Matcher( + "(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]" + "ain([_A-Z]|$))|(_wmain(_|$))"); assert(Matcher.isValid() && "Invalid Matcher for wmain like functions."); return Matcher.match(FDecl->getName()); } @@ -1212,7 +1215,7 @@ StyleKind IdentifierNamingCheck::findStyleKind( if (const auto *Decl = dyn_cast(D)) { if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions)) return SK_Invalid; - QualType Type = Decl->getType(); + const QualType Type = Decl->getType(); if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable]) return SK_ConstexprVariable; @@ -1381,7 +1384,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl, if (Decl->isImplicit()) return std::nullopt; - SourceLocation Loc = Decl->getLocation(); + const SourceLocation Loc = Decl->getLocation(); const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc)); if (!FileStyle.isActive()) return std::nullopt; @@ -1398,7 +1401,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl, std::optional IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const { - SourceLocation Loc = MacroNameTok.getLocation(); + const SourceLocation Loc = MacroNameTok.getLocation(); const FileStyle &Style = getStyleForFile(SM.getFilename(Loc)); if (!Style.isActive()) return std::nullopt; @@ -1431,13 +1434,13 @@ IdentifierNamingCheck::getStyleForFile(StringRef FileName) const { if (!GetConfigPerFile) return *MainFileStyle; - StringRef RealFileName = getRealFileName(FileName); - StringRef Parent = llvm::sys::path::parent_path(RealFileName); + const StringRef RealFileName = getRealFileName(FileName); + const StringRef Parent = llvm::sys::path::parent_path(RealFileName); auto Iter = NamingStylesCache.find(Parent); if (Iter != NamingStylesCache.end()) return Iter->getValue(); - llvm::StringRef CheckName = getID(); + const llvm::StringRef CheckName = getID(); ClangTidyOptions Options = Context->getOptionsForFile(RealFileName); if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) { auto It = NamingStylesCache.try_emplace( @@ -1459,7 +1462,7 @@ StyleKind IdentifierNamingCheck::findStyleKindForAnonField( utils::findOutermostIndirectFieldDeclForField(AnonField); assert(IFD && "Found an anonymous record field without an IndirectFieldDecl"); - QualType Type = AnonField->getType(); + const QualType Type = AnonField->getType(); if (const auto *F = dyn_cast(IFD->chain().front())) { return findStyleKindForField(F, Type, NamingStyles); diff --git a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp index 4cf8574e56c5e..77150fd3ac9b4 100644 --- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp @@ -22,8 +22,8 @@ namespace clang::tidy::readability { namespace { AST_MATCHER(Stmt, isMacroExpansion) { - SourceManager &SM = Finder->getASTContext().getSourceManager(); - SourceLocation Loc = Node.getBeginLoc(); + const SourceManager &SM = Finder->getASTContext().getSourceManager(); + const SourceLocation Loc = Node.getBeginLoc(); return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); } @@ -32,9 +32,9 @@ AST_MATCHER(Stmt, isC23) { return Finder->getASTContext().getLangOpts().C23; } // Preserve same name as AST_MATCHER(isNULLMacroExpansion) // NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) { - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); const LangOptions &LO = Context.getLangOpts(); - SourceLocation Loc = Statement->getBeginLoc(); + const SourceLocation Loc = Statement->getBeginLoc(); return SM.isMacroBodyExpansion(Loc) && Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL"; } @@ -77,11 +77,11 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, bool UseUpperCaseLiteralSuffix) { // In case of expressions like (! integer), we should remove the redundant not // operator and use inverted comparison (integer == 0). - bool InvertComparison = + const bool InvertComparison = Parent != nullptr && isUnaryLogicalNotOperator(Parent); if (InvertComparison) { - SourceLocation ParentStartLoc = Parent->getBeginLoc(); - SourceLocation ParentEndLoc = + const SourceLocation ParentStartLoc = Parent->getBeginLoc(); + const SourceLocation ParentEndLoc = cast(Parent)->getSubExpr()->getBeginLoc(); Diag << FixItHint::CreateRemoval( CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc)); @@ -91,9 +91,9 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, const Expr *SubExpr = Cast->getSubExpr(); - bool NeedInnerParens = + const bool NeedInnerParens = utils::fixit::areParensNeededForStatement(*SubExpr->IgnoreImpCasts()); - bool NeedOuterParens = + const bool NeedOuterParens = Parent != nullptr && utils::fixit::areParensNeededForStatement(*Parent); std::string StartLocInsertion; @@ -133,7 +133,7 @@ static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, EndLocInsertion += ")"; } - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts()); Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion); } @@ -167,8 +167,8 @@ static StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, } static bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { - SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); - StringRef SpaceBeforeStmtStr = Lexer::getSourceText( + const SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); + const StringRef SpaceBeforeStmtStr = Lexer::getSourceText( CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(), Context.getLangOpts(), nullptr); if (SpaceBeforeStmtStr.empty()) @@ -198,7 +198,7 @@ static void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, .str()); if (NeedParens) { - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts()); @@ -234,7 +234,7 @@ static bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, std::queue Q; Q.push(Cast); - TraversalKindScope RAII(Context, TK_AsIs); + const TraversalKindScope RAII(Context, TK_AsIs); while (!Q.empty()) { for (const auto &N : Context.getParents(*Q.front())) { @@ -396,7 +396,7 @@ void ImplicitBoolConversionCheck::handleCastToBool(const ImplicitCastExpr *Cast, auto Diag = diag(Cast->getBeginLoc(), "implicit conversion %0 -> 'bool'") << Cast->getSubExpr()->getType(); - StringRef EquivalentLiteral = + const StringRef EquivalentLiteral = getEquivalentBoolLiteralForExpr(Cast->getSubExpr(), Context); if (!EquivalentLiteral.empty()) { Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral); @@ -409,7 +409,7 @@ void ImplicitBoolConversionCheck::handleCastToBool(const ImplicitCastExpr *Cast, void ImplicitBoolConversionCheck::handleCastFromBool( const ImplicitCastExpr *Cast, const ImplicitCastExpr *NextImplicitCast, ASTContext &Context) { - QualType DestType = + const QualType DestType = NextImplicitCast ? NextImplicitCast->getType() : Cast->getType(); auto Diag = diag(Cast->getBeginLoc(), "implicit conversion 'bool' -> %0") << DestType; diff --git a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp index 93580a7e67c4a..c49684112a5d4 100644 --- a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp @@ -113,12 +113,12 @@ findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, // FIXME: Provide a way to extract commented out parameter name from comment // next to it. if (!nameMatch(SourceParamName, OtherParamName, Strict)) { - SourceRange OtherParamNameRange = + const SourceRange OtherParamNameRange = DeclarationNameInfo((*OtherParamIt)->getDeclName(), (*OtherParamIt)->getLocation()) .getSourceRange(); - bool GenerateFixItHint = checkIfFixItHintIsApplicable( + const bool GenerateFixItHint = checkIfFixItHintIsApplicable( ParameterSourceDeclaration, *SourceParamIt, OriginalDeclaration); DifferingParams.emplace_back(SourceParamName, OtherParamName, @@ -137,11 +137,11 @@ findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, const FunctionDecl *ParameterSourceDeclaration, SourceManager &SM, bool Strict) { InconsistentDeclarationsContainer InconsistentDeclarations; - SourceLocation ParameterSourceLocation = + const SourceLocation ParameterSourceLocation = ParameterSourceDeclaration->getLocation(); for (const FunctionDecl *OtherDeclaration : OriginalDeclaration->redecls()) { - SourceLocation OtherLocation = OtherDeclaration->getLocation(); + const SourceLocation OtherLocation = OtherDeclaration->getLocation(); if (OtherLocation != ParameterSourceLocation) { // Skip self. DifferingParamsContainer DifferingParams = findDifferingParamsInDeclaration(ParameterSourceDeclaration, @@ -305,7 +305,7 @@ void InconsistentDeclarationParameterNameCheck::check( const FunctionDecl *ParameterSourceDeclaration = getParameterSourceDeclaration(OriginalDeclaration); - InconsistentDeclarationsContainer InconsistentDeclarations = + const InconsistentDeclarationsContainer InconsistentDeclarations = findInconsistentDeclarations(OriginalDeclaration, ParameterSourceDeclaration, *Result.SourceManager, Strict); @@ -315,7 +315,7 @@ void InconsistentDeclarationParameterNameCheck::check( return; } - SourceLocation StartLoc = OriginalDeclaration->getBeginLoc(); + const SourceLocation StartLoc = OriginalDeclaration->getBeginLoc(); if (StartLoc.isMacroID() && IgnoreMacros) { markRedeclarationsAsVisited(OriginalDeclaration); return; diff --git a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp index bc5edecb8a65b..fa5a0b7cd3647 100644 --- a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp @@ -107,7 +107,7 @@ static bool typeIsMemberPointer(const Type *T) { static std::optional> declRanges(const DeclStmt *DS, const SourceManager &SM, const LangOptions &LangOpts) { - std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end()); + const std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end()); if (DeclCount < 2) return std::nullopt; @@ -157,7 +157,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, if (Start.isInvalid() || Start.isMacroID()) break; - Token T = getPreviousToken(Start, SM, LangOpts); + const Token T = getPreviousToken(Start, SM, LangOpts); if (T.is(tok::l_paren)) { Start = findPreviousTokenStart(Start, SM, LangOpts); continue; @@ -165,7 +165,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, break; } - SourceRange DeclRange(DS->getBeginLoc(), Start); + const SourceRange DeclRange(DS->getBeginLoc(), Start); if (DeclRange.isInvalid() || isMacroID(DeclRange)) return std::nullopt; @@ -183,13 +183,13 @@ declRanges(const DeclStmt *DS, const SourceManager &SM, if (typeIsMemberPointer(CurrentDecl->getType().IgnoreParens().getTypePtr())) return std::nullopt; - SourceLocation DeclEnd = + const SourceLocation DeclEnd = CurrentDecl->hasInit() ? findNextTerminator(CurrentDecl->getInit()->getEndLoc(), SM, LangOpts) : findNextTerminator(CurrentDecl->getEndLoc(), SM, LangOpts); - SourceRange VarNameRange(DeclBegin, DeclEnd); + const SourceRange VarNameRange(DeclBegin, DeclEnd); if (VarNameRange.isInvalid() || isMacroID(VarNameRange)) return std::nullopt; @@ -206,7 +206,7 @@ collectSourceRanges(llvm::ArrayRef Ranges, const SourceManager &SM, Snippets.reserve(Ranges.size()); for (const auto &Range : Ranges) { - CharSourceRange CharRange = Lexer::getAsCharRange( + const CharSourceRange CharRange = Lexer::getAsCharRange( CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()), SM, LangOpts); @@ -214,7 +214,7 @@ collectSourceRanges(llvm::ArrayRef Ranges, const SourceManager &SM, return std::nullopt; bool InvalidText = false; - StringRef Snippet = + const StringRef Snippet = Lexer::getSourceText(CharRange, SM, LangOpts, &InvalidText); if (InvalidText) @@ -262,7 +262,7 @@ void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) { return; std::vector NewDecls = createIsolatedDecls(*PotentialSnippets); - std::string Replacement = llvm::join( + const std::string Replacement = llvm::join( NewDecls, (Twine("\n") + Lexer::getIndentationForLine(WholeDecl->getBeginLoc(), *Result.SourceManager)) diff --git a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp index a38f7bc029e8b..01abf513ce9b9 100644 --- a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp @@ -145,7 +145,7 @@ void MagicNumbersCheck::registerMatchers(MatchFinder *Finder) { void MagicNumbersCheck::check(const MatchFinder::MatchResult &Result) { - TraversalKindScope RAII(*Result.Context, TK_AsIs); + const TraversalKindScope RAII(*Result.Context, TK_AsIs); checkBoundMatch(Result, "integer"); checkBoundMatch(Result, "float"); @@ -248,7 +248,7 @@ bool MagicNumbersCheck::isBitFieldWidth( bool MagicNumbersCheck::isUserDefinedLiteral( const clang::ast_matchers::MatchFinder::MatchResult &Result, const clang::Expr &Literal) const { - DynTypedNodeList Parents = Result.Context->getParents(Literal); + const DynTypedNodeList Parents = Result.Context->getParents(Literal); if (Parents.empty()) return false; return Parents[0].get() != nullptr; diff --git a/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp b/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp index bea68884e3bda..ddc92ef312446 100644 --- a/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp @@ -59,7 +59,7 @@ class FindUsageOfThis : public RecursiveASTVisitor { UsageKind Usage = Unused; template const T *getParent(const Expr *E) { - DynTypedNodeList Parents = Ctxt.getParents(*E); + const DynTypedNodeList Parents = Ctxt.getParents(*E); if (Parents.size() != 1) return nullptr; @@ -241,7 +241,7 @@ void MakeMemberFunctionConstCheck::registerMatchers(MatchFinder *Finder) { } static SourceLocation getConstInsertionPoint(const CXXMethodDecl *M) { - TypeSourceInfo *TSI = M->getTypeSourceInfo(); + const TypeSourceInfo *TSI = M->getTypeSourceInfo(); if (!TSI) return {}; diff --git a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp index e15b2ecd8f5c0..69bc554778379 100644 --- a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp @@ -56,8 +56,8 @@ static void addParentheses(const BinaryOperator *BinOp, if (!BinOp) return; - int Precedence1 = getPrecedence(BinOp); - int Precedence2 = getPrecedence(ParentBinOp); + const int Precedence1 = getPrecedence(BinOp); + const int Precedence2 = getPrecedence(ParentBinOp); if (ParentBinOp != nullptr && Precedence1 != Precedence2 && Precedence1 > 0 && Precedence2 > 0) { diff --git a/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp b/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp index 0765d8d82ee04..450961c8b4fee 100644 --- a/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp @@ -21,7 +21,7 @@ static const IfStmt *getPrecedingIf(const SourceManager &SM, if (Parents.size() != 1) return nullptr; if (const auto *PrecedingIf = Parents[0].get()) { - SourceLocation PreviousElseLoc = PrecedingIf->getElseLoc(); + const SourceLocation PreviousElseLoc = PrecedingIf->getElseLoc(); if (SM.getExpansionLineNumber(PreviousElseLoc) == SM.getExpansionLineNumber(If->getIfLoc())) return PrecedingIf; @@ -33,7 +33,7 @@ void MisleadingIndentationCheck::danglingElseCheck(const SourceManager &SM, ASTContext *Context, const IfStmt *If) { SourceLocation IfLoc = If->getIfLoc(); - SourceLocation ElseLoc = If->getElseLoc(); + const SourceLocation ElseLoc = If->getElseLoc(); if (IfLoc.isMacroID() || ElseLoc.isMacroID()) return; @@ -89,8 +89,8 @@ void MisleadingIndentationCheck::missingBracesCheck( if (isa(Inner)) continue; - SourceLocation InnerLoc = Inner->getBeginLoc(); - SourceLocation OuterLoc = CurrentStmt->getBeginLoc(); + const SourceLocation InnerLoc = Inner->getBeginLoc(); + const SourceLocation OuterLoc = CurrentStmt->getBeginLoc(); if (InnerLoc.isInvalid() || InnerLoc.isMacroID() || OuterLoc.isInvalid() || OuterLoc.isMacroID()) @@ -101,7 +101,7 @@ void MisleadingIndentationCheck::missingBracesCheck( continue; const Stmt *NextStmt = CStmt->body_begin()[I + 1]; - SourceLocation NextLoc = NextStmt->getBeginLoc(); + const SourceLocation NextLoc = NextStmt->getBeginLoc(); if (NextLoc.isInvalid() || NextLoc.isMacroID()) continue; From 385dbc12c4597a158e1c7906e39a4832c4de97cc Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 19:05:36 +0300 Subject: [PATCH 16/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (12/N) (#167129) --- .../bugprone/ArgumentCommentCheck.cpp | 43 ++++---- .../bugprone/AssertSideEffectCheck.cpp | 6 +- .../bugprone/AssignmentInIfConditionCheck.cpp | 2 +- .../bugprone/BadSignalToKillThreadCheck.cpp | 2 +- .../clang-tidy/bugprone/BranchCloneCheck.cpp | 8 +- .../bugprone/CopyConstructorInitCheck.cpp | 4 +- .../CrtpConstructorAccessibilityCheck.cpp | 7 +- ...faultOperatorNewOnOveralignedTypeCheck.cpp | 14 +-- .../DerivedMethodShadowingBaseMethodCheck.cpp | 2 +- .../DynamicStaticInitializersCheck.cpp | 2 +- .../EasilySwappableParametersCheck.cpp | 103 +++++++++--------- .../clang-tidy/bugprone/EmptyCatchCheck.cpp | 4 +- .../ForwardDeclarationNamespaceCheck.cpp | 2 +- .../ForwardingReferenceOverloadCheck.cpp | 9 +- ...citWideningOfMultiplicationResultCheck.cpp | 25 +++-- .../bugprone/InaccurateEraseCheck.cpp | 2 +- .../bugprone/IncorrectEnableIfCheck.cpp | 4 +- .../clang-tidy/bugprone/InfiniteLoopCheck.cpp | 6 +- .../InvalidEnumDefaultInitializationCheck.cpp | 4 +- .../bugprone/LambdaFunctionNameCheck.cpp | 2 +- .../MacroRepeatedSideEffectsCheck.cpp | 2 +- 21 files changed, 132 insertions(+), 121 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp index c0a778a027377..ed30d01e645d1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp @@ -81,14 +81,16 @@ static std::vector> getCommentsInRange(ASTContext *Ctx, CharSourceRange Range) { std::vector> Comments; auto &SM = Ctx->getSourceManager(); - std::pair BeginLoc = SM.getDecomposedLoc(Range.getBegin()), - EndLoc = SM.getDecomposedLoc(Range.getEnd()); + const std::pair BeginLoc = + SM.getDecomposedLoc(Range.getBegin()), + EndLoc = + SM.getDecomposedLoc(Range.getEnd()); if (BeginLoc.first != EndLoc.first) return Comments; bool Invalid = false; - StringRef Buffer = SM.getBufferData(BeginLoc.first, &Invalid); + const StringRef Buffer = SM.getBufferData(BeginLoc.first, &Invalid); if (Invalid) return Comments; @@ -106,7 +108,7 @@ getCommentsInRange(ASTContext *Ctx, CharSourceRange Range) { break; if (Tok.is(tok::comment)) { - std::pair CommentLoc = + const std::pair CommentLoc = SM.getDecomposedLoc(Tok.getLocation()); assert(CommentLoc.first == BeginLoc.first); Comments.emplace_back( @@ -125,7 +127,7 @@ static std::vector> getCommentsBeforeLoc(ASTContext *Ctx, SourceLocation Loc) { std::vector> Comments; while (Loc.isValid()) { - clang::Token Tok = utils::lexer::getPreviousToken( + const clang::Token Tok = utils::lexer::getPreviousToken( Loc, Ctx->getSourceManager(), Ctx->getLangOpts(), /*SkipComments=*/false); if (Tok.isNot(tok::comment)) @@ -142,11 +144,11 @@ getCommentsBeforeLoc(ASTContext *Ctx, SourceLocation Loc) { static bool isLikelyTypo(llvm::ArrayRef Params, StringRef ArgName, unsigned ArgIndex) { - std::string ArgNameLowerStr = ArgName.lower(); - StringRef ArgNameLower = ArgNameLowerStr; + const std::string ArgNameLowerStr = ArgName.lower(); + const StringRef ArgNameLower = ArgNameLowerStr; // The threshold is arbitrary. - unsigned UpperBound = ((ArgName.size() + 2) / 3) + 1; - unsigned ThisED = ArgNameLower.edit_distance( + const unsigned UpperBound = ((ArgName.size() + 2) / 3) + 1; + const unsigned ThisED = ArgNameLower.edit_distance( Params[ArgIndex]->getIdentifier()->getName().lower(), /*AllowReplacements=*/true, UpperBound); if (ThisED >= UpperBound) @@ -155,7 +157,7 @@ static bool isLikelyTypo(llvm::ArrayRef Params, for (unsigned I = 0, E = Params.size(); I != E; ++I) { if (I == ArgIndex) continue; - IdentifierInfo *II = Params[I]->getIdentifier(); + const IdentifierInfo *II = Params[I]->getIdentifier(); if (!II) continue; @@ -163,9 +165,9 @@ static bool isLikelyTypo(llvm::ArrayRef Params, // Other parameters must be an edit distance at least Threshold more away // from this parameter. This gives us greater confidence that this is a // typo of this parameter and not one with a similar name. - unsigned OtherED = ArgNameLower.edit_distance(II->getName().lower(), - /*AllowReplacements=*/true, - ThisED + Threshold); + const unsigned OtherED = ArgNameLower.edit_distance( + II->getName().lower(), + /*AllowReplacements=*/true, ThisED + Threshold); if (OtherED < ThisED + Threshold) return false; } @@ -267,7 +269,8 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, return; Callee = Callee->getFirstDecl(); - unsigned NumArgs = std::min(Args.size(), Callee->getNumParams()); + const unsigned NumArgs = + std::min(Args.size(), Callee->getNumParams()); if ((NumArgs == 0) || (IgnoreSingleArgument && NumArgs == 1)) return; @@ -279,7 +282,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, for (unsigned I = 0; I < NumArgs; ++I) { const ParmVarDecl *PVD = Callee->getParamDecl(I); - IdentifierInfo *II = PVD->getIdentifier(); + const IdentifierInfo *II = PVD->getIdentifier(); if (!II) continue; if (FunctionDecl *Template = Callee->getTemplateInstantiationPattern()) { @@ -293,7 +296,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, } } - CharSourceRange BeforeArgument = + const CharSourceRange BeforeArgument = MakeFileCharRange(ArgBeginLoc, Args[I]->getBeginLoc()); ArgBeginLoc = Args[I]->getEndLoc(); @@ -302,7 +305,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, Comments = getCommentsInRange(Ctx, BeforeArgument); } else { // Fall back to parsing back from the start of the argument. - CharSourceRange ArgsRange = + const CharSourceRange ArgsRange = MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getEndLoc()); Comments = getCommentsBeforeLoc(Ctx, ArgsRange.getBegin()); } @@ -312,7 +315,7 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, if (IdentRE.match(Comment.second, &Matches) && !sameName(Matches[2], II->getName(), StrictMode)) { { - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(Comment.first, "argument name '%0' in comment does not " "match parameter name %1") << Matches[2] << II; @@ -332,9 +335,9 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, // If the argument comments are missing for literals add them. if (Comments.empty() && shouldAddComment(Args[I])) { - std::string ArgComment = + const std::string ArgComment = (llvm::Twine("/*") + II->getName() + "=*/").str(); - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(Args[I]->getBeginLoc(), "argument comment missing for literal argument %0") << II diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp index 170050247014a..a29aa552b0953 100644 --- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp @@ -29,7 +29,7 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, const Expr *E = &Node; if (const auto *Op = dyn_cast(E)) { - UnaryOperator::Opcode OC = Op->getOpcode(); + const UnaryOperator::Opcode OC = Op->getOpcode(); return OC == UO_PostInc || OC == UO_PostDec || OC == UO_PreInc || OC == UO_PreDec; } @@ -44,7 +44,7 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, if (MethodDecl->isConst()) return false; - OverloadedOperatorKind OpKind = OpCallExpr->getOperator(); + const OverloadedOperatorKind OpKind = OpCallExpr->getOperator(); return OpKind == OO_Equal || OpKind == OO_PlusEqual || OpKind == OO_MinusEqual || OpKind == OO_StarEqual || OpKind == OO_SlashEqual || OpKind == OO_AmpEqual || @@ -130,7 +130,7 @@ void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) { StringRef AssertMacroName; while (Loc.isValid() && Loc.isMacroID()) { - StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts); + const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts); Loc = SM.getImmediateMacroCallerLoc(Loc); // Check if this macro is an assert. diff --git a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp index 2c8856298e7be..d5d8a29d96969 100644 --- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp @@ -66,7 +66,7 @@ void AssignmentInIfConditionCheck::check( } void AssignmentInIfConditionCheck::report(const Expr *AssignmentExpr) { - SourceLocation OpLoc = + const SourceLocation OpLoc = isa(AssignmentExpr) ? cast(AssignmentExpr)->getOperatorLoc() : cast(AssignmentExpr)->getOperatorLoc(); diff --git a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp index e1d0538ab1644..3e1188d5e2463 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp @@ -40,7 +40,7 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) { const Token &T = MI->tokens().back(); if (!T.isLiteral() || !T.getLiteralData()) return std::nullopt; - StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength()); + const StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength()); llvm::APInt IntValue; constexpr unsigned AutoSenseRadix = 0; diff --git a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp index 07bb08166a006..8e0f0c55bdf94 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp @@ -281,8 +281,8 @@ static bool isIdenticalStmt(const ASTContext &Ctx, const Stmt *Stmt1, const auto *IntLit1 = cast(Stmt1); const auto *IntLit2 = cast(Stmt2); - llvm::APInt I1 = IntLit1->getValue(); - llvm::APInt I2 = IntLit2->getValue(); + const llvm::APInt I1 = IntLit1->getValue(); + const llvm::APInt I2 = IntLit2->getValue(); if (I1.getBitWidth() != I2.getBitWidth()) return false; return I1 == I2; @@ -352,7 +352,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) { } } - size_t N = Branches.size(); + const size_t N = Branches.size(); llvm::BitVector KnownAsClone(N); for (size_t I = 0; I + 1 < N; I++) { @@ -375,7 +375,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) { // We report the first occurrence only when we find the second one. diag(Branches[I]->getBeginLoc(), "repeated branch body in conditional chain"); - SourceLocation End = + const SourceLocation End = Lexer::getLocForEndOfToken(Branches[I]->getEndLoc(), 0, *Result.SourceManager, getLangOpts()); if (End.isValid()) { diff --git a/clang-tools-extra/clang-tidy/bugprone/CopyConstructorInitCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/CopyConstructorInitCheck.cpp index 76bcbbbcdf680..ccbc86ae74cc6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CopyConstructorInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/CopyConstructorInitCheck.cpp @@ -31,7 +31,7 @@ void CopyConstructorInitCheck::registerMatchers(MatchFinder *Finder) { void CopyConstructorInitCheck::check(const MatchFinder::MatchResult &Result) { const auto *Ctor = Result.Nodes.getNodeAs("ctor"); - std::string ParamName = Ctor->getParamDecl(0)->getNameAsString(); + const std::string ParamName = Ctor->getParamDecl(0)->getNameAsString(); // We want only one warning (and FixIt) for each ctor. std::string FixItInitList; @@ -40,7 +40,7 @@ void CopyConstructorInitCheck::check(const MatchFinder::MatchResult &Result) { bool HasWrittenInitializer = false; SmallVector SafeFixIts; for (const auto *Init : Ctor->inits()) { - bool CtorInitIsWritten = Init->isWritten(); + const bool CtorInitIsWritten = Init->isWritten(); HasWrittenInitializer = HasWrittenInitializer || CtorInitIsWritten; if (!Init->isBaseInitializer()) continue; diff --git a/clang-tools-extra/clang-tidy/bugprone/CrtpConstructorAccessibilityCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/CrtpConstructorAccessibilityCheck.cpp index 60f7be8996933..5ef72eac763e7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CrtpConstructorAccessibilityCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/CrtpConstructorAccessibilityCheck.cpp @@ -116,9 +116,10 @@ void CrtpConstructorAccessibilityCheck::check( assert(DerivedTemplateParameter && "No template parameter corresponds to the derived class of the CRTP."); - bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration, - DerivedTemplateParameter) && - !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord); + const bool NeedsFriend = + !isDerivedParameterBefriended(CRTPDeclaration, + DerivedTemplateParameter) && + !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord); const FixItHint HintFriend = FixItHint::CreateInsertion( CRTPDeclaration->getBraceRange().getEnd(), diff --git a/clang-tools-extra/clang-tidy/bugprone/DefaultOperatorNewOnOveralignedTypeCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/DefaultOperatorNewOnOveralignedTypeCheck.cpp index 0aafdfd202390..cb4f69ae96115 100644 --- a/clang-tools-extra/clang-tidy/bugprone/DefaultOperatorNewOnOveralignedTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/DefaultOperatorNewOnOveralignedTypeCheck.cpp @@ -26,7 +26,7 @@ void DefaultOperatorNewOnOveralignedTypeCheck::check( // Get the found 'new' expression. const auto *NewExpr = Result.Nodes.getNodeAs("new"); - QualType T = NewExpr->getAllocatedType(); + const QualType T = NewExpr->getAllocatedType(); // Dependent types do not have fixed alignment. if (T->isDependentType()) return; @@ -35,25 +35,25 @@ void DefaultOperatorNewOnOveralignedTypeCheck::check( if (!D || !D->isCompleteDefinition()) return; - ASTContext &Context = D->getASTContext(); + const ASTContext &Context = D->getASTContext(); // Check if no alignment was specified for the type. if (!Context.isAlignmentRequired(T)) return; // The user-specified alignment (in bits). - unsigned SpecifiedAlignment = D->getMaxAlignment(); + const unsigned SpecifiedAlignment = D->getMaxAlignment(); // Double-check if no alignment was specified. if (!SpecifiedAlignment) return; // The alignment used by default 'operator new' (in bits). - unsigned DefaultNewAlignment = Context.getTargetInfo().getNewAlign(); + const unsigned DefaultNewAlignment = Context.getTargetInfo().getNewAlign(); - bool OverAligned = SpecifiedAlignment > DefaultNewAlignment; - bool HasDefaultOperatorNew = + const bool OverAligned = SpecifiedAlignment > DefaultNewAlignment; + const bool HasDefaultOperatorNew = !NewExpr->getOperatorNew() || NewExpr->getOperatorNew()->isImplicit(); - unsigned CharWidth = Context.getTargetInfo().getCharWidth(); + const unsigned CharWidth = Context.getTargetInfo().getCharWidth(); if (HasDefaultOperatorNew && OverAligned) diag(NewExpr->getBeginLoc(), "allocation function returns a pointer with alignment %0 but the " diff --git a/clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp index 743e6cd27509b..7c5867619cf4e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp @@ -65,7 +65,7 @@ AST_MATCHER(CXXMethodDecl, nameCollidesWithMethodInBase) { for (const auto &BaseMethod : CurrentRecord->methods()) { if (namesCollide(*BaseMethod, Node)) { - ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder); + const ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder); Builder->setBinding("base_method", clang::DynTypedNode::create(*BaseMethod)); return true; diff --git a/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp index 4d0428ec18598..48de7fbe7fad6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp @@ -43,7 +43,7 @@ void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) { void DynamicStaticInitializersCheck::check( const MatchFinder::MatchResult &Result) { const auto *Var = Result.Nodes.getNodeAs("var"); - SourceLocation Loc = Var->getLocation(); + const SourceLocation Loc = Var->getLocation(); if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile( Loc, *Result.SourceManager, HeaderFileExtensions)) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp index b4ee35154f5f0..a07a68c8a3e65 100644 --- a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp @@ -417,7 +417,7 @@ struct MixData { void sanitize() { assert(Flags != MixFlags::Invalid && "sanitize() called on invalid bitvec"); - MixFlags CanonicalAndWorkaround = + const MixFlags CanonicalAndWorkaround = MixFlags::Canonical | MixFlags::WorkaroundDisableCanonicalEquivalence; if ((Flags & CanonicalAndWorkaround) == CanonicalAndWorkaround) { // A workaround for too eagerly equivalent canonical types was requested, @@ -483,7 +483,7 @@ struct MixData { if (CommonType.isNull()) return *this; - QualType NewCommonType = Func(CommonType); + const QualType NewCommonType = Func(CommonType); if (CreatedFromOneWayConversion) { MixData M{Flags, Conversion}; @@ -761,7 +761,7 @@ calculateMixability(const TheCheck &Check, QualType LType, QualType RType, return {MixFlags::None}; } - MixData UnqualifiedMixability = + const MixData UnqualifiedMixability = calculateMixability(Check, LType.getLocalUnqualifiedType(), RType.getLocalUnqualifiedType(), Ctx, ImplicitMode) .withCommonTypeTransformed([&AdditionalQuals, &Ctx](QualType QT) { @@ -813,7 +813,7 @@ calculateMixability(const TheCheck &Check, QualType LType, QualType RType, if (ImplicitMode > ImplicitConversionModellingMode::None) { LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. Start implicit...\n"); - MixData MixLTR = + const MixData MixLTR = approximateImplicitConversion(Check, LType, RType, Ctx, ImplicitMode); LLVM_DEBUG( if (hasFlag(MixLTR.Flags, MixFlags::ImplicitConversion)) llvm::dbgs() @@ -833,7 +833,7 @@ calculateMixability(const TheCheck &Check, QualType LType, QualType RType, // Otherwise if the invoker requested a full modelling, do the other // direction as well. - MixData MixRTL = + const MixData MixRTL = approximateImplicitConversion(Check, RType, LType, Ctx, ImplicitMode); LLVM_DEBUG( if (hasFlag(MixRTL.Flags, MixFlags::ImplicitConversion)) llvm::dbgs() @@ -868,7 +868,7 @@ calculateMixability(const TheCheck &Check, QualType LType, QualType RType, // If none of the previous logic found a match, try if Clang otherwise // believes the types to be the same. - QualType LCanonical = LType.getCanonicalType(); + const QualType LCanonical = LType.getCanonicalType(); if (LCanonical == RType.getCanonicalType()) { LLVM_DEBUG(llvm::dbgs() << "<<< calculateMixability. Same CanonicalType.\n"); @@ -983,9 +983,9 @@ approximateStandardConversionSequence(const TheCheck &Check, QualType From, // Numeric promotions and conversions. const auto *FromBuiltin = WorkType->getAs(); const auto *ToBuiltin = To->getAs(); - bool FromNumeric = FromBuiltin && (FromBuiltin->isIntegerType() || - FromBuiltin->isFloatingType()); - bool ToNumeric = + const bool FromNumeric = FromBuiltin && (FromBuiltin->isIntegerType() || + FromBuiltin->isFloatingType()); + const bool ToNumeric = ToBuiltin && (ToBuiltin->isIntegerType() || ToBuiltin->isFloatingType()); if (FromNumeric && ToNumeric) { // If both are integral types, the numeric conversion is performed. @@ -1150,9 +1150,9 @@ class UserDefinedConversionSelector { continue; } - bool BestConversionHasImplicit = + const bool BestConversionHasImplicit = hasFlag(BestConversion->Flags, MixFlags::ImplicitConversion); - bool ThisConversionHasImplicit = + const bool ThisConversionHasImplicit = hasFlag(Prepared.Flags, MixFlags::ImplicitConversion); if (!BestConversionHasImplicit && ThisConversionHasImplicit) // This is a worse conversion, because a better one was found earlier. @@ -1221,7 +1221,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD, if (std::optional SelectedConversion = ConversionSet()) { - CanQualType RecordType = RD->getASTContext().getCanonicalTagType(RD); + const CanQualType RecordType = RD->getASTContext().getCanonicalTagType(RD); ConversionSequence Result{RecordType, ToType}; // The conversion from the operator call's return type to ToType was @@ -1272,7 +1272,7 @@ tryConvertingConstructors(const TheCheck &Check, QualType FromType, if (std::optional SelectedConversion = ConversionSet()) { - CanQualType RecordType = RD->getASTContext().getCanonicalTagType(RD); + const CanQualType RecordType = RD->getASTContext().getCanonicalTagType(RD); ConversionSequence Result{FromType, RecordType}; Result.AfterFirstStandard = SelectedConversion->Seq.AfterFirstStandard; @@ -1385,7 +1385,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType, LLVM_DEBUG( llvm::dbgs() << "--- approximateImplicitConversion. Try to find post-conversion.\n"); - MixData SecondStdConv = approximateImplicitConversion( + const MixData SecondStdConv = approximateImplicitConversion( Check, WorkType, RType, Ctx, ImplicitConversionModellingMode::OneWaySingleStandardOnly); if (SecondStdConv.indicatesMixability()) { @@ -1414,7 +1414,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType, static MixableParameterRange modelMixingRange( const TheCheck &Check, const FunctionDecl *FD, std::size_t StartIndex, const filter::SimilarlyUsedParameterPairSuppressor &UsageBasedSuppressor) { - std::size_t NumParams = FD->getNumParams(); + const std::size_t NumParams = FD->getNumParams(); assert(StartIndex < NumParams && "out of bounds for start"); const ASTContext &Ctx = FD->getASTContext(); @@ -1424,7 +1424,7 @@ static MixableParameterRange modelMixingRange( for (std::size_t I = StartIndex + 1; I < NumParams; ++I) { const ParmVarDecl *Ith = FD->getParamDecl(I); - StringRef ParamName = Ith->getName(); + const StringRef ParamName = Ith->getName(); LLVM_DEBUG(llvm::dbgs() << "Check param #" << I << " '" << ParamName << "'...\n"); if (filter::isIgnoredParameter(Check, Ith)) { @@ -1432,7 +1432,7 @@ static MixableParameterRange modelMixingRange( break; } - StringRef PrevParamName = FD->getParamDecl(I - 1)->getName(); + const StringRef PrevParamName = FD->getParamDecl(I - 1)->getName(); if (!ParamName.empty() && !PrevParamName.empty() && filter::prefixSuffixCoverUnderThreshold( Check.NamePrefixSuffixSilenceDissimilarityThreshold, PrevParamName, @@ -1518,18 +1518,18 @@ static bool isIgnoredParameter(const TheCheck &Check, const ParmVarDecl *Node) { if (!Node->getIdentifier()) return llvm::is_contained(Check.IgnoredParameterNames, "\"\""); - StringRef NodeName = Node->getName(); + const StringRef NodeName = Node->getName(); if (llvm::is_contained(Check.IgnoredParameterNames, NodeName)) { LLVM_DEBUG(llvm::dbgs() << "\tName ignored.\n"); return true; } - StringRef NodeTypeName = [Node] { + const StringRef NodeTypeName = [Node] { const ASTContext &Ctx = Node->getASTContext(); const SourceManager &SM = Ctx.getSourceManager(); SourceLocation B = Node->getTypeSpecStartLoc(); SourceLocation E = Node->getTypeSpecEndLoc(); - LangOptions LO; + const LangOptions LO; LLVM_DEBUG(llvm::dbgs() << "\tType name code is '" << Lexer::getSourceText( @@ -1633,7 +1633,7 @@ class AppearsInSameExpr : public RecursiveASTVisitor { RootSetInCurrentStackFrame = true; } - bool Ret = Base::TraverseStmt(S); + const bool Ret = Base::TraverseStmt(S); if (RootSetInCurrentStackFrame) CurrentExprOnlyTreeRoot = nullptr; @@ -1684,7 +1684,7 @@ class PassedToSameFunction { continue; std::optional TargetIdx; - unsigned NumFnParams = CalledFn->getNumParams(); + const unsigned NumFnParams = CalledFn->getNumParams(); for (unsigned Idx = 0; Idx < NumFnParams; ++Idx) if (CalledFn->getParamDecl(Idx) == PassedToParam) TargetIdx.emplace(Idx); @@ -1837,16 +1837,16 @@ static void padStringAtBegin(SmallVectorImpl &Str, std::size_t ToLen) { static bool isCommonPrefixWithoutSomeCharacters(std::size_t N, StringRef S1, StringRef S2) { assert(S1.size() >= N && S2.size() >= N); - StringRef S1Prefix = S1.take_front(S1.size() - N), - S2Prefix = S2.take_front(S2.size() - N); + const StringRef S1Prefix = S1.take_front(S1.size() - N), + S2Prefix = S2.take_front(S2.size() - N); return S1Prefix == S2Prefix && !S1Prefix.empty(); } static bool isCommonSuffixWithoutSomeCharacters(std::size_t N, StringRef S1, StringRef S2) { assert(S1.size() >= N && S2.size() >= N); - StringRef S1Suffix = S1.take_back(S1.size() - N), - S2Suffix = S2.take_back(S2.size() - N); + const StringRef S1Suffix = S1.take_back(S1.size() - N), + S2Suffix = S2.take_back(S2.size() - N); return S1Suffix == S2Suffix && !S1Suffix.empty(); } @@ -1858,7 +1858,7 @@ static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold, return false; // Pad the two strings to the longer length. - std::size_t BiggerLength = std::max(Str1.size(), Str2.size()); + const std::size_t BiggerLength = std::max(Str1.size(), Str2.size()); if (BiggerLength <= Threshold) // If the length of the strings is still smaller than the threshold, they @@ -1980,7 +1980,7 @@ struct FormattedConversionSequence { // However, the parameter's defined type might not be what the implicit // conversion started with, e.g. if a typedef is found to convert. - std::string SeqBeginTypeStr = Conv.Begin.getAsString(PP); + const std::string SeqBeginTypeStr = Conv.Begin.getAsString(PP); std::string SeqEndTypeStr = Conv.End.getAsString(PP); if (StartTypeAsDiagnosed != SeqBeginTypeStr) { OS << " (as '" << SeqBeginTypeStr << "')"; @@ -1995,7 +1995,7 @@ struct FormattedConversionSequence { ++NumElementsAdded; } }; - for (QualType InvolvedType : Conv.getInvolvedTypesInSequence()) + for (const QualType InvolvedType : Conv.getInvolvedTypesInSequence()) // Print every type that's unique in the sequence into the diagnosis. AddType(InvolvedType.getAsString(PP)); @@ -2073,12 +2073,14 @@ class UniqueTypeAliasDiagnosticHelper if (CommonType.isNull() || CommonType == LHSType || CommonType == RHSType) return Base::operator()({LHSType, RHSType, {}}); - TypeAliasDiagnosticTuple ThreeTuple{LHSType, RHSType, CommonType}; + const TypeAliasDiagnosticTuple ThreeTuple{LHSType, RHSType, CommonType}; if (!Base::operator()(ThreeTuple)) return false; - bool AlreadySaidLHSAndCommonIsSame = calledWith({LHSType, CommonType, {}}); - bool AlreadySaidRHSAndCommonIsSame = calledWith({RHSType, CommonType, {}}); + const bool AlreadySaidLHSAndCommonIsSame = + calledWith({LHSType, CommonType, {}}); + const bool AlreadySaidRHSAndCommonIsSame = + calledWith({RHSType, CommonType, {}}); if (AlreadySaidLHSAndCommonIsSame && AlreadySaidRHSAndCommonIsSame) { // "SomeInt == int" && "SomeOtherInt == int" => "Common(SomeInt, // SomeOtherInt) == int", no need to diagnose it. Save the 3-tuple only @@ -2154,12 +2156,12 @@ void EasilySwappableParametersCheck::check( assert(FD); const PrintingPolicy &PP = FD->getASTContext().getPrintingPolicy(); - std::size_t NumParams = FD->getNumParams(); + const std::size_t NumParams = FD->getNumParams(); std::size_t MixableRangeStartIndex = 0; // Spawn one suppressor and if the user requested, gather information from // the AST for the parameters' usages. - filter::SimilarlyUsedParameterPairSuppressor UsageBasedSuppressor{ + const filter::SimilarlyUsedParameterPairSuppressor UsageBasedSuppressor{ FD, SuppressParametersUsedTogether}; LLVM_DEBUG(llvm::dbgs() << "Begin analysis of " << getName(FD) << " with " @@ -2182,11 +2184,13 @@ void EasilySwappableParametersCheck::check( continue; } - bool NeedsAnyTypeNote = llvm::any_of(R.Mixes, needsToPrintTypeInDiagnostic); - bool HasAnyImplicits = + const bool NeedsAnyTypeNote = + llvm::any_of(R.Mixes, needsToPrintTypeInDiagnostic); + const bool HasAnyImplicits = llvm::any_of(R.Mixes, needsToElaborateImplicitConversion); const ParmVarDecl *First = R.getFirstParam(), *Last = R.getLastParam(); - std::string FirstParamTypeAsWritten = First->getType().getAsString(PP); + const std::string FirstParamTypeAsWritten = + First->getType().getAsString(PP); { StringRef DiagText; @@ -2205,7 +2209,7 @@ void EasilySwappableParametersCheck::check( if (!NeedsAnyTypeNote) Diag << FirstParamTypeAsWritten; - CharSourceRange HighlightRange = CharSourceRange::getTokenRange( + const CharSourceRange HighlightRange = CharSourceRange::getTokenRange( First->getBeginLoc(), Last->getEndLoc()); Diag << HighlightRange; } @@ -2240,12 +2244,12 @@ void EasilySwappableParametersCheck::check( // emitted to a note diagnostic, so prepare it. const ParmVarDecl *LVar = M.First; const ParmVarDecl *RVar = M.Second; - QualType LType = LVar->getType(); - QualType RType = RVar->getType(); - QualType CommonType = M.commonUnderlyingType(); - std::string LTypeStr = LType.getAsString(PP); - std::string RTypeStr = RType.getAsString(PP); - std::string CommonTypeStr = CommonType.getAsString(PP); + const QualType LType = LVar->getType(); + const QualType RType = RVar->getType(); + const QualType CommonType = M.commonUnderlyingType(); + const std::string LTypeStr = LType.getAsString(PP); + const std::string RTypeStr = RType.getAsString(PP); + const std::string CommonTypeStr = CommonType.getAsString(PP); if (hasFlag(M.flags(), MixFlags::TypeAlias) && UniqueTypeAlias(LType, RType, CommonType)) { @@ -2274,8 +2278,9 @@ void EasilySwappableParametersCheck::check( if ((hasFlag(M.flags(), MixFlags::ReferenceBind) || hasFlag(M.flags(), MixFlags::Qualifiers)) && UniqueBindPower({LType, RType})) { - StringRef DiagText = "'%0' and '%1' parameters accept and bind the " - "same kind of values"; + const StringRef DiagText = + "'%0' and '%1' parameters accept and bind the " + "same kind of values"; diag(RVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note) << LTypeStr << RTypeStr; } @@ -2286,8 +2291,8 @@ void EasilySwappableParametersCheck::check( M.leftToRightConversionSequence(); const model::ConversionSequence &RTL = M.rightToLeftConversionSequence(); - FormattedConversionSequence LTRFmt{PP, LTypeStr, LTR, RTypeStr}; - FormattedConversionSequence RTLFmt{PP, RTypeStr, RTL, LTypeStr}; + const FormattedConversionSequence LTRFmt{PP, LTypeStr, LTR, RTypeStr}; + const FormattedConversionSequence RTLFmt{PP, RTypeStr, RTL, LTypeStr}; StringRef DiagText = "'%0' and '%1' may be implicitly converted"; if (!LTRFmt.Trivial || !RTLFmt.Trivial) @@ -2302,7 +2307,7 @@ void EasilySwappableParametersCheck::check( Diag << LTRFmt.DiagnosticText << RTLFmt.DiagnosticText; } - StringRef ConversionFunctionDiagText = + const StringRef ConversionFunctionDiagText = "the implicit conversion involves the " "%select{|converting constructor|conversion operator}0 " "declared here"; diff --git a/clang-tools-extra/clang-tidy/bugprone/EmptyCatchCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/EmptyCatchCheck.cpp index eebab847d1070..5dd2f62504c71 100644 --- a/clang-tools-extra/clang-tidy/bugprone/EmptyCatchCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/EmptyCatchCheck.cpp @@ -25,7 +25,7 @@ AST_MATCHER(CXXCatchStmt, isInMacro) { } AST_MATCHER_P(CXXCatchStmt, hasHandler, Matcher, InnerMatcher) { - Stmt *Handler = Node.getHandlerBlock(); + const Stmt *Handler = Node.getHandlerBlock(); if (!Handler) return false; return InnerMatcher.matches(*Handler, Finder, Builder); @@ -41,7 +41,7 @@ AST_MATCHER_P(CompoundStmt, hasAnyTextFromList, std::vector, return false; ASTContext &Context = Finder->getASTContext(); - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); StringRef Text = Lexer::getSourceText( CharSourceRange::getTokenRange(Node.getSourceRange()), SM, Context.getLangOpts()); diff --git a/clang-tools-extra/clang-tidy/bugprone/ForwardDeclarationNamespaceCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ForwardDeclarationNamespaceCheck.cpp index c3db8fa9b3af2..11270e7f34d79 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ForwardDeclarationNamespaceCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ForwardDeclarationNamespaceCheck.cpp @@ -46,7 +46,7 @@ void ForwardDeclarationNamespaceCheck::check( const MatchFinder::MatchResult &Result) { if (const auto *RecordDecl = Result.Nodes.getNodeAs("record_decl")) { - StringRef DeclName = RecordDecl->getName(); + const StringRef DeclName = RecordDecl->getName(); if (RecordDecl->isThisDeclarationADefinition()) { DeclNameToDefinitions[DeclName].push_back(RecordDecl); } else { diff --git a/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp index d372cbd798b2e..c1e66f210b8b2 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp @@ -40,7 +40,7 @@ AST_MATCHER(QualType, isEnableIf) { if (CheckTemplate(BaseType->getAs())) return true; // Case: enable_if_t< >. if (const auto *TT = BaseType->getAs()) - if (NestedNameSpecifier Q = TT->getQualifier(); + if (const NestedNameSpecifier Q = TT->getQualifier(); Q.getKind() == NestedNameSpecifier::Kind::Type) if (CheckTemplate(Q.getAsType()->getAs())) return true; // Case: enable_if< >::type. @@ -67,7 +67,7 @@ void ForwardingReferenceOverloadCheck::registerMatchers(MatchFinder *Finder) { unless(references(isConstQualified()))))) .bind("parm-var"); - DeclarationMatcher FindOverload = + const DeclarationMatcher FindOverload = cxxConstructorDecl( hasParameter(0, ForwardingRefParm), unless(isDeleted()), unless(hasAnyParameter( @@ -128,8 +128,9 @@ void ForwardingReferenceOverloadCheck::check( (OtherCtor->isCopyConstructor() ? EnabledCopy : EnabledMove) = true; } } - bool Copy = (!EnabledMove && !DisabledMove && !DisabledCopy) || EnabledCopy; - bool Move = !DisabledMove || EnabledMove; + const bool Copy = + (!EnabledMove && !DisabledMove && !DisabledCopy) || EnabledCopy; + const bool Move = !DisabledMove || EnabledMove; if (!Copy && !Move) return; diag(Ctor->getLocation(), diff --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp index 2211a0ba24ebc..634d54c2b9bd3 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp @@ -71,18 +71,18 @@ ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader( void ImplicitWideningOfMultiplicationResultCheck::handleImplicitCastExpr( const ImplicitCastExpr *ICE) { - ASTContext *Context = Result->Context; + const ASTContext *Context = Result->Context; const Expr *E = ICE->getSubExpr()->IgnoreParens(); - QualType Ty = ICE->getType(); - QualType ETy = E->getType(); + const QualType Ty = ICE->getType(); + const QualType ETy = E->getType(); assert(!ETy->isDependentType() && !Ty->isDependentType() && "Don't expect to ever get here in template Context."); // This must be a widening cast. Else we do not care. - unsigned SrcWidth = Context->getIntWidth(ETy); - unsigned TgtWidth = Context->getIntWidth(Ty); + const unsigned SrcWidth = Context->getIntWidth(ETy); + const unsigned TgtWidth = Context->getIntWidth(Ty); if (TgtWidth <= SrcWidth) return; @@ -92,7 +92,7 @@ void ImplicitWideningOfMultiplicationResultCheck::handleImplicitCastExpr( !ETy->isUnsignedIntegerType()) { if (const auto ConstExprResult = E->getIntegerConstantExpr(*Context)) { const auto TypeSize = Context->getTypeSize(ETy); - llvm::APSInt WidenedResult = ConstExprResult->extOrTrunc(TypeSize); + const llvm::APSInt WidenedResult = ConstExprResult->extOrTrunc(TypeSize); if (WidenedResult <= llvm::APSInt::getMaxValue(TypeSize, false) && WidenedResult >= llvm::APSInt::getMinValue(TypeSize, false)) return; @@ -168,7 +168,7 @@ void ImplicitWideningOfMultiplicationResultCheck::handleImplicitCastExpr( void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting( const Expr *E) { - ASTContext *Context = Result->Context; + const ASTContext *Context = Result->Context; // We are looking for a pointer offset operation, // with one hand being a pointer, and another one being an offset. @@ -191,19 +191,20 @@ void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting( IndexExpr = IndexExpr->IgnoreParens(); - QualType IndexExprType = IndexExpr->getType(); + const QualType IndexExprType = IndexExpr->getType(); // If the index expression's type is not known (i.e. we are in a template), // we can't do anything here. if (IndexExprType->isDependentType()) return; - QualType SSizeTy = Context->getPointerDiffType(); - QualType USizeTy = Context->getSizeType(); - QualType SizeTy = IndexExprType->isSignedIntegerType() ? SSizeTy : USizeTy; + const QualType SSizeTy = Context->getPointerDiffType(); + const QualType USizeTy = Context->getSizeType(); + const QualType SizeTy = + IndexExprType->isSignedIntegerType() ? SSizeTy : USizeTy; // FIXME: is there a way to actually get the QualType for size_t/ptrdiff_t? // Note that SizeTy.getAsString() will be unsigned long/..., NOT size_t! - StringRef TyAsString = + const StringRef TyAsString = IndexExprType->isSignedIntegerType() ? "ptrdiff_t" : "size_t"; // So, is size_t actually wider than the result of the multiplication? diff --git a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp index b0dd9017c8426..12fa3655ffcd6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp @@ -43,7 +43,7 @@ void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) { if (!Loc.isMacroID() && EndExpr) { const auto *AlgCall = Result.Nodes.getNodeAs("alg"); - std::string ReplacementText = std::string(Lexer::getSourceText( + const std::string ReplacementText = std::string(Lexer::getSourceText( CharSourceRange::getTokenRange(EndExpr->getSourceRange()), *Result.SourceManager, getLangOpts())); const SourceLocation EndLoc = Lexer::getLocForEndOfToken( diff --git a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp index 84a99c36523ac..6181ac84f36e3 100644 --- a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp @@ -22,7 +22,7 @@ AST_MATCHER_P(TemplateTypeParmDecl, hasUnnamedDefaultArgument, Node.getDefaultArgument().getArgument().isNull()) return false; - TypeLoc DefaultArgTypeLoc = + const TypeLoc DefaultArgTypeLoc = Node.getDefaultArgument().getTypeSourceInfo()->getTypeLoc(); return InnerMatcher.matches(DefaultArgTypeLoc, Finder, Builder); } @@ -51,7 +51,7 @@ void IncorrectEnableIfCheck::check(const MatchFinder::MatchResult &Result) { return; const SourceManager &SM = *Result.SourceManager; - SourceLocation RAngleLoc = + const SourceLocation RAngleLoc = SM.getExpansionLoc(EnableIfSpecializationLoc->getRAngleLoc()); auto Diag = diag(EnableIf->getBeginLoc(), diff --git a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp index 1e516c1573219..50280d22be0d8 100644 --- a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp @@ -34,7 +34,7 @@ AST_MATCHER(FunctionType, typeHasNoReturnAttr) { } // namespace static Matcher loopEndingStmt(Matcher Internal) { - Matcher IsNoReturnFunType = + const Matcher IsNoReturnFunType = ignoringParens(functionType(typeHasNoReturnAttr())); Matcher IsNoReturnDecl = anyOf(declHasNoReturnAttr(), functionDecl(hasType(IsNoReturnFunType)), @@ -145,7 +145,7 @@ static std::string getCondVarNames(const Stmt *Cond) { if (!Child) continue; - std::string NewNames = getCondVarNames(Child); + const std::string NewNames = getCondVarNames(Child); if (!Result.empty() && !NewNames.empty()) Result += ", "; Result += NewNames; @@ -332,7 +332,7 @@ void InfiniteLoopCheck::check(const MatchFinder::MatchResult &Result) { Result.Context)) return; - std::string CondVarNames = getCondVarNames(Cond); + const std::string CondVarNames = getCondVarNames(Cond); if (ShouldHaveConditionVariables && CondVarNames.empty()) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp index 18eb40f4eb6d2..f3e94b62f0dbd 100644 --- a/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/InvalidEnumDefaultInitializationCheck.cpp @@ -151,7 +151,7 @@ void InvalidEnumDefaultInitializationCheck::check( SourceLocation Loc = InitExpr->getExprLoc(); if (Loc.isInvalid()) { if (isa(InitExpr)) { - DynTypedNodeList Parents = ACtx.getParents(*InitExpr); + const DynTypedNodeList Parents = ACtx.getParents(*InitExpr); if (Parents.empty()) return; @@ -170,7 +170,7 @@ void InvalidEnumDefaultInitializationCheck::check( // The expression may be implicitly generated for an initialization. // Search for a parent initialization list with valid source location. while (InitList->getExprLoc().isInvalid()) { - DynTypedNodeList Parents = ACtx.getParents(*InitList); + const DynTypedNodeList Parents = ACtx.getParents(*InitList); if (Parents.empty()) return; InitList = Parents[0].get(); diff --git a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp index fb73e896fdb13..1f666d2a4345f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp @@ -40,7 +40,7 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks { bool HasLine = false; for (const Token &T : MD.getMacroInfo()->tokens()) { if (T.is(tok::identifier)) { - StringRef IdentName = T.getIdentifierInfo()->getName(); + const StringRef IdentName = T.getIdentifierInfo()->getName(); if (IdentName == "__FILE__") { HasFile = true; } else if (IdentName == "__LINE__") { diff --git a/clang-tools-extra/clang-tidy/bugprone/MacroRepeatedSideEffectsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MacroRepeatedSideEffectsCheck.cpp index 78a53d12bd312..c79320fbf3304 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MacroRepeatedSideEffectsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MacroRepeatedSideEffectsCheck.cpp @@ -127,7 +127,7 @@ unsigned MacroRepeatedPPCallbacks::countArgumentExpansions( continue; } - IdentifierInfo *TII = T.getIdentifierInfo(); + const IdentifierInfo *TII = T.getIdentifierInfo(); // If not existent, skip it. if (TII == nullptr) continue; From 5896a25ffe53648cdf7bf057e006565cbd2bf260 Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 19:05:47 +0300 Subject: [PATCH 17/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (13/N) (#167130) --- .../bugprone/MisplacedWideningCastCheck.cpp | 12 +-- .../bugprone/MoveForwardingReferenceCheck.cpp | 4 +- ...ltiLevelImplicitPointerConversionCheck.cpp | 5 +- .../MultipleNewInOneExpressionCheck.cpp | 5 +- .../bugprone/NarrowingConversionsCheck.cpp | 40 ++++---- ...eterministicPointerIterationOrderCheck.cpp | 4 +- .../bugprone/NotNullTerminatedResultCheck.cpp | 94 ++++++++++--------- .../clang-tidy/bugprone/PosixReturnCheck.cpp | 4 +- .../RedundantBranchConditionCheck.cpp | 10 +- .../ReturnConstRefFromParameterCheck.cpp | 2 +- .../bugprone/SignalHandlerCheck.cpp | 15 +-- .../clang-tidy/bugprone/SignalHandlerCheck.h | 5 +- .../bugprone/SignedCharMisuseCheck.cpp | 4 +- .../bugprone/SizeofExpressionCheck.cpp | 6 +- .../bugprone/SmartPtrArrayMismatchCheck.cpp | 10 +- .../SpuriouslyWakeUpFunctionsCheck.cpp | 2 +- .../bugprone/StandaloneEmptyCheck.cpp | 30 +++--- .../StdNamespaceModificationCheck.cpp | 4 +- .../bugprone/StringConstructorCheck.cpp | 6 +- 19 files changed, 135 insertions(+), 127 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp index d508e2aaba53c..f040235322a4f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp @@ -52,8 +52,8 @@ static unsigned getMaxCalculationWidth(const ASTContext &Context, E = E->IgnoreParenImpCasts(); if (const auto *Bop = dyn_cast(E)) { - unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS()); - unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS()); + const unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS()); + const unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS()); if (Bop->getOpcode() == BO_Mul) return LHSWidth + RHSWidth; if (Bop->getOpcode() == BO_Add) @@ -79,7 +79,7 @@ static unsigned getMaxCalculationWidth(const ASTContext &Context, if (Uop->getOpcode() == UO_Not) return 1024U; - QualType T = Uop->getType(); + const QualType T = Uop->getType(); return T->isIntegerType() ? Context.getIntWidth(T) : 1024U; } else if (const auto *I = dyn_cast(E)) { return I->getValue().getActiveBits(); @@ -190,10 +190,10 @@ void MisplacedWideningCastCheck::check(const MatchFinder::MatchResult &Result) { Calc->isTypeDependent() || Calc->isValueDependent()) return; - ASTContext &Context = *Result.Context; + const ASTContext &Context = *Result.Context; - QualType CastType = Cast->getType(); - QualType CalcType = Calc->getType(); + const QualType CastType = Cast->getType(); + const QualType CalcType = Calc->getType(); // Explicit truncation using cast. if (Context.getIntWidth(CastType) < Context.getIntWidth(CalcType)) diff --git a/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp index 66559a0e5d7b5..e182df75b1d9a 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp @@ -21,7 +21,7 @@ static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee, const SourceManager &SM = Context.getSourceManager(); const LangOptions &LangOpts = Context.getLangOpts(); - CharSourceRange CallRange = + const CharSourceRange CallRange = Lexer::makeFileCharRange(CharSourceRange::getTokenRange( Callee->getBeginLoc(), Callee->getEndLoc()), SM, LangOpts); @@ -39,7 +39,7 @@ static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee, // std::move(). This will hopefully prevent erroneous replacements if the // code does unusual things (e.g. create an alias for std::move() in // another namespace). - NestedNameSpecifier NNS = Callee->getQualifier(); + const NestedNameSpecifier NNS = Callee->getQualifier(); switch (NNS.getKind()) { case NestedNameSpecifier::Kind::Null: // Called as "move" (i.e. presumably the code had a "using std::move;"). diff --git a/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp index 2eff013b2ab7d..78f2017984a96 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp @@ -86,8 +86,9 @@ MultiLevelImplicitPointerConversionCheck::getCheckTraversalKind() const { void MultiLevelImplicitPointerConversionCheck::check( const MatchFinder::MatchResult &Result) { const auto *MatchedExpr = Result.Nodes.getNodeAs("expr"); - QualType Target = MatchedExpr->getType().getDesugaredType(*Result.Context); - QualType Source = + const QualType Target = + MatchedExpr->getType().getDesugaredType(*Result.Context); + const QualType Source = MatchedExpr->getSubExpr()->getType().getDesugaredType(*Result.Context); diag(MatchedExpr->getExprLoc(), "multilevel pointer conversion from %0 to " diff --git a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp index 17aea9392bd26..b81d2b438d58d 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp @@ -51,7 +51,8 @@ namespace { AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { - for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { + const unsigned NH = Node.getNumHandlers(); + for (unsigned I = 0; I < NH; ++I) { const CXXCatchStmt *CatchS = Node.getHandler(I); // Check for generic catch handler (match anything). if (CatchS->getCaughtType().isNull()) @@ -66,7 +67,7 @@ AST_MATCHER_P(CXXTryStmt, hasHandlerFor, } AST_MATCHER(CXXNewExpr, mayThrow) { - FunctionDecl *OperatorNew = Node.getOperatorNew(); + const FunctionDecl *OperatorNew = Node.getOperatorNew(); if (!OperatorNew) return false; return !OperatorNew->getType()->castAs()->isNothrow(); diff --git a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp index 287ee95a4db55..501a82d67d558 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp @@ -29,15 +29,15 @@ AST_MATCHER_P(QualType, hasAnyType, std::vector, Names) { if (Names.empty()) return false; - std::string Name = Node.getLocalUnqualifiedType().getAsString(); + const std::string Name = Node.getLocalUnqualifiedType().getAsString(); return llvm::is_contained(Names, Name); } AST_MATCHER(FieldDecl, hasIntBitwidth) { assert(Node.isBitField()); const ASTContext &Ctx = Node.getASTContext(); - unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy); - unsigned CurrentBitWidth = Node.getBitWidthValue(); + const unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy); + const unsigned CurrentBitWidth = Node.getBitWidthValue(); return IntBitWidth == CurrentBitWidth; } @@ -79,7 +79,7 @@ void NarrowingConversionsCheck::registerMatchers(MatchFinder *Finder) { const auto IsCeilFloorCallExpr = expr(callExpr(callee(functionDecl( hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor"))))); - std::vector IgnoreConversionFromTypesVec = + const std::vector IgnoreConversionFromTypesVec = utils::options::parseStringList(IgnoreConversionFromTypes); // We may want to exclude other types from the checks, such as `size_type` @@ -243,7 +243,7 @@ struct IntegerRange { static IntegerRange createFromType(const ASTContext &Context, const BuiltinType &T) { if (T.isFloatingPoint()) { - unsigned PrecisionBits = llvm::APFloatBase::semanticsPrecision( + const unsigned PrecisionBits = llvm::APFloatBase::semanticsPrecision( Context.getFloatTypeSemantics(T.desugar())); // Contrary to two's complement integer, floating point values are // symmetric and have the same number of positive and negative values. @@ -262,8 +262,8 @@ static IntegerRange createFromType(const ASTContext &Context, return {LowerValue, UpperValue}; } assert(T.isInteger() && "Unexpected builtin type"); - uint64_t TypeSize = Context.getTypeSize(&T); - bool IsUnsignedInteger = T.isUnsignedInteger(); + const uint64_t TypeSize = Context.getTypeSize(&T); + const bool IsUnsignedInteger = T.isUnsignedInteger(); return {llvm::APSInt::getMinValue(TypeSize, IsUnsignedInteger), llvm::APSInt::getMaxValue(TypeSize, IsUnsignedInteger)}; } @@ -271,15 +271,15 @@ static IntegerRange createFromType(const ASTContext &Context, static bool isWideEnoughToHold(const ASTContext &Context, const BuiltinType &FromType, const BuiltinType &ToType) { - IntegerRange FromIntegerRange = createFromType(Context, FromType); - IntegerRange ToIntegerRange = createFromType(Context, ToType); + const IntegerRange FromIntegerRange = createFromType(Context, FromType); + const IntegerRange ToIntegerRange = createFromType(Context, ToType); return ToIntegerRange.contains(FromIntegerRange); } static bool isWideEnoughToHold(const ASTContext &Context, const llvm::APSInt &IntegerConstant, const BuiltinType &ToType) { - IntegerRange ToIntegerRange = createFromType(Context, ToType); + const IntegerRange ToIntegerRange = createFromType(Context, ToType); return ToIntegerRange.contains(IntegerConstant); } @@ -289,13 +289,13 @@ static bool isWideEnoughToHold(const ASTContext &Context, static bool isFloatExactlyRepresentable(const ASTContext &Context, const llvm::APFloat &FloatConstant, const QualType &DestType) { - unsigned DestWidth = Context.getIntWidth(DestType); - bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); + const unsigned DestWidth = Context.getIntWidth(DestType); + const bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); llvm::APSInt Result = llvm::APSInt(DestWidth, !DestSigned); bool IsExact = false; - bool Overflows = FloatConstant.convertToInteger( - Result, llvm::APFloat::rmTowardZero, &IsExact) & - llvm::APFloat::opInvalidOp; + const bool Overflows = FloatConstant.convertToInteger( + Result, llvm::APFloat::rmTowardZero, &IsExact) & + llvm::APFloat::opInvalidOp; return !Overflows && IsExact; } @@ -321,8 +321,8 @@ bool NarrowingConversionsCheck::isWarningInhibitedByEquivalentSize( // With this option, we don't warn on conversions that have equivalent width // in bits. eg. uint32 <-> int32. if (!WarnOnEquivalentBitWidth) { - uint64_t FromTypeSize = Context.getTypeSize(&FromType); - uint64_t ToTypeSize = Context.getTypeSize(&ToType); + const uint64_t FromTypeSize = Context.getTypeSize(&FromType); + const uint64_t ToTypeSize = Context.getTypeSize(&ToType); if (FromTypeSize == ToTypeSize) { return true; } @@ -406,8 +406,8 @@ void NarrowingConversionsCheck::handleIntegralCast(const ASTContext &Context, // With this option, we don't warn on conversions that have equivalent width // in bits. eg. uint32 <-> int32. if (!WarnOnEquivalentBitWidth) { - uint64_t FromTypeSize = Context.getTypeSize(FromType); - uint64_t ToTypeSize = Context.getTypeSize(ToType); + const uint64_t FromTypeSize = Context.getTypeSize(FromType); + const uint64_t ToTypeSize = Context.getTypeSize(ToType); if (FromTypeSize == ToTypeSize) return; } @@ -583,7 +583,7 @@ void NarrowingConversionsCheck::handleImplicitCast( return; if (handleConditionalOperator(Context, Lhs, Rhs)) return; - SourceLocation SourceLoc = Lhs.getExprLoc(); + const SourceLocation SourceLoc = Lhs.getExprLoc(); switch (Cast.getCastKind()) { case CK_BooleanToSignedIntegral: handleBooleanToSignedIntegral(Context, SourceLoc, Lhs, Rhs); diff --git a/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp index abde115d10a1b..40305cab81c7f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp @@ -60,7 +60,7 @@ void NondeterministicPointerIterationOrderCheck::check( TemplateArgs[0].getAsType()->isPointerType(); if (IsAlgoArgPointer) { - SourceRange R = RangeInit->getSourceRange(); + const SourceRange R = RangeInit->getSourceRange(); diag(R.getBegin(), "iteration of pointers is nondeterministic") << R; } } @@ -69,7 +69,7 @@ void NondeterministicPointerIterationOrderCheck::check( const auto *SortPointers = Result.Nodes.getNodeAs("sortsemantic"); if ((SortPointers) && !(SortPointers->getBeginLoc().isMacroID())) { - SourceRange R = SortPointers->getSourceRange(); + const SourceRange R = SortPointers->getSourceRange(); diag(R.getBegin(), "sorting pointers is nondeterministic") << R; } } diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index 08fae7b59bae5..7198c1b1c8aaf 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -120,18 +120,18 @@ static int getGivenLength(const MatchFinder::MatchResult &Result) { if (Result.Nodes.getNodeAs(UnknownLengthName)) return 0; - if (int Length = + if (const int Length = getLength(Result.Nodes.getNodeAs(WrongLengthExprName), Result)) return Length; - if (int Length = + if (const int Length = getLength(Result.Nodes.getNodeAs(LengthExprName), Result)) return Length; // Special case, for example 'strlen("foo")'. if (const CallExpr *StrlenCE = getStrlenExpr(Result)) if (const Expr *Arg = StrlenCE->getArg(0)->IgnoreImpCasts()) - if (int ArgLength = getLength(Arg, Result)) + if (const int ArgLength = getLength(Arg, Result)) return ArgLength; return 0; @@ -174,9 +174,9 @@ static bool isKnownDest(const MatchFinder::MatchResult &Result) { // True if the capacity of the destination array is based on the given length, // therefore we assume that it cannot overflow (e.g. 'malloc(given_length + 1)' static bool isDestBasedOnGivenLength(const MatchFinder::MatchResult &Result) { - StringRef DestCapacityExprStr = + const StringRef DestCapacityExprStr = exprToStr(getDestCapacityExpr(Result), Result).trim(); - StringRef LengthExprStr = + const StringRef LengthExprStr = exprToStr(Result.Nodes.getNodeAs(LengthExprName), Result).trim(); return !DestCapacityExprStr.empty() && !LengthExprStr.empty() && @@ -226,8 +226,9 @@ isGivenLengthEqualToSrcLength(const MatchFinder::MatchResult &Result) { if (isStringDataAndLength(Result)) return true; - int GivenLength = getGivenLength(Result); - int SrcLength = getLength(Result.Nodes.getNodeAs(SrcExprName), Result); + const int GivenLength = getGivenLength(Result); + const int SrcLength = + getLength(Result.Nodes.getNodeAs(SrcExprName), Result); if (GivenLength != 0 && SrcLength != 0 && GivenLength == SrcLength) return true; @@ -261,15 +262,15 @@ static bool isDestCapacityOverflows(const MatchFinder::MatchResult &Result) { return true; const Expr *DestCapacityExpr = getDestCapacityExpr(Result); - int DestCapacity = getLength(DestCapacityExpr, Result); - int GivenLength = getGivenLength(Result); + const int DestCapacity = getLength(DestCapacityExpr, Result); + const int GivenLength = getGivenLength(Result); if (GivenLength != 0 && DestCapacity != 0) return isGivenLengthEqualToSrcLength(Result) && DestCapacity == GivenLength; // Assume that the destination array's capacity cannot overflow if the // expression of the memory allocation contains '+ 1'. - StringRef DestCapacityExprStr = exprToStr(DestCapacityExpr, Result); + const StringRef DestCapacityExprStr = exprToStr(DestCapacityExpr, Result); if (DestCapacityExprStr.contains("+1") || DestCapacityExprStr.contains("+ 1")) return false; @@ -297,7 +298,7 @@ static void lengthExprHandle(const Expr *LengthExpr, // See whether we work with a macro. bool IsMacroDefinition = false; - StringRef LengthExprStr = exprToStr(LengthExpr, Result); + const StringRef LengthExprStr = exprToStr(LengthExpr, Result); Preprocessor::macro_iterator It = PP->macro_begin(); while (It != PP->macro_end() && !IsMacroDefinition) { if (It->first->getName() == LengthExprStr) @@ -309,7 +310,7 @@ static void lengthExprHandle(const Expr *LengthExpr, // Try to obtain an 'IntegerLiteral' and adjust it. if (!IsMacroDefinition) { if (const auto *LengthIL = dyn_cast(LengthExpr)) { - uint64_t NewLength = + const uint64_t NewLength = LengthIL->getValue().getZExtValue() + (LengthHandle == LengthHandleKind::Increase ? 1 : -1); @@ -347,7 +348,7 @@ static void lengthExprHandle(const Expr *LengthExpr, } // Try to inject the '+ 1'/'- 1' string. - bool NeedInnerParen = BO && BO->getOpcode() != BO_Add; + const bool NeedInnerParen = BO && BO->getOpcode() != BO_Add; if (NeedInnerParen) Diag << FixItHint::CreateInsertion(LengthExpr->getBeginLoc(), "("); @@ -384,8 +385,8 @@ static bool isDestExprFix(const MatchFinder::MatchResult &Result, if (!Dest) return false; - std::string TempTyStr = Dest->getType().getAsString(); - StringRef TyStr = TempTyStr; + const std::string TempTyStr = Dest->getType().getAsString(); + const StringRef TyStr = TempTyStr; if (TyStr.starts_with("char") || TyStr.starts_with("wchar_t")) return false; @@ -397,7 +398,7 @@ static bool isDestExprFix(const MatchFinder::MatchResult &Result, // increase the capacity by one to create space for the null terminator. static bool isDestCapacityFix(const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityOverflows(Result); + const bool IsOverflows = isDestCapacityOverflows(Result); if (IsOverflows) if (const Expr *CapacityExpr = getDestCapacityExpr(Result)) lengthExprHandle(CapacityExpr, LengthHandleKind::Increase, Result, Diag); @@ -424,9 +425,9 @@ static void renameFunc(StringRef NewFuncName, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); - int FuncNameLength = + const int FuncNameLength = FunctionExpr->getDirectCallee()->getIdentifier()->getLength(); - SourceRange FuncNameRange( + const SourceRange FuncNameRange( FunctionExpr->getBeginLoc(), FunctionExpr->getBeginLoc().getLocWithOffset(FuncNameLength - 1)); @@ -451,7 +452,7 @@ static void insertDestCapacityArg(bool IsOverflows, StringRef Name, const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); SmallString<64> NewSecondArg; - if (int DestLength = getDestCapacity(Result)) { + if (const int DestLength = getDestCapacity(Result)) { NewSecondArg = Twine(IsOverflows ? DestLength + 1 : DestLength).str(); } else { NewSecondArg = @@ -470,12 +471,12 @@ static void insertNullTerminatorExpr(StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); - int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber( + const int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber( FunctionExpr->getBeginLoc()); - SourceRange SpaceRange( + const SourceRange SpaceRange( FunctionExpr->getBeginLoc().getLocWithOffset(-FuncLocStartColumn + 1), FunctionExpr->getBeginLoc()); - StringRef SpaceBeforeStmtStr = Lexer::getSourceText( + const StringRef SpaceBeforeStmtStr = Lexer::getSourceText( CharSourceRange::getCharRange(SpaceRange), *Result.SourceManager, Result.Context->getLangOpts(), nullptr); @@ -717,10 +718,10 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { }; auto MatchCall = [=](CallContext CC) { - std::string CharHandlerFuncName = "::" + CC.Name.str(); + const std::string CharHandlerFuncName = "::" + CC.Name.str(); // Try to match with 'wchar_t' based function calls. - std::string WcharHandlerFuncName = + const std::string WcharHandlerFuncName = "::" + (CC.Name.starts_with("mem") ? "w" + CC.Name.str() : "wcs" + CC.Name.substr(3).str()); @@ -804,7 +805,8 @@ void NotNullTerminatedResultCheck::check( if (MI) { const auto &T = MI->tokens().back(); if (T.isLiteral() && T.getLiteralData()) { - StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength()); + const StringRef ValueStr = + StringRef(T.getLiteralData(), T.getLength()); llvm::APInt IntValue; ValueStr.getAsInteger(10, IntValue); AreSafeFunctionsWanted = IntValue.getZExtValue(); @@ -819,7 +821,7 @@ void NotNullTerminatedResultCheck::check( UseSafeFunctions = *AreSafeFunctionsWanted; } - StringRef Name = FunctionExpr->getDirectCallee()->getName(); + const StringRef Name = FunctionExpr->getDirectCallee()->getName(); if (Name.starts_with("mem") || Name.starts_with("wmem")) memoryHandlerFunctionFix(Name, Result); else if (Name == "strerror_s") @@ -864,16 +866,16 @@ void NotNullTerminatedResultCheck::memoryHandlerFunctionFix( void NotNullTerminatedResultCheck::memcpyFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityFix(Result, Diag); - bool IsDestFixed = isDestExprFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsDestFixed = isDestExprFix(Result, Diag); - bool IsCopy = + const bool IsCopy = isGivenLengthEqualToSrcLength(Result) || isDestBasedOnGivenLength(Result); - bool IsSafe = UseSafeFunctions && IsOverflows && isKnownDest(Result) && - !isDestBasedOnGivenLength(Result); + const bool IsSafe = UseSafeFunctions && IsOverflows && isKnownDest(Result) && + !isDestBasedOnGivenLength(Result); - bool IsDestLengthNotRequired = + const bool IsDestLengthNotRequired = IsSafe && getLangOpts().CPlusPlus && Result.Nodes.getNodeAs(DestArrayTyName) && !IsDestFixed; @@ -892,14 +894,14 @@ void NotNullTerminatedResultCheck::memcpyFix( void NotNullTerminatedResultCheck::memcpySFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityFix(Result, Diag); - bool IsDestFixed = isDestExprFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsDestFixed = isDestExprFix(Result, Diag); - bool RemoveDestLength = getLangOpts().CPlusPlus && - Result.Nodes.getNodeAs(DestArrayTyName) && - !IsDestFixed; - bool IsCopy = isGivenLengthEqualToSrcLength(Result); - bool IsSafe = IsOverflows; + const bool RemoveDestLength = + getLangOpts().CPlusPlus && + Result.Nodes.getNodeAs(DestArrayTyName) && !IsDestFixed; + const bool IsCopy = isGivenLengthEqualToSrcLength(Result); + const bool IsSafe = IsOverflows; renameMemcpy(Name, IsCopy, IsSafe, Result, Diag); @@ -932,7 +934,7 @@ void NotNullTerminatedResultCheck::memchrFix( Diag << CastRemoveFix; } - StringRef NewFuncName = (Name[0] != 'w') ? "strchr" : "wcschr"; + const StringRef NewFuncName = (Name[0] != 'w') ? "strchr" : "wcschr"; renameFunc(NewFuncName, Result, Diag); removeArg(2, Result, Diag); } @@ -940,7 +942,7 @@ void NotNullTerminatedResultCheck::memchrFix( void NotNullTerminatedResultCheck::memmoveFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) const { - bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); if (UseSafeFunctions && isKnownDest(Result)) { renameFunc((Name[0] != 'w') ? "memmove_s" : "wmemmove_s", Result, Diag); @@ -970,15 +972,15 @@ void NotNullTerminatedResultCheck::ncmpFix( if (const CallExpr *StrlenExpr = getStrlenExpr(Result)) { const Expr *LengthExprArg = StrlenExpr->getArg(0); - StringRef FirstExprStr = exprToStr(FirstArgExpr, Result).trim(); - StringRef SecondExprStr = exprToStr(SecondArgExpr, Result).trim(); - StringRef LengthArgStr = exprToStr(LengthExprArg, Result).trim(); + const StringRef FirstExprStr = exprToStr(FirstArgExpr, Result).trim(); + const StringRef SecondExprStr = exprToStr(SecondArgExpr, Result).trim(); + const StringRef LengthArgStr = exprToStr(LengthExprArg, Result).trim(); IsLengthTooLong = LengthArgStr == FirstExprStr || LengthArgStr == SecondExprStr; } else { - int SrcLength = + const int SrcLength = getLength(Result.Nodes.getNodeAs(SrcExprName), Result); - int GivenLength = getGivenLength(Result); + const int GivenLength = getGivenLength(Result); if (SrcLength != 0 && GivenLength != 0) IsLengthTooLong = GivenLength > SrcLength; } diff --git a/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp index 57196adf38fb6..0084ace7d0fcc 100644 --- a/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp @@ -66,8 +66,8 @@ void PosixReturnCheck::registerMatchers(MatchFinder *Finder) { void PosixReturnCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *LessThanZeroOp = Result.Nodes.getNodeAs("ltzop")) { - SourceLocation OperatorLoc = LessThanZeroOp->getOperatorLoc(); - StringRef NewBinOp = + const SourceLocation OperatorLoc = LessThanZeroOp->getOperatorLoc(); + const StringRef NewBinOp = LessThanZeroOp->getOpcode() == BinaryOperator::Opcode::BO_LT ? ">" : "<"; diag(OperatorLoc, "the comparison always evaluates to false because %0 " diff --git a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp index 6abe53f47b8f9..528c254dbe17e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp @@ -112,7 +112,7 @@ void RedundantBranchConditionCheck::check( if (isa(InnerIf->getCond()->IgnoreParenImpCasts()) || (BinOpCond && BinOpCond->getOpcode() == BO_LOr)) { - SourceLocation IfBegin = InnerIf->getBeginLoc(); + const SourceLocation IfBegin = InnerIf->getBeginLoc(); const Stmt *Body = InnerIf->getThen(); const Expr *OtherSide = nullptr; if (BinOpCond) { @@ -132,9 +132,9 @@ void RedundantBranchConditionCheck::check( // If the other side has side effects then keep it. if (OtherSide && OtherSide->HasSideEffects(*Result.Context)) { - SourceLocation BeforeOtherSide = + const SourceLocation BeforeOtherSide = OtherSide->getBeginLoc().getLocWithOffset(-1); - SourceLocation AfterOtherSide = + const SourceLocation AfterOtherSide = Lexer::findNextToken(OtherSide->getEndLoc(), *Result.SourceManager, getLangOpts()) ->getLocation(); @@ -161,12 +161,12 @@ void RedundantBranchConditionCheck::check( const auto *LeftDRE = dyn_cast(CondOp->getLHS()->IgnoreParenImpCasts()); if (LeftDRE && LeftDRE->getDecl() == CondVar) { - SourceLocation BeforeRHS = + const SourceLocation BeforeRHS = CondOp->getRHS()->getBeginLoc().getLocWithOffset(-1); Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange( CondOp->getLHS()->getBeginLoc(), BeforeRHS)); } else { - SourceLocation AfterLHS = + const SourceLocation AfterLHS = Lexer::findNextToken(CondOp->getLHS()->getEndLoc(), *Result.SourceManager, getLangOpts()) ->getLocation(); diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp index a3265293bef58..1107cefe4d3c6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp @@ -83,7 +83,7 @@ static const Decl *findRVRefOverload(const FunctionDecl &FD, // FIXME: // 1. overload in anonymous namespace // 2. forward reference - DeclContext::lookup_result LookupResult = + const DeclContext::lookup_result LookupResult = FD.getParent()->lookup(FD.getNameInfo().getName()); if (LookupResult.isSingleResult()) { return nullptr; diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp index c262b1c05b047..b9a0b9ee3a6c6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp @@ -283,7 +283,7 @@ static bool isStandardFunction(const FunctionDecl *FD) { /// This includes all statements that have a class name with "CXX" prefix /// and every other statement that is declared in file ExprCXX.h. static bool isCXXOnlyStmt(const Stmt *S) { - StringRef Name = S->getStmtClassName(); + const StringRef Name = S->getStmtClassName(); if (Name.starts_with("CXX")) return true; // Check for all other class names in ExprCXX.h that have no 'CXX' prefix. @@ -317,7 +317,7 @@ static SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { ParentMapContext &PM = Ctx.getParentMapContext(); DynTypedNode P = DynTypedNode::create(*S); while (P.getSourceRange().isInvalid()) { - DynTypedNodeList PL = PM.getParents(P); + const DynTypedNodeList PL = PM.getParents(P); if (PL.size() != 1) return {}; P = PL[0]; @@ -401,14 +401,15 @@ void SignalHandlerCheck::check(const MatchFinder::MatchResult &Result) { } // FIXME: Update CallGraph::getNode to use canonical decl? - CallGraphNode *HandlerNode = CG.getNode(HandlerDecl->getCanonicalDecl()); + const CallGraphNode *HandlerNode = + CG.getNode(HandlerDecl->getCanonicalDecl()); assert(HandlerNode && "Handler with body should be present in the call graph."); // Start from signal handler and visit every function call. auto Itr = llvm::df_begin(HandlerNode), ItrE = llvm::df_end(HandlerNode); while (Itr != ItrE) { const auto *CallF = dyn_cast((*Itr)->getDecl()); - unsigned int PathL = Itr.getPathLength(); + const unsigned int PathL = Itr.getPathLength(); if (CallF) { // A signal handler or a function transitively reachable from the signal // handler was found to be unsafe. @@ -435,7 +436,7 @@ void SignalHandlerCheck::check(const MatchFinder::MatchResult &Result) { bool SignalHandlerCheck::checkFunction( const FunctionDecl *FD, const Expr *CallOrRef, std::function ChainReporter) { - bool FunctionIsCalled = isa(CallOrRef); + const bool FunctionIsCalled = isa(CallOrRef); if (isStandardFunction(FD)) { if (!isStandardFunctionAsyncSafe(FD)) { @@ -492,7 +493,7 @@ bool SignalHandlerCheck::checkFunctionCPP14( for (const auto &Match : Matches) { const auto *FoundS = Match.getNodeAs("stmt"); if (isCXXOnlyStmt(FoundS)) { - SourceRange R = getSourceRangeOfStmt(FoundS, Ctx); + const SourceRange R = getSourceRangeOfStmt(FoundS, Ctx); if (R.isInvalid()) continue; diag(R.getBegin(), @@ -531,7 +532,7 @@ bool SignalHandlerCheck::isStandardFunctionAsyncSafe( } void SignalHandlerCheck::reportHandlerChain( - const llvm::df_iterator &Itr, + const llvm::df_iterator &Itr, const DeclRefExpr *HandlerRef, bool SkipPathEnd) { int CallLevel = Itr.getPathLength() - 2; assert(CallLevel >= -1 && "Empty iterator?"); diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h index b5317793cbf45..67bdc9e292764 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h @@ -65,8 +65,9 @@ class SignalHandlerCheck : public ClangTidyCheck { /// registered as signal handler. /// @param SkipPathEnd If true the last item of the call chain (farthest away /// from the \c signal call) is omitted from note generation. - void reportHandlerChain(const llvm::df_iterator &Itr, - const DeclRefExpr *HandlerRef, bool SkipPathEnd); + void + reportHandlerChain(const llvm::df_iterator &Itr, + const DeclRefExpr *HandlerRef, bool SkipPathEnd); clang::CallGraph CG; diff --git a/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp index 742d85bb7bab9..31c5413b8aa4c 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp @@ -140,7 +140,7 @@ void SignedCharMisuseCheck::check(const MatchFinder::MatchResult &Result) { if (!SignedCastExpression->isValueDependent() && SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, *Result.Context)) { - llvm::APSInt Value = EVResult.Val.getInt(); + const llvm::APSInt Value = EVResult.Val.getInt(); if (Value.isNonNegative()) return; } @@ -154,7 +154,7 @@ void SignedCharMisuseCheck::check(const MatchFinder::MatchResult &Result) { if (!UnSignedCastExpression->isValueDependent() && UnSignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, *Result.Context)) { - llvm::APSInt Value = EVResult.Val.getInt(); + const llvm::APSInt Value = EVResult.Val.getInt(); if (Value <= UnsignedASCIIUpperBound) return; } diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp index 2672dc74f82f7..49ba3b83795dd 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp @@ -407,9 +407,9 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { const auto *ElementTy = Result.Nodes.getNodeAs("elem-type"); const auto *PointedTy = Result.Nodes.getNodeAs("elem-ptr-type"); - CharUnits NumeratorSize = getSizeOfType(Ctx, NumTy); - CharUnits DenominatorSize = getSizeOfType(Ctx, DenomTy); - CharUnits ElementSize = getSizeOfType(Ctx, ElementTy); + const CharUnits NumeratorSize = getSizeOfType(Ctx, NumTy); + const CharUnits DenominatorSize = getSizeOfType(Ctx, DenomTy); + const CharUnits ElementSize = getSizeOfType(Ctx, ElementTy); if (DenominatorSize > CharUnits::Zero() && !NumeratorSize.isMultipleOf(DenominatorSize)) { diff --git a/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp index f76e4a722a508..af478b105fdd1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp @@ -93,10 +93,10 @@ void SmartPtrArrayMismatchCheck::check(const MatchFinder::MatchResult &Result) { assert(TSTypeLoc.getNumArgs() >= 1 && "Matched type should have at least 1 template argument."); - SourceRange TemplateArgumentRange = TSTypeLoc.getArgLoc(0) - .getTypeSourceInfo() - ->getTypeLoc() - .getSourceRange(); + const SourceRange TemplateArgumentRange = TSTypeLoc.getArgLoc(0) + .getTypeSourceInfo() + ->getTypeLoc() + .getSourceRange(); D << TemplateArgumentRange; if (isInSingleDeclStmt(VarOrField)) { @@ -104,7 +104,7 @@ void SmartPtrArrayMismatchCheck::check(const MatchFinder::MatchResult &Result) { if (!utils::rangeCanBeFixed(TemplateArgumentRange, &SM)) return; - SourceLocation InsertLoc = Lexer::getLocForEndOfToken( + const SourceLocation InsertLoc = Lexer::getLocForEndOfToken( TemplateArgumentRange.getEnd(), 0, SM, Ctx.getLangOpts()); D << FixItHint::CreateInsertion(InsertLoc, "[]"); } diff --git a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp index 1e8058bc4abc9..a093b094de4c7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp @@ -77,7 +77,7 @@ void SpuriouslyWakeUpFunctionsCheck::registerMatchers(MatchFinder *Finder) { void SpuriouslyWakeUpFunctionsCheck::check( const MatchFinder::MatchResult &Result) { const auto *MatchedWait = Result.Nodes.getNodeAs("wait"); - StringRef WaitName = MatchedWait->getDirectCallee()->getName(); + const StringRef WaitName = MatchedWait->getDirectCallee()->getName(); diag(MatchedWait->getExprLoc(), "'%0' should be placed inside a while statement %select{|or used with a " "conditional parameter}1") diff --git a/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp index a7958cc229ffe..056ae4b80f109 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp @@ -117,12 +117,13 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { if (ParentReturnStmt) return; - SourceLocation MemberLoc = MemberCall->getBeginLoc(); - SourceLocation ReplacementLoc = MemberCall->getExprLoc(); - SourceRange ReplacementRange = SourceRange(ReplacementLoc, ReplacementLoc); + const SourceLocation MemberLoc = MemberCall->getBeginLoc(); + const SourceLocation ReplacementLoc = MemberCall->getExprLoc(); + const SourceRange ReplacementRange = + SourceRange(ReplacementLoc, ReplacementLoc); ASTContext &Context = MemberCall->getRecordDecl()->getASTContext(); - DeclarationName Name = + const DeclarationName Name = Context.DeclarationNames.getIdentifier(&Context.Idents.get("clear")); auto Candidates = HeuristicResolver(Context).lookupDependentName( @@ -133,11 +134,12 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { !llvm::cast(ND)->isConst(); }); - bool HasClear = !Candidates.empty(); + const bool HasClear = !Candidates.empty(); if (HasClear) { const auto *Clear = llvm::cast(Candidates.at(0)); - QualType RangeType = MemberCall->getImplicitObjectArgument()->getType(); - bool QualifierIncompatible = + const QualType RangeType = + MemberCall->getImplicitObjectArgument()->getType(); + const bool QualifierIncompatible = (!Clear->isVolatile() && RangeType.isVolatileQualified()) || RangeType.isConstQualified(); if (!QualifierIncompatible) { @@ -162,8 +164,8 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { if (NonMemberCall->getNumArgs() != 1) return; - SourceLocation NonMemberLoc = NonMemberCall->getExprLoc(); - SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc(); + const SourceLocation NonMemberLoc = NonMemberCall->getExprLoc(); + const SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc(); const Expr *Arg = NonMemberCall->getArg(0); CXXRecordDecl *ArgRecordDecl = Arg->getType()->getAsCXXRecordDecl(); @@ -171,7 +173,7 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { return; ASTContext &Context = ArgRecordDecl->getASTContext(); - DeclarationName Name = + const DeclarationName Name = Context.DeclarationNames.getIdentifier(&Context.Idents.get("clear")); auto Candidates = HeuristicResolver(Context).lookupDependentName( @@ -182,20 +184,20 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { !llvm::cast(ND)->isConst(); }); - bool HasClear = !Candidates.empty(); + const bool HasClear = !Candidates.empty(); if (HasClear) { const auto *Clear = llvm::cast(Candidates.at(0)); - bool QualifierIncompatible = + const bool QualifierIncompatible = (!Clear->isVolatile() && Arg->getType().isVolatileQualified()) || Arg->getType().isConstQualified(); if (!QualifierIncompatible) { - std::string ReplacementText = + const std::string ReplacementText = std::string(Lexer::getSourceText( CharSourceRange::getTokenRange(Arg->getSourceRange()), *Result.SourceManager, getLangOpts())) + ".clear()"; - SourceRange ReplacementRange = + const SourceRange ReplacementRange = SourceRange(NonMemberLoc, NonMemberEndLoc); diag(NonMemberLoc, "ignoring the result of '%0'; did you mean 'clear()'?") diff --git a/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp index 13e5c03d7c4d3..1dff741be3c08 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp @@ -20,12 +20,12 @@ AST_POLYMORPHIC_MATCHER_P( AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), clang::ast_matchers::internal::Matcher, InnerMatcher) { - ArrayRef Args = + const ArrayRef Args = clang::ast_matchers::internal::getTemplateSpecializationArgs(Node); for (const auto &Arg : Args) { if (Arg.getKind() != TemplateArgument::Pack) continue; - ArrayRef PackArgs = Arg.getPackAsArray(); + const ArrayRef PackArgs = Arg.getPackAsArray(); if (matchesFirstInRange(InnerMatcher, PackArgs.begin(), PackArgs.end(), Finder, Builder) != PackArgs.end()) return true; diff --git a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp index 832377e376feb..d2e631e539b78 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp @@ -29,8 +29,8 @@ static std::vector removeNamespaces(const std::vector &Names) { std::vector Result; Result.reserve(Names.size()); - for (StringRef Name : Names) { - std::string::size_type ColonPos = Name.rfind(':'); + for (const StringRef Name : Names) { + const std::string::size_type ColonPos = Name.rfind(':'); Result.push_back( Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1)); } @@ -168,7 +168,7 @@ void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) { const ASTContext &Ctx = *Result.Context; const auto *E = Result.Nodes.getNodeAs("constructor"); assert(E && "missing constructor expression"); - SourceLocation Loc = E->getBeginLoc(); + const SourceLocation Loc = E->getBeginLoc(); if (Result.Nodes.getNodeAs("swapped-parameter")) { const Expr *P0 = E->getArg(0); From ace77c25a4926899006d76ca87fc6d50da8baae1 Mon Sep 17 00:00:00 2001 From: Baranov Victor Date: Sat, 8 Nov 2025 19:27:21 +0300 Subject: [PATCH 18/18] [clang-tidy][NFC] Fix misc-const-correctness warnings (9/N) (#167124) --- .../readability/NamedParameterCheck.cpp | 6 +-- .../readability/NamespaceCommentCheck.cpp | 22 ++++---- .../readability/NonConstParameterCheck.cpp | 2 +- .../OperatorsRepresentationCheck.cpp | 16 +++--- .../readability/QualifiedAutoCheck.cpp | 37 ++++++------- .../RedundantAccessSpecifiersCheck.cpp | 2 +- .../readability/RedundantCastingCheck.cpp | 4 +- .../readability/RedundantControlFlowCheck.cpp | 9 ++-- .../readability/RedundantDeclarationCheck.cpp | 2 +- .../RedundantInlineSpecifierCheck.cpp | 4 +- .../RedundantPreprocessorCheck.cpp | 6 +-- .../readability/RedundantSmartptrGetCheck.cpp | 8 +-- .../readability/RedundantStringCStrCheck.cpp | 4 +- .../readability/RedundantStringInitCheck.cpp | 8 +-- .../ReferenceToConstructedTemporaryCheck.cpp | 2 +- .../readability/SimplifyBooleanExprCheck.cpp | 51 +++++++++--------- ...ticDefinitionInAnonymousNamespaceCheck.cpp | 4 +- .../SuspiciousCallArgumentCheck.cpp | 52 +++++++++---------- .../UppercaseLiteralSuffixCheck.cpp | 2 +- .../readability/UseAnyOfAllOfCheck.cpp | 2 +- .../readability/UseStdMinMaxCheck.cpp | 10 ++-- 21 files changed, 130 insertions(+), 123 deletions(-) diff --git a/clang-tools-extra/clang-tidy/readability/NamedParameterCheck.cpp b/clang-tools-extra/clang-tidy/readability/NamedParameterCheck.cpp index 7251d63edfd89..1283632a91bb1 100644 --- a/clang-tools-extra/clang-tidy/readability/NamedParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NamedParameterCheck.cpp @@ -79,7 +79,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) { // void foo(int /*unused*/) const char *Begin = SM.getCharacterData(Parm->getBeginLoc()); const char *End = SM.getCharacterData(Parm->getLocation()); - StringRef Data(Begin, End - Begin); + const StringRef Data(Begin, End - Begin); if (Data.contains("/*")) continue; @@ -104,7 +104,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) { if (M && M->size_overridden_methods() > 0) { const ParmVarDecl *OtherParm = (*M->begin_overridden_methods())->getParamDecl(P.second); - StringRef Name = OtherParm->getName(); + const StringRef Name = OtherParm->getName(); if (!Name.empty()) NewName = Name; } @@ -112,7 +112,7 @@ void NamedParameterCheck::check(const MatchFinder::MatchResult &Result) { // If the definition has a named parameter use that name. if (Definition) { const ParmVarDecl *DefParm = Definition->getParamDecl(P.second); - StringRef Name = DefParm->getName(); + const StringRef Name = DefParm->getName(); if (!Name.empty()) NewName = Name; } diff --git a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp index 744d23a6fdbcd..dffd7fdcc1beb 100644 --- a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp @@ -70,7 +70,7 @@ getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources, --Nesting; } else if (Nesting == 0) { if (T->is(tok::raw_identifier)) { - StringRef ID = T->getRawIdentifier(); + const StringRef ID = T->getRawIdentifier(); if (ID != "namespace") Result.append(std::string(ID)); if (ID == "inline") @@ -96,13 +96,13 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { // Don't require closing comments for namespaces spanning less than certain // number of lines. - unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc()); - unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc()); + const unsigned StartLine = Sources.getSpellingLineNumber(ND->getBeginLoc()); + const unsigned EndLine = Sources.getSpellingLineNumber(ND->getRBraceLoc()); if (EndLine - StartLine + 1 <= ShortNamespaceLines) return; // Find next token after the namespace closing brace. - SourceLocation AfterRBrace = Lexer::getLocForEndOfToken( + const SourceLocation AfterRBrace = Lexer::getLocForEndOfToken( ND->getRBraceLoc(), /*Offset=*/0, Sources, getLangOpts()); SourceLocation Loc = AfterRBrace; SourceLocation LBraceLoc = ND->getBeginLoc(); @@ -137,7 +137,8 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { if (!locationsInSameFile(Sources, ND->getRBraceLoc(), Loc)) return; - bool NextTokenIsOnSameLine = Sources.getSpellingLineNumber(Loc) == EndLine; + const bool NextTokenIsOnSameLine = + Sources.getSpellingLineNumber(Loc) == EndLine; // If we insert a line comment before the token in the same line, we need // to insert a line break. bool NeedLineBreak = NextTokenIsOnSameLine && Tok.isNot(tok::eof); @@ -148,11 +149,12 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { // Try to find existing namespace closing comment on the same line. if (Tok.is(tok::comment) && NextTokenIsOnSameLine) { - StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength()); + const StringRef Comment(Sources.getCharacterData(Loc), Tok.getLength()); SmallVector Groups; if (NamespaceCommentPattern.match(Comment, &Groups)) { - StringRef NamespaceNameInComment = Groups.size() > 5 ? Groups[5] : ""; - StringRef Anonymous = Groups.size() > 3 ? Groups[3] : ""; + const StringRef NamespaceNameInComment = + Groups.size() > 5 ? Groups[5] : ""; + const StringRef Anonymous = Groups.size() > 3 ? Groups[3] : ""; if ((ND->isAnonymousNamespace() && NamespaceNameInComment.empty()) || (*NamespaceNameAsWritten == NamespaceNameInComment && @@ -186,7 +188,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { // multi-line or there may be other tokens behind it. } - std::string NamespaceNameForDiag = + const std::string NamespaceNameForDiag = ND->isAnonymousNamespace() ? "anonymous namespace" : ("namespace '" + *NamespaceNameAsWritten + "'"); @@ -203,7 +205,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { Fix.append("\n"); // Place diagnostic at an old comment, or closing brace if we did not have it. - SourceLocation DiagLoc = + const SourceLocation DiagLoc = OldCommentRange.getBegin() != OldCommentRange.getEnd() ? OldCommentRange.getBegin() : ND->getRBraceLoc(); diff --git a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp index 29fff3971599e..9fbe3badc864b 100644 --- a/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp @@ -155,7 +155,7 @@ void NonConstParameterCheck::diagnoseNonConstParameters() { dyn_cast_or_null(Par->getParentFunctionOrMethod()); if (!Function) continue; - unsigned Index = Par->getFunctionScopeIndex(); + const unsigned Index = Par->getFunctionScopeIndex(); for (FunctionDecl *FnDecl : Function->redecls()) { if (FnDecl->getNumParams() <= Index) continue; diff --git a/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp b/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp index 196fb31bd4b7a..4260e0fc41754 100644 --- a/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp @@ -23,7 +23,7 @@ static StringRef getOperatorSpelling(SourceLocation Loc, ASTContext &Context) { if (Loc.isInvalid()) return {}; - SourceManager &SM = Context.getSourceManager(); + const SourceManager &SM = Context.getSourceManager(); Loc = SM.getSpellingLoc(Loc); if (Loc.isInvalid()) @@ -41,7 +41,7 @@ AST_MATCHER_P2(BinaryOperator, hasInvalidBinaryOperatorRepresentation, if (Node.getOpcode() != Kind || ExpectedRepresentation.empty()) return false; - StringRef Spelling = + const StringRef Spelling = getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext()); return !Spelling.empty() && Spelling != ExpectedRepresentation; } @@ -52,7 +52,7 @@ AST_MATCHER_P2(UnaryOperator, hasInvalidUnaryOperatorRepresentation, if (Node.getOpcode() != Kind || ExpectedRepresentation.empty()) return false; - StringRef Spelling = + const StringRef Spelling = getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext()); return !Spelling.empty() && Spelling != ExpectedRepresentation; } @@ -63,7 +63,7 @@ AST_MATCHER_P2(CXXOperatorCallExpr, hasInvalidOverloadedOperatorRepresentation, if (Node.getOperator() != Kind || ExpectedRepresentation.empty()) return false; - StringRef Spelling = + const StringRef Spelling = getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext()); return !Spelling.empty() && Spelling != ExpectedRepresentation; } @@ -297,9 +297,9 @@ void OperatorsRepresentationCheck::check( if (TokenRange.isInvalid()) return; - StringRef Spelling = Lexer::getSourceText(TokenRange, *Result.SourceManager, - Result.Context->getLangOpts()); - StringRef TranslatedSpelling = translate(Spelling); + const StringRef Spelling = Lexer::getSourceText( + TokenRange, *Result.SourceManager, Result.Context->getLangOpts()); + const StringRef TranslatedSpelling = translate(Spelling); if (TranslatedSpelling.empty()) return; @@ -312,7 +312,7 @@ void OperatorsRepresentationCheck::check( SourceRepresentation = "a traditional"; TargetRepresentation = "an alternative"; - StringRef SpellingEx = Lexer::getSourceText( + const StringRef SpellingEx = Lexer::getSourceText( CharSourceRange::getCharRange( TokenRange.getBegin().getLocWithOffset(-1), TokenRange.getBegin().getLocWithOffset(Spelling.size() + 1U)), diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp index a8a6d350a70a3..556f7fe7a7eb9 100644 --- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -44,18 +44,18 @@ findQualToken(const VarDecl *Decl, Qualifier Qual, SourceLocation BeginLoc = Decl->getQualifierLoc().getBeginLoc(); if (BeginLoc.isInvalid()) BeginLoc = Decl->getBeginLoc(); - SourceLocation EndLoc = Decl->getLocation(); + const SourceLocation EndLoc = Decl->getLocation(); - CharSourceRange FileRange = Lexer::makeFileCharRange( + const CharSourceRange FileRange = Lexer::makeFileCharRange( CharSourceRange::getCharRange(BeginLoc, EndLoc), *Result.SourceManager, Result.Context->getLangOpts()); if (FileRange.isInvalid()) return std::nullopt; - tok::TokenKind Tok = Qual == Qualifier::Const ? tok::kw_const - : Qual == Qualifier::Volatile ? tok::kw_volatile - : tok::kw_restrict; + const tok::TokenKind Tok = Qual == Qualifier::Const ? tok::kw_const + : Qual == Qualifier::Volatile ? tok::kw_volatile + : tok::kw_restrict; return utils::lexer::getQualifyingToken(Tok, FileRange, *Result.Context, *Result.SourceManager); @@ -90,13 +90,13 @@ mergeReplacementRange(SourceRange &TypeSpecifier, const Token &ConstToken) { } static bool isPointerConst(QualType QType) { - QualType Pointee = QType->getPointeeType(); + const QualType Pointee = QType->getPointeeType(); assert(!Pointee.isNull() && "can't have a null Pointee"); return Pointee.isConstQualified(); } static bool isAutoPointerConst(QualType QType) { - QualType Pointee = + const QualType Pointee = cast(QType->getPointeeType().getTypePtr())->desugar(); assert(!Pointee.isNull() && "can't have a null Pointee"); return Pointee.isConstQualified(); @@ -222,33 +222,34 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) { if (Var->getLocation() == TypeSpecifier.getEnd().getLocWithOffset(1)) TypeSpecifier.setEnd(TypeSpecifier.getEnd().getLocWithOffset(1)); - CharSourceRange FixItRange = CharSourceRange::getCharRange(TypeSpecifier); + const CharSourceRange FixItRange = + CharSourceRange::getCharRange(TypeSpecifier); if (FixItRange.isInvalid()) return; SourceLocation FixitLoc = FixItRange.getBegin(); - for (SourceRange &Range : RemoveQualifiersRange) { + for (const SourceRange &Range : RemoveQualifiersRange) { if (Range.getBegin() < FixitLoc) FixitLoc = Range.getBegin(); } - std::string ReplStr = [&] { - llvm::StringRef PtrConst = isPointerConst(Var->getType()) ? "const " : ""; - llvm::StringRef LocalConst = IsLocalConst ? "const " : ""; - llvm::StringRef LocalVol = IsLocalVolatile ? "volatile " : ""; - llvm::StringRef LocalRestrict = IsLocalRestrict ? "__restrict " : ""; + const std::string ReplStr = [&] { + const StringRef PtrConst = isPointerConst(Var->getType()) ? "const " : ""; + const StringRef LocalConst = IsLocalConst ? "const " : ""; + const StringRef LocalVol = IsLocalVolatile ? "volatile " : ""; + const StringRef LocalRestrict = IsLocalRestrict ? "__restrict " : ""; return (PtrConst + "auto *" + LocalConst + LocalVol + LocalRestrict) .str(); }(); - DiagnosticBuilder Diag = + const DiagnosticBuilder Diag = diag(FixitLoc, "'%select{|const }0%select{|volatile }1%select{|__restrict }2auto " "%3' can be declared as '%4%3'") << IsLocalConst << IsLocalVolatile << IsLocalRestrict << Var->getName() << ReplStr; - for (SourceRange &Range : RemoveQualifiersRange) { + for (const SourceRange &Range : RemoveQualifiersRange) { Diag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(Range)); } @@ -285,7 +286,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) { if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() || TypeSpec->getEnd().isMacroID()) return; - SourceLocation InsertPos = TypeSpec->getBegin(); + const SourceLocation InsertPos = TypeSpec->getBegin(); diag(InsertPos, "'auto *%select{|const }0%select{|volatile }1%2' can be declared as " "'const auto *%select{|const }0%select{|volatile }1%2'") @@ -307,7 +308,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) { if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() || TypeSpec->getEnd().isMacroID()) return; - SourceLocation InsertPos = TypeSpec->getBegin(); + const SourceLocation InsertPos = TypeSpec->getBegin(); diag(InsertPos, "'auto &%0' can be declared as 'const auto &%0'") << Var->getName() << FixItHint::CreateInsertion(InsertPos, "const "); } diff --git a/clang-tools-extra/clang-tidy/readability/RedundantAccessSpecifiersCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantAccessSpecifiersCheck.cpp index e93aa16ebdb13..14580a6a26809 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantAccessSpecifiersCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantAccessSpecifiersCheck.cpp @@ -43,7 +43,7 @@ void RedundantAccessSpecifiersCheck::check( LastASDecl = ASDecl; if (CheckFirstDeclaration) { - AccessSpecifier DefaultSpecifier = + const AccessSpecifier DefaultSpecifier = MatchedDecl->isClass() ? AS_private : AS_public; if (ASDecl->getAccess() == DefaultSpecifier) { diag(ASDecl->getLocation(), diff --git a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp index 1ee75220b1c4e..d11c41c33d2be 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp @@ -25,8 +25,8 @@ static bool areTypesEqual(QualType S, QualType D) { if (TS != TD) return false; - QualType PtrS = S->getPointeeType(); - QualType PtrD = D->getPointeeType(); + const QualType PtrS = S->getPointeeType(); + const QualType PtrD = D->getPointeeType(); if (!PtrS.isNull() && !PtrD.isNull()) return areTypesEqual(PtrS, PtrD); diff --git a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp index b3b84e2cc0ccd..132b7ddc4311b 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp @@ -50,7 +50,7 @@ void RedundantControlFlowCheck::check(const MatchFinder::MatchResult &Result) { void RedundantControlFlowCheck::checkRedundantReturn( const MatchFinder::MatchResult &Result, const CompoundStmt *Block) { - CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin(); + const CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin(); if (const auto *Return = dyn_cast(*Last)) issueDiagnostic(Result, Block, Return->getSourceRange(), RedundantReturnDiag); @@ -58,7 +58,7 @@ void RedundantControlFlowCheck::checkRedundantReturn( void RedundantControlFlowCheck::checkRedundantContinue( const MatchFinder::MatchResult &Result, const CompoundStmt *Block) { - CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin(); + const CompoundStmt::const_reverse_body_iterator Last = Block->body_rbegin(); if (const auto *Continue = dyn_cast(*Last)) issueDiagnostic(Result, Block, Continue->getSourceRange(), RedundantContinueDiag); @@ -67,11 +67,12 @@ void RedundantControlFlowCheck::checkRedundantContinue( void RedundantControlFlowCheck::issueDiagnostic( const MatchFinder::MatchResult &Result, const CompoundStmt *const Block, const SourceRange &StmtRange, const char *const Diag) { - SourceManager &SM = *Result.SourceManager; + const SourceManager &SM = *Result.SourceManager; if (isLocationInMacroExpansion(SM, StmtRange.getBegin())) return; - CompoundStmt::const_reverse_body_iterator Previous = ++Block->body_rbegin(); + const CompoundStmt::const_reverse_body_iterator Previous = + ++Block->body_rbegin(); SourceLocation Start; if (Previous != Block->body_rend()) Start = Lexer::findLocationAfterToken( diff --git a/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp index cf6e92d84e92a..0f12b8bcea6fb 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp @@ -79,7 +79,7 @@ void RedundantDeclarationCheck::check(const MatchFinder::MatchResult &Result) { } } - SourceLocation EndLoc = Lexer::getLocForEndOfToken( + const SourceLocation EndLoc = Lexer::getLocForEndOfToken( D->getSourceRange().getEnd(), 0, SM, Result.Context->getLangOpts()); { auto Diag = diag(D->getLocation(), "redundant %0 declaration") << D; diff --git a/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp index 2053b89ada7e2..76adaa80207da 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp @@ -52,7 +52,7 @@ AST_POLYMORPHIC_MATCHER_P(isInternalLinkage, static SourceLocation getInlineTokenLocation(SourceRange RangeLocation, const SourceManager &Sources, const LangOptions &LangOpts) { - SourceLocation Loc = RangeLocation.getBegin(); + const SourceLocation Loc = RangeLocation.getBegin(); if (Loc.isMacroID()) return {}; @@ -106,7 +106,7 @@ template void RedundantInlineSpecifierCheck::handleMatchedDecl( const T *MatchedDecl, const SourceManager &Sources, const MatchFinder::MatchResult &Result, StringRef Message) { - SourceLocation Loc = getInlineTokenLocation( + const SourceLocation Loc = getInlineTokenLocation( MatchedDecl->getSourceRange(), Sources, Result.Context->getLangOpts()); if (Loc.isValid()) diag(Loc, Message) << MatchedDecl << FixItHint::CreateRemoval(Loc); diff --git a/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp index 931126a154d1e..4c503714346f8 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp @@ -36,7 +36,7 @@ class RedundantPreprocessorCallbacks : public PPCallbacks { void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) override { - StringRef Condition = + const StringRef Condition = Lexer::getSourceText(CharSourceRange::getTokenRange(ConditionRange), PP.getSourceManager(), PP.getLangOpts()); checkMacroRedundancy(Loc, Condition, IfStack, DK_If, DK_If, true); @@ -44,7 +44,7 @@ class RedundantPreprocessorCallbacks : public PPCallbacks { void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MacroDefinition) override { - std::string MacroName = PP.getSpelling(MacroNameTok); + const std::string MacroName = PP.getSpelling(MacroNameTok); checkMacroRedundancy(Loc, MacroName, IfdefStack, DK_Ifdef, DK_Ifdef, true); checkMacroRedundancy(Loc, MacroName, IfndefStack, DK_Ifdef, DK_Ifndef, false); @@ -52,7 +52,7 @@ class RedundantPreprocessorCallbacks : public PPCallbacks { void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MacroDefinition) override { - std::string MacroName = PP.getSpelling(MacroNameTok); + const std::string MacroName = PP.getSpelling(MacroNameTok); checkMacroRedundancy(Loc, MacroName, IfndefStack, DK_Ifndef, DK_Ifndef, true); checkMacroRedundancy(Loc, MacroName, IfdefStack, DK_Ifndef, DK_Ifdef, diff --git a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp index 11065230edc60..a458ae3ebc20d 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp @@ -149,8 +149,9 @@ void RedundantSmartptrGetCheck::check(const MatchFinder::MatchResult &Result) { if (!allReturnTypesMatch(Result)) return; - bool IsPtrToPtr = Result.Nodes.getNodeAs("ptr_to_ptr") != nullptr; - bool IsMemberExpr = Result.Nodes.getNodeAs("memberExpr") != nullptr; + const bool IsPtrToPtr = Result.Nodes.getNodeAs("ptr_to_ptr") != nullptr; + const bool IsMemberExpr = + Result.Nodes.getNodeAs("memberExpr") != nullptr; const auto *GetCall = Result.Nodes.getNodeAs("redundant_get"); if (GetCall->getBeginLoc().isMacroID() && IgnoreMacros) return; @@ -178,7 +179,8 @@ void RedundantSmartptrGetCheck::check(const MatchFinder::MatchResult &Result) { SmartptrText = SmartptrText.drop_back(2); } // Replace foo->get() with *foo, and foo.get() with foo. - std::string Replacement = Twine(IsPtrToPtr ? "*" : "", SmartptrText).str(); + const std::string Replacement = + Twine(IsPtrToPtr ? "*" : "", SmartptrText).str(); diag(GetCall->getBeginLoc(), "redundant get() call on smart pointer") << FixItHint::CreateReplacement(SR, Replacement); } diff --git a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp index c90d1521e6b8d..e4d08cbf0d282 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp @@ -171,10 +171,10 @@ void RedundantStringCStrCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs("call"); const auto *Arg = Result.Nodes.getNodeAs("arg"); const auto *Member = Result.Nodes.getNodeAs("member"); - bool Arrow = Member->isArrow(); + const bool Arrow = Member->isArrow(); // Replace the "call" node with the "arg" node, prefixed with '*' // if the call was using '->' rather than '.'. - std::string ArgText = + const std::string ArgText = Arrow ? utils::fixit::formatDereference(*Arg, *Result.Context) : tooling::fixit::getText(*Arg, *Result.Context).str(); if (ArgText.empty()) diff --git a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp index b579aafe8ea43..756fe437b3e10 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp @@ -23,8 +23,8 @@ const char DefaultStringNames[] = static std::vector removeNamespaces(ArrayRef Names) { std::vector Result; Result.reserve(Names.size()); - for (StringRef Name : Names) { - StringRef::size_type ColonPos = Name.rfind(':'); + for (const StringRef Name : Names) { + const StringRef::size_type ColonPos = Name.rfind(':'); Result.push_back( Name.drop_front(ColonPos == StringRef::npos ? 0 : ColonPos + 1)); } @@ -125,14 +125,14 @@ void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *VDecl = Result.Nodes.getNodeAs("vardecl")) { // VarDecl's getSourceRange() spans 'string foo = ""' or 'string bar("")'. // So start at getLocation() to span just 'foo = ""' or 'bar("")'. - SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc()); + const SourceRange ReplaceRange(VDecl->getLocation(), VDecl->getEndLoc()); diag(VDecl->getLocation(), "redundant string initialization") << FixItHint::CreateReplacement(ReplaceRange, VDecl->getName()); } if (const auto *FDecl = Result.Nodes.getNodeAs("fieldDecl")) { // FieldDecl's getSourceRange() spans 'string foo = ""'. // So start at getLocation() to span just 'foo = ""'. - SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc()); + const SourceRange ReplaceRange(FDecl->getLocation(), FDecl->getEndLoc()); diag(FDecl->getLocation(), "redundant string initialization") << FixItHint::CreateReplacement(ReplaceRange, FDecl->getName()); } diff --git a/clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.cpp b/clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.cpp index 5d3fd14b92471..398bee1d40923 100644 --- a/clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.cpp @@ -37,7 +37,7 @@ struct NotExtendedByDeclBoundToPredicate { AST_MATCHER_P(MaterializeTemporaryExpr, isExtendedByDeclBoundTo, StringRef, ID) { - NotExtendedByDeclBoundToPredicate Predicate{ + const NotExtendedByDeclBoundToPredicate Predicate{ ID, ::clang::DynTypedNode::create(Node)}; return Builder->removeBindings(Predicate); } diff --git a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp index 9f3f26b775c9a..1a9c161068030 100644 --- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp @@ -203,7 +203,7 @@ static std::string replacementExpression(const ASTContext &Context, .str(), NeedsStaticCast)); - StringRef Text = getText(Context, *E); + const StringRef Text = getText(Context, *E); if (!NeedsStaticCast && needsParensAfterUnaryNegation(E)) return ("!(" + Text + ")").str(); @@ -366,7 +366,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { * if (false) ThenStmt(); -> ; * if (false) ThenStmt(); else ElseStmt() -> ElseStmt(); */ - Expr *Cond = If->getCond()->IgnoreImplicit(); + const Expr *Cond = If->getCond()->IgnoreImplicit(); if (std::optional Bool = getAsBoolLiteral(Cond, true)) { if (*Bool) Check->replaceWithThenStatement(Context, If, Cond); @@ -379,9 +379,9 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { * if (Cond) return true; else return false; -> return Cond; * if (Cond) return false; else return true; -> return !Cond; */ - if (ExprAndBool ThenReturnBool = + if (const ExprAndBool ThenReturnBool = checkSingleStatement(If->getThen(), parseReturnLiteralBool)) { - ExprAndBool ElseReturnBool = + const ExprAndBool ElseReturnBool = checkSingleStatement(If->getElse(), parseReturnLiteralBool); if (ElseReturnBool && ThenReturnBool.Bool != ElseReturnBool.Bool) { if (Check->ChainedConditionalReturn || @@ -418,9 +418,9 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { return {ME->getMemberDecl(), *RightasBool}; return {}; }; - if (DeclAndBool ThenAssignment = + if (const DeclAndBool ThenAssignment = checkSingleStatement(If->getThen(), VarBoolAssignmentMatcher)) { - DeclAndBool ElseAssignment = + const DeclAndBool ElseAssignment = checkSingleStatement(If->getElse(), VarBoolAssignmentMatcher); if (ElseAssignment.Item == ThenAssignment.Item && ElseAssignment.Bool != ThenAssignment.Bool) { @@ -461,7 +461,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { Second != End; ++Second, ++First) { PrevIf = CurIf; CurIf = isa(*First); - ExprAndBool TrailingReturnBool = parseReturnLiteralBool(*Second); + const ExprAndBool TrailingReturnBool = parseReturnLiteralBool(*Second); if (!TrailingReturnBool) continue; @@ -473,7 +473,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { auto *If = cast(*First); if (!If->hasInitStorage() && !If->hasVarStorage() && !If->isConsteval()) { - ExprAndBool ThenReturnBool = + const ExprAndBool ThenReturnBool = checkSingleStatement(If->getThen(), parseReturnLiteralBool); if (ThenReturnBool && ThenReturnBool.Bool != TrailingReturnBool.Bool) { @@ -497,7 +497,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { auto *SubIf = dyn_cast(SubStmt); if (SubIf && !SubIf->getElse() && !SubIf->hasInitStorage() && !SubIf->hasVarStorage() && !SubIf->isConsteval()) { - ExprAndBool ThenReturnBool = + const ExprAndBool ThenReturnBool = checkSingleStatement(SubIf->getThen(), parseReturnLiteralBool); if (ThenReturnBool && ThenReturnBool.Bool != TrailingReturnBool.Bool) { @@ -574,7 +574,7 @@ class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor { if (Check->reportDeMorgan(Context, Op, BinaryOp, !IsProcessing, parent(), Parens) && !Check->areDiagsSelfContained()) { - llvm::SaveAndRestore RAII(IsProcessing, true); + const llvm::SaveAndRestore RAII(IsProcessing, true); return Base::TraverseUnaryOperator(Op); } } @@ -638,13 +638,13 @@ void SimplifyBooleanExprCheck::reportBinOp(const ASTContext &Context, if (!isa(Other) && containsBoolLiteral(Other)) return; - bool BoolValue = Bool->getValue(); + const bool BoolValue = Bool->getValue(); auto ReplaceWithExpression = [this, &Context, LHS, RHS, Bool](const Expr *ReplaceWith, bool Negated) { - std::string Replacement = + const std::string Replacement = replacementExpression(Context, Negated, ReplaceWith); - SourceRange Range(LHS->getBeginLoc(), RHS->getEndLoc()); + const SourceRange Range(LHS->getBeginLoc(), RHS->getEndLoc()); issueDiag(Context, Bool->getBeginLoc(), SimplifyOperatorDiagnostic, Range, Replacement); }; @@ -706,11 +706,11 @@ bool SimplifyBooleanExprCheck::issueDiag(const ASTContext &Context, StringRef Description, SourceRange ReplacementRange, StringRef Replacement) { - CharSourceRange CharRange = + const CharSourceRange CharRange = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(ReplacementRange), Context.getSourceManager(), getLangOpts()); - DiagnosticBuilder Diag = diag(Loc, Description); + const DiagnosticBuilder Diag = diag(Loc, Description); const bool HasReplacement = !containsDiscardedTokens(Context, CharRange); if (HasReplacement) Diag << FixItHint::CreateReplacement(CharRange, Replacement); @@ -737,7 +737,7 @@ void SimplifyBooleanExprCheck::replaceWithElseStatement( void SimplifyBooleanExprCheck::replaceWithCondition( const ASTContext &Context, const ConditionalOperator *Ternary, bool Negated) { - std::string Replacement = + const std::string Replacement = replacementExpression(Context, Negated, Ternary->getCond()); issueDiag(Context, Ternary->getTrueExpr()->getBeginLoc(), "redundant boolean literal in ternary expression result", @@ -747,11 +747,11 @@ void SimplifyBooleanExprCheck::replaceWithCondition( void SimplifyBooleanExprCheck::replaceWithReturnCondition( const ASTContext &Context, const IfStmt *If, const Expr *BoolLiteral, bool Negated) { - StringRef Terminator = isa(If->getElse()) ? ";" : ""; - std::string Condition = + const StringRef Terminator = isa(If->getElse()) ? ";" : ""; + const std::string Condition = replacementExpression(Context, Negated, If->getCond()); - std::string Replacement = ("return " + Condition + Terminator).str(); - SourceLocation Start = BoolLiteral->getBeginLoc(); + const std::string Replacement = ("return " + Condition + Terminator).str(); + const SourceLocation Start = BoolLiteral->getBeginLoc(); const bool HasReplacement = issueDiag(Context, Start, SimplifyConditionalReturnDiagnostic, @@ -795,12 +795,13 @@ void SimplifyBooleanExprCheck::replaceWithAssignment(const ASTContext &Context, const Expr *Var, SourceLocation Loc, bool Negated) { - SourceRange Range = IfAssign->getSourceRange(); - StringRef VariableName = getText(Context, *Var); - StringRef Terminator = isa(IfAssign->getElse()) ? ";" : ""; - std::string Condition = + const SourceRange Range = IfAssign->getSourceRange(); + const StringRef VariableName = getText(Context, *Var); + const StringRef Terminator = + isa(IfAssign->getElse()) ? ";" : ""; + const std::string Condition = replacementExpression(Context, Negated, IfAssign->getCond()); - std::string Replacement = + const std::string Replacement = (VariableName + " = " + Condition + Terminator).str(); issueDiag(Context, Loc, "redundant boolean literal in conditional assignment", Range, Replacement); diff --git a/clang-tools-extra/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp b/clang-tools-extra/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp index e9a2eae11bfde..abc9f6709125b 100644 --- a/clang-tools-extra/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/StaticDefinitionInAnonymousNamespaceCheck.cpp @@ -45,8 +45,8 @@ void StaticDefinitionInAnonymousNamespaceCheck::check( while (Loc < Def->getSourceRange().getEnd() && !Lexer::getRawToken(Loc, Tok, *Result.SourceManager, getLangOpts(), true)) { - SourceRange TokenRange(Tok.getLocation(), Tok.getEndLoc()); - StringRef SourceText = + const SourceRange TokenRange(Tok.getLocation(), Tok.getEndLoc()); + const StringRef SourceText = Lexer::getSourceText(CharSourceRange::getTokenRange(TokenRange), *Result.SourceManager, getLangOpts()); if (SourceText == "static") { diff --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp index feb248dd62411..19b47263c0089 100644 --- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp @@ -150,8 +150,8 @@ static bool applyAbbreviationHeuristic( /// Check whether the shorter String is a prefix of the longer String. static bool applyPrefixHeuristic(StringRef Arg, StringRef Param, int8_t Threshold) { - StringRef Shorter = Arg.size() < Param.size() ? Arg : Param; - StringRef Longer = Arg.size() >= Param.size() ? Arg : Param; + const StringRef Shorter = Arg.size() < Param.size() ? Arg : Param; + const StringRef Longer = Arg.size() >= Param.size() ? Arg : Param; if (Longer.starts_with_insensitive(Shorter)) return percentage(Shorter.size(), Longer.size()) > Threshold; @@ -162,8 +162,8 @@ static bool applyPrefixHeuristic(StringRef Arg, StringRef Param, /// Check whether the shorter String is a suffix of the longer String. static bool applySuffixHeuristic(StringRef Arg, StringRef Param, int8_t Threshold) { - StringRef Shorter = Arg.size() < Param.size() ? Arg : Param; - StringRef Longer = Arg.size() >= Param.size() ? Arg : Param; + const StringRef Shorter = Arg.size() < Param.size() ? Arg : Param; + const StringRef Longer = Arg.size() >= Param.size() ? Arg : Param; if (Longer.ends_with_insensitive(Shorter)) return percentage(Shorter.size(), Longer.size()) > Threshold; @@ -196,13 +196,13 @@ static bool applySubstringHeuristic(StringRef Arg, StringRef Param, Current.swap(Previous); } - size_t LongerLength = std::max(Arg.size(), Param.size()); + const size_t LongerLength = std::max(Arg.size(), Param.size()); return percentage(MaxLength, LongerLength) > Threshold; } static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param, int8_t Threshold) { - std::size_t LongerLength = std::max(Arg.size(), Param.size()); + const std::size_t LongerLength = std::max(Arg.size(), Param.size()); double Dist = Arg.edit_distance(Param); Dist = (1.0 - Dist / LongerLength) * 100.0; return Dist > Threshold; @@ -212,11 +212,11 @@ static bool applyLevenshteinHeuristic(StringRef Arg, StringRef Param, static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param, int8_t Threshold) { std::size_t Match = 0, Transpos = 0; - std::ptrdiff_t ArgLen = Arg.size(); - std::ptrdiff_t ParamLen = Param.size(); + const std::ptrdiff_t ArgLen = Arg.size(); + const std::ptrdiff_t ParamLen = Param.size(); SmallVector ArgFlags(ArgLen); SmallVector ParamFlags(ParamLen); - std::ptrdiff_t Range = + const std::ptrdiff_t Range = std::max(std::ptrdiff_t{0}, (std::max(ArgLen, ParamLen) / 2) - 1); // Calculate matching characters. @@ -252,7 +252,7 @@ static bool applyJaroWinklerHeuristic(StringRef Arg, StringRef Param, Transpos /= 2; // Jaro distance. - double MatchD = Match; + const double MatchD = Match; double Dist = ((MatchD / ArgLen) + (MatchD / ParamLen) + ((MatchD - Transpos) / Match)) / 3.0; @@ -347,7 +347,7 @@ static bool arePointersStillQualCompatible(QualType ArgType, QualType ParamType, // The types are compatible, if the parameter is at least as qualified as the // argument, and if it is more qualified, it has to be const on upper pointer // levels. - bool AreTypesQualCompatible = + const bool AreTypesQualCompatible = ParamType.isAtLeastAsQualifiedAs(ArgType, Ctx) && (!ParamType.hasQualifiers() || IsParamContinuouslyConst); // Check whether the parameter's constness continues at the current pointer @@ -401,7 +401,7 @@ static bool areTypesCompatible(QualType ArgType, QualType ParamType, if (!areRefAndQualCompatible(ArgType, ParamType, Ctx)) return false; - bool IsParamReference = ParamType->isReferenceType(); + const bool IsParamReference = ParamType->isReferenceType(); // Reference-ness has already been checked and should be removed // before further checking. @@ -438,7 +438,7 @@ static bool areTypesCompatible(QualType ArgType, QualType ParamType, if (IsParamReference && ParamType->isArrayType()) return isCompatibleWithArrayReference(ArgType, ParamType, Ctx); - bool IsParamContinuouslyConst = + const bool IsParamContinuouslyConst = !IsParamReference || ParamType.getNonReferenceType().isConstQualified(); // Remove the first level of indirection. @@ -513,9 +513,9 @@ SuspiciousCallArgumentCheck::SuspiciousCallArgumentCheck( SmallString<32> Key = HeuristicToString[Idx]; Key.append(BK == BoundKind::DissimilarBelow ? "DissimilarBelow" : "SimilarAbove"); - int8_t Default = BK == BoundKind::DissimilarBelow - ? Defaults[Idx].DissimilarBelow - : Defaults[Idx].SimilarAbove; + const int8_t Default = BK == BoundKind::DissimilarBelow + ? Defaults[Idx].DissimilarBelow + : Defaults[Idx].SimilarAbove; return Options.get(Key, Default); }; for (std::size_t Idx = 0; Idx < HeuristicCount; ++Idx) { @@ -527,7 +527,7 @@ SuspiciousCallArgumentCheck::SuspiciousCallArgumentCheck( GetBoundOpt(H, BoundKind::SimilarAbove))); } - for (StringRef Abbreviation : optutils::parseStringList( + for (const StringRef Abbreviation : optutils::parseStringList( Options.get("Abbreviations", DefaultAbbreviations))) { auto KeyAndValue = Abbreviation.split("="); assert(!KeyAndValue.first.empty() && !KeyAndValue.second.empty()); @@ -652,7 +652,7 @@ void SuspiciousCallArgumentCheck::check( if (ArgNames.empty()) return; - std::size_t ParamCount = ParamNames.size(); + const std::size_t ParamCount = ParamNames.size(); // Check similarity. for (std::size_t I = 0; I < ParamCount; ++I) { @@ -673,9 +673,9 @@ void SuspiciousCallArgumentCheck::check( << MatchedCallExpr->getArg(J)->getSourceRange(); // Note at the functions declaration. - SourceLocation IParNameLoc = + const SourceLocation IParNameLoc = CalleeFuncDecl->getParamDecl(I)->getLocation(); - SourceLocation JParNameLoc = + const SourceLocation JParNameLoc = CalleeFuncDecl->getParamDecl(J)->getLocation(); diag(CalleeFuncDecl->getLocation(), "in the call to %0, declared here", @@ -697,7 +697,7 @@ void SuspiciousCallArgumentCheck::setParamNamesAndTypes( for (const ParmVarDecl *Param : CalleeFuncDecl->parameters()) { ParamTypes.push_back(Param->getType()); - if (IdentifierInfo *II = Param->getIdentifier()) + if (const IdentifierInfo *II = Param->getIdentifier()) ParamNames.push_back(II->getName()); else ParamNames.push_back(StringRef()); @@ -759,16 +759,16 @@ bool SuspiciousCallArgumentCheck::areParamAndArgComparable( bool SuspiciousCallArgumentCheck::areArgsSwapped(std::size_t Position1, std::size_t Position2) const { - for (Heuristic H : AppliedHeuristics) { - bool A1ToP2Similar = areNamesSimilar( + for (const Heuristic H : AppliedHeuristics) { + const bool A1ToP2Similar = areNamesSimilar( ArgNames[Position2], ParamNames[Position1], H, BoundKind::SimilarAbove); - bool A2ToP1Similar = areNamesSimilar( + const bool A2ToP1Similar = areNamesSimilar( ArgNames[Position1], ParamNames[Position2], H, BoundKind::SimilarAbove); - bool A1ToP1Dissimilar = + const bool A1ToP1Dissimilar = !areNamesSimilar(ArgNames[Position1], ParamNames[Position1], H, BoundKind::DissimilarBelow); - bool A2ToP2Dissimilar = + const bool A2ToP2Dissimilar = !areNamesSimilar(ArgNames[Position2], ParamNames[Position2], H, BoundKind::DissimilarBelow); diff --git a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp index 740a68d852c9e..db226f97818c5 100644 --- a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp @@ -110,7 +110,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal, ReplacementDsc.LiteralLocation = L.getSourceRange(); // Was this literal fully spelled or is it a product of macro expansion? - bool RangeCanBeFixed = + const bool RangeCanBeFixed = utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM); // The literal may have macro expansion, we need the final expanded src range. diff --git a/clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp b/clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp index 82eb6de8fa3dc..fe03f2194e1b8 100644 --- a/clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp @@ -20,7 +20,7 @@ namespace { /// followed by a Stmt matching the inner matcher. AST_MATCHER_P(Stmt, nextStmt, ast_matchers::internal::Matcher, InnerMatcher) { - DynTypedNodeList Parents = Finder->getASTContext().getParents(Node); + const DynTypedNodeList Parents = Finder->getASTContext().getParents(Node); if (Parents.size() != 1) return false; diff --git a/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp b/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp index 8052e04c99f43..5a7add88d6eeb 100644 --- a/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/UseStdMinMaxCheck.cpp @@ -77,11 +77,11 @@ static QualType getNonTemplateAlias(QualType QT) { static QualType getReplacementCastType(const Expr *CondLhs, const Expr *CondRhs, QualType ComparedType) { - QualType LhsType = CondLhs->getType(); - QualType RhsType = CondRhs->getType(); - QualType LhsCanonicalType = + const QualType LhsType = CondLhs->getType(); + const QualType RhsType = CondRhs->getType(); + const QualType LhsCanonicalType = LhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType(); - QualType RhsCanonicalType = + const QualType RhsCanonicalType = RhsType.getCanonicalType().getNonReferenceType().getUnqualifiedType(); QualType GlobalImplicitCastType; if (LhsCanonicalType != RhsCanonicalType) { @@ -109,7 +109,7 @@ static std::string createReplacement(const Expr *CondLhs, const Expr *CondRhs, const llvm::StringRef AssignLhsStr = Lexer::getSourceText( Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO); - QualType GlobalImplicitCastType = + const QualType GlobalImplicitCastType = getReplacementCastType(CondLhs, CondRhs, BO->getLHS()->getType()); return (AssignLhsStr + " = " + FunctionName +