clang-tools 24.0.0git
RedundantExpressionCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "../utils/Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Basic/LLVM.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/SmallBitVector.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/raw_ostream.h"
23#include <algorithm>
24#include <cassert>
25#include <cstdint>
26#include <optional>
27#include <string>
28
29using namespace clang::ast_matchers;
30using namespace clang::tidy::matchers;
31
32namespace clang::tidy::misc {
33using llvm::APSInt;
34
35static constexpr StringRef KnownBannedMacroNames[] = {
36 "EAGAIN",
37 "EWOULDBLOCK",
38 "SIGCLD",
39 "SIGCHLD",
40};
41
42static bool incrementWithoutOverflow(const APSInt &Value, APSInt &Result) {
43 Result = Value;
44 ++Result;
45 return Value < Result;
46}
47
48static bool areEquivalentDeclRefExpr(const DeclRefExpr *L,
49 const DeclRefExpr *R) {
50 if (L->getDecl() != R->getDecl())
51 return false;
52
53 const PrintingPolicy &Policy =
54 L->getDecl()->getASTContext().getPrintingPolicy();
55
56 if (L->hasQualifier() && R->hasQualifier()) {
57 std::string LQual, RQual;
58 llvm::raw_string_ostream LOS(LQual), ROS(RQual);
59 L->getQualifier().print(LOS, Policy);
60 R->getQualifier().print(ROS, Policy);
61 if (LQual != RQual)
62 return false;
63 }
64
65 if (L->hasExplicitTemplateArgs() != R->hasExplicitTemplateArgs())
66 return false;
67 if (L->hasExplicitTemplateArgs()) {
68 if (L->getNumTemplateArgs() != R->getNumTemplateArgs())
69 return false;
70
71 return llvm::equal(L->template_arguments(), R->template_arguments(),
72 [&Policy](const TemplateArgumentLoc &LArg,
73 const TemplateArgumentLoc &RArg) {
74 std::string LStr, RStr;
75 llvm::raw_string_ostream LOS(LStr), ROS(RStr);
76 LArg.getArgument().print(Policy, LOS, true);
77 RArg.getArgument().print(Policy, ROS, true);
78 return LStr == RStr;
79 });
80 }
81 return true;
82}
83
84static bool areEquivalentExpr(const Expr *Left, const Expr *Right) {
85 if (!Left || !Right)
86 return !Left && !Right;
87
88 Left = Left->IgnoreParens();
89 Right = Right->IgnoreParens();
90
91 // Compare classes.
92 if (Left->getStmtClass() != Right->getStmtClass())
93 return false;
94
95 // Compare children.
96 Expr::const_child_iterator LeftIter = Left->child_begin();
97 Expr::const_child_iterator RightIter = Right->child_begin();
98 while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
99 if (!areEquivalentExpr(dyn_cast_or_null<Expr>(*LeftIter),
100 dyn_cast_or_null<Expr>(*RightIter)))
101 return false;
102 ++LeftIter;
103 ++RightIter;
104 }
105 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
106 return false;
107
108 // Perform extra checks.
109 switch (Left->getStmtClass()) {
110 default:
111 return false;
112
113 case Stmt::CharacterLiteralClass:
114 return cast<CharacterLiteral>(Left)->getValue() ==
115 cast<CharacterLiteral>(Right)->getValue();
116 case Stmt::IntegerLiteralClass: {
117 const llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
118 const llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
119 return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
120 LeftLit == RightLit;
121 }
122 case Stmt::FloatingLiteralClass:
123 return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
124 cast<FloatingLiteral>(Right)->getValue());
125 case Stmt::StringLiteralClass:
126 return cast<StringLiteral>(Left)->getBytes() ==
127 cast<StringLiteral>(Right)->getBytes();
128 case Stmt::CXXOperatorCallExprClass:
129 return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
130 cast<CXXOperatorCallExpr>(Right)->getOperator();
131 case Stmt::DependentScopeDeclRefExprClass:
132 if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
133 cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
134 return false;
135 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
136 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
137 case Stmt::DeclRefExprClass:
138 return areEquivalentDeclRefExpr(cast<DeclRefExpr>(Left),
139 cast<DeclRefExpr>(Right));
140 case Stmt::MemberExprClass:
141 return cast<MemberExpr>(Left)->getMemberDecl() ==
142 cast<MemberExpr>(Right)->getMemberDecl();
143 case Stmt::CXXFoldExprClass:
144 return cast<CXXFoldExpr>(Left)->getOperator() ==
145 cast<CXXFoldExpr>(Right)->getOperator();
146 case Stmt::CXXFunctionalCastExprClass:
147 case Stmt::CStyleCastExprClass:
148 return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
149 cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
150 case Stmt::CallExprClass:
151 case Stmt::ImplicitCastExprClass:
152 case Stmt::ArraySubscriptExprClass:
153 return true;
154 case Stmt::UnaryOperatorClass:
155 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
156 return false;
157 return cast<UnaryOperator>(Left)->getOpcode() ==
158 cast<UnaryOperator>(Right)->getOpcode();
159 case Stmt::BinaryOperatorClass:
160 if (cast<BinaryOperator>(Left)->isAssignmentOp())
161 return false;
162 return cast<BinaryOperator>(Left)->getOpcode() ==
163 cast<BinaryOperator>(Right)->getOpcode();
164 case Stmt::UnaryExprOrTypeTraitExprClass:
165 const auto *LeftUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Left);
166 const auto *RightUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Right);
167 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
168 return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
169 LeftUnaryExpr->getArgumentType() ==
170 RightUnaryExpr->getArgumentType();
171 if (!LeftUnaryExpr->isArgumentType() && !RightUnaryExpr->isArgumentType())
172 return areEquivalentExpr(LeftUnaryExpr->getArgumentExpr(),
173 RightUnaryExpr->getArgumentExpr());
174
175 return false;
176 }
177}
178
179// For a given expression 'x', returns whether the ranges covered by the
180// relational operators are equivalent (i.e. x <= 4 is equivalent to x < 5).
181static bool areEquivalentRanges(BinaryOperatorKind OpcodeLHS,
182 const APSInt &ValueLHS,
183 BinaryOperatorKind OpcodeRHS,
184 const APSInt &ValueRHS) {
185 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
186 "Values must be ordered");
187 // Handle the case where constants are the same: x <= 4 <==> x <= 4.
188 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
189 return OpcodeLHS == OpcodeRHS;
190
191 // Handle the case where constants are off by one: x <= 4 <==> x < 5.
192 APSInt ValueLhsPlus1;
193 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
194 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
195 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
196 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
197}
198
199// For a given expression 'x', returns whether the ranges covered by the
200// relational operators are fully disjoint (i.e. x < 4 and x > 7).
201static bool areExclusiveRanges(BinaryOperatorKind OpcodeLHS,
202 const APSInt &ValueLHS,
203 BinaryOperatorKind OpcodeRHS,
204 const APSInt &ValueRHS) {
205 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
206 "Values must be ordered");
207
208 // Handle cases where the constants are the same.
209 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
210 switch (OpcodeLHS) {
211 case BO_EQ:
212 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
213 case BO_NE:
214 return OpcodeRHS == BO_EQ;
215 case BO_LE:
216 return OpcodeRHS == BO_GT;
217 case BO_GE:
218 return OpcodeRHS == BO_LT;
219 case BO_LT:
220 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
221 case BO_GT:
222 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
223 default:
224 return false;
225 }
226 }
227
228 // Handle cases where the constants are different.
229 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
230 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
231 return true;
232
233 // Handle the case where constants are off by one: x > 5 && x < 6.
234 APSInt ValueLhsPlus1;
235 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
236 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
237 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
238 return true;
239
240 return false;
241}
242
243// Returns whether the ranges covered by the union of both relational
244// expressions cover the whole domain (i.e. x < 10 and x > 0).
245static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS,
246 const APSInt &ValueLHS,
247 BinaryOperatorKind OpcodeRHS,
248 const APSInt &ValueRHS) {
249 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
250 "Values must be ordered");
251
252 // Handle cases where the constants are the same: x < 5 || x >= 5.
253 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
254 switch (OpcodeLHS) {
255 case BO_EQ:
256 return OpcodeRHS == BO_NE;
257 case BO_NE:
258 return OpcodeRHS == BO_EQ;
259 case BO_LE:
260 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
261 case BO_LT:
262 return OpcodeRHS == BO_GE;
263 case BO_GE:
264 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
265 case BO_GT:
266 return OpcodeRHS == BO_LE;
267 default:
268 return false;
269 }
270 }
271
272 // Handle the case where constants are off by one: x <= 4 || x >= 5.
273 APSInt ValueLhsPlus1;
274 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
275 incrementWithoutOverflow(ValueLHS, ValueLhsPlus1) &&
276 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
277 return true;
278
279 // Handle cases where the constants are different: x > 4 || x <= 7.
280 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
281 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
282 return true;
283
284 // Handle cases where constants are different but both ops are !=, like:
285 // x != 5 || x != 10
286 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
287 return true;
288
289 return false;
290}
291
292static bool rangeSubsumesRange(BinaryOperatorKind OpcodeLHS,
293 const APSInt &ValueLHS,
294 BinaryOperatorKind OpcodeRHS,
295 const APSInt &ValueRHS) {
296 const int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
297 switch (OpcodeLHS) {
298 case BO_EQ:
299 return OpcodeRHS == BO_EQ && Comparison == 0;
300 case BO_NE:
301 return (OpcodeRHS == BO_NE && Comparison == 0) ||
302 (OpcodeRHS == BO_EQ && Comparison != 0) ||
303 (OpcodeRHS == BO_LT && Comparison >= 0) ||
304 (OpcodeRHS == BO_LE && Comparison > 0) ||
305 (OpcodeRHS == BO_GT && Comparison <= 0) ||
306 (OpcodeRHS == BO_GE && Comparison < 0);
307
308 case BO_LT:
309 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
310 (OpcodeRHS == BO_LE && Comparison > 0) ||
311 (OpcodeRHS == BO_EQ && Comparison > 0));
312 case BO_GT:
313 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
314 (OpcodeRHS == BO_GE && Comparison < 0) ||
315 (OpcodeRHS == BO_EQ && Comparison < 0));
316 case BO_LE:
317 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
318 Comparison >= 0;
319 case BO_GE:
320 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
321 Comparison <= 0;
322 default:
323 return false;
324 }
325}
326
327static void transformSubToCanonicalAddExpr(BinaryOperatorKind &Opcode,
328 APSInt &Value) {
329 if (Opcode == BO_Sub) {
330 Opcode = BO_Add;
331 Value = -Value;
332 }
333}
334
335// to use in the template below
336static OverloadedOperatorKind getOp(const BinaryOperator *Op) {
337 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
338}
339
340static OverloadedOperatorKind getOp(const CXXOperatorCallExpr *Op) {
341 if (Op->getNumArgs() != 2)
342 return OO_None;
343 return Op->getOperator();
344}
345
346static std::pair<const Expr *, const Expr *>
347getOperands(const BinaryOperator *Op) {
348 return {Op->getLHS()->IgnoreParenImpCasts(),
349 Op->getRHS()->IgnoreParenImpCasts()};
350}
351
352static std::pair<const Expr *, const Expr *>
353getOperands(const CXXOperatorCallExpr *Op) {
354 return {Op->getArg(0)->IgnoreParenImpCasts(),
355 Op->getArg(1)->IgnoreParenImpCasts()};
356}
357
358template <typename TExpr>
359static const TExpr *checkOpKind(const Expr *TheExpr,
360 OverloadedOperatorKind OpKind) {
361 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
362 if (AsTExpr && getOp(AsTExpr) == OpKind)
363 return AsTExpr;
364
365 return nullptr;
366}
367
368// returns true if a subexpression has two directly equivalent operands and
369// is already handled by operands/parametersAreEquivalent
370template <typename TExpr, unsigned N>
371static bool collectOperands(const Expr *Part,
372 SmallVector<const Expr *, N> &AllOperands,
373 OverloadedOperatorKind OpKind) {
374 if (const auto *BinOp = checkOpKind<TExpr>(Part, OpKind)) {
375 const std::pair<const Expr *, const Expr *> Operands = getOperands(BinOp);
376 if (areEquivalentExpr(Operands.first, Operands.second))
377 return true;
378 return collectOperands<TExpr>(Operands.first, AllOperands, OpKind) ||
379 collectOperands<TExpr>(Operands.second, AllOperands, OpKind);
380 }
381
382 AllOperands.push_back(Part);
383 return false;
384}
385
386template <typename TExpr>
387static bool hasSameOperatorParent(const Expr *TheExpr,
388 OverloadedOperatorKind OpKind,
389 ASTContext &Context) {
390 // IgnoreParenImpCasts logic in reverse: skip surrounding uninteresting nodes
391 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
392 for (const DynTypedNode DynParent : Parents) {
393 if (const auto *Parent = DynParent.get<Expr>()) {
394 const bool Skip =
395 isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
396 isa<FullExpr>(Parent) || isa<MaterializeTemporaryExpr>(Parent);
397 if (Skip && hasSameOperatorParent<TExpr>(Parent, OpKind, Context))
398 return true;
399 if (checkOpKind<TExpr>(Parent, OpKind))
400 return true;
401 }
402 }
403
404 return false;
405}
406
407static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
408 const SourceManager &SM) {
409 if (T1.getKind() != T2.getKind())
410 return false;
411 if (T1.isNot(tok::raw_identifier))
412 return true;
413 if (T1.getLength() != T2.getLength())
414 return false;
415 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
416 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
417}
418
419static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T,
420 const SourceManager &SM) {
421 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
422}
423
424/// Returns true if both LhsExpr and RhsExpr are
425/// macro expressions and they are expanded
426/// from different macros.
427static bool areExprsFromDifferentMacros(const Expr *LhsExpr,
428 const Expr *RhsExpr,
429 const ASTContext *AstCtx) {
430 if (!LhsExpr || !RhsExpr)
431 return false;
432 const SourceRange Lsr = LhsExpr->getSourceRange();
433 const SourceRange Rsr = RhsExpr->getSourceRange();
434 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
435 return false;
436
437 const SourceManager &SM = AstCtx->getSourceManager();
438 const LangOptions &LO = AstCtx->getLangOpts();
439
440 const std::pair<FileID, unsigned> LsrLocInfo =
441 SM.getDecomposedLoc(SM.getExpansionLoc(Lsr.getBegin()));
442 const std::pair<FileID, unsigned> RsrLocInfo =
443 SM.getDecomposedLoc(SM.getExpansionLoc(Rsr.getBegin()));
444 const llvm::MemoryBufferRef MB = SM.getBufferOrFake(LsrLocInfo.first);
445
446 const char *LTokenPos = MB.getBufferStart() + LsrLocInfo.second;
447 const char *RTokenPos = MB.getBufferStart() + RsrLocInfo.second;
448 Lexer LRawLex(SM.getLocForStartOfFile(LsrLocInfo.first), LO,
449 MB.getBufferStart(), LTokenPos, MB.getBufferEnd());
450 Lexer RRawLex(SM.getLocForStartOfFile(RsrLocInfo.first), LO,
451 MB.getBufferStart(), RTokenPos, MB.getBufferEnd());
452
453 Token LTok, RTok;
454 do { // Compare the expressions token-by-token.
455 LRawLex.LexFromRawLexer(LTok);
456 RRawLex.LexFromRawLexer(RTok);
457 } while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
458 isSameRawIdentifierToken(LTok, RTok, SM) &&
459 !isTokAtEndOfExpr(Lsr, LTok, SM) &&
460 !isTokAtEndOfExpr(Rsr, RTok, SM));
461 return (!isTokAtEndOfExpr(Lsr, LTok, SM) ||
462 !isTokAtEndOfExpr(Rsr, RTok, SM)) ||
463 !isSameRawIdentifierToken(LTok, RTok, SM);
464}
465
466static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr,
467 const Expr *&RhsExpr) {
468 if (!LhsExpr || !RhsExpr)
469 return false;
470
471 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
472 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
473
474 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
475}
476
477template <typename TExpr>
478static bool
479markDuplicateOperands(const TExpr *TheExpr,
480 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
481 ASTContext &Context) {
482 const OverloadedOperatorKind OpKind = getOp(TheExpr);
483 if (OpKind == OO_None)
484 return false;
485 // if there are no nested operators of the same kind, it's handled by
486 // operands/parametersAreEquivalent
487 const std::pair<const Expr *, const Expr *> Operands = getOperands(TheExpr);
488 if (!(checkOpKind<TExpr>(Operands.first, OpKind) ||
489 checkOpKind<TExpr>(Operands.second, OpKind)))
490 return false;
491
492 // if parent is the same kind of operator, it's handled by a previous call to
493 // markDuplicateOperands
494 if (hasSameOperatorParent<TExpr>(TheExpr, OpKind, Context))
495 return false;
496
498 if (collectOperands<TExpr>(Operands.first, AllOperands, OpKind))
499 return false;
500 if (collectOperands<TExpr>(Operands.second, AllOperands, OpKind))
501 return false;
502 const size_t NumOperands = AllOperands.size();
503 llvm::SmallBitVector Duplicates(NumOperands);
504 for (size_t I = 0; I < NumOperands; I++) {
505 if (Duplicates[I])
506 continue;
507 bool FoundDuplicates = false;
508
509 for (size_t J = I + 1; J < NumOperands; J++) {
510 if (AllOperands[J]->HasSideEffects(Context))
511 break;
512
513 const Expr *Lhs = AllOperands[I];
514 const Expr *Rhs = AllOperands[J];
515 if (!areEquivalentExpr(Lhs, Rhs) ||
516 areExprsFromDifferentMacros(Lhs, Rhs, &Context) ||
517 areExprsMacroAndNonMacro(Lhs, Rhs))
518 continue;
519
520 FoundDuplicates = true;
521 Duplicates.set(J);
522 Builder->setBinding(SmallString<11>(llvm::formatv("duplicate{0}", J)),
523 DynTypedNode::create(*Rhs));
524 }
525
526 if (FoundDuplicates)
527 Builder->setBinding(SmallString<11>(llvm::formatv("duplicate{0}", I)),
528 DynTypedNode::create(*AllOperands[I]));
529 }
530
531 return Duplicates.any();
532}
533
534namespace {
535
536AST_MATCHER(Expr, isIntegerConstantExpr) {
537 if (Node.isInstantiationDependent())
538 return false;
539 return Node.isIntegerConstantExpr(Finder->getASTContext());
540}
541
542AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
543 return areEquivalentExpr(Node.getLHS(), Node.getRHS());
544}
545
546AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
547 return markDuplicateOperands(&Node, Builder, Finder->getASTContext());
548}
549
550AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
551 return areEquivalentExpr(Node.getTrueExpr(), Node.getFalseExpr());
552}
553
554AST_MATCHER(CallExpr, parametersAreEquivalent) {
555 return Node.getNumArgs() == 2 &&
556 areEquivalentExpr(Node.getArg(0), Node.getArg(1));
557}
558
559AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
560 return markDuplicateOperands(&Node, Builder, Finder->getASTContext());
561}
562
563AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
564 return Node.getOperatorLoc().isMacroID();
565}
566
567AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
568 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
569}
570
571AST_MATCHER(Expr, isMacro) { return Node.getExprLoc().isMacroID(); }
572
573AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<StringRef>, Names) {
574 const SourceManager &SM = Finder->getASTContext().getSourceManager();
575 const LangOptions &LO = Finder->getASTContext().getLangOpts();
576 SourceLocation Loc = Node.getExprLoc();
577 while (Loc.isMacroID()) {
578 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
579 if (llvm::is_contained(Names, MacroName))
580 return true;
581 Loc = SM.getImmediateMacroCallerLoc(Loc);
582 }
583 return false;
584}
585
586} // namespace
587
588// Returns a matcher for integer constant expressions.
589static ast_matchers::internal::Matcher<Expr>
591 const std::string CstId = (Id + "-const").str();
592 return expr(isIntegerConstantExpr()).bind(CstId);
593}
594
595// Retrieves the integer expression matched by 'matchIntegerConstantExpr' with
596// name 'Id' and stores it into 'ConstExpr', the value of the expression is
597// stored into `Value`.
598static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
599 StringRef Id, APSInt &Value,
600 const Expr *&ConstExpr) {
601 const std::string CstId = (Id + "-const").str();
602 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
603 if (!ConstExpr)
604 return false;
605 std::optional<llvm::APSInt> R =
606 ConstExpr->getIntegerConstantExpr(*Result.Context);
607 if (!R)
608 return false;
609 Value = *R;
610 return true;
611}
612
613// Overloaded `retrieveIntegerConstantExpr` for compatibility.
614static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
615 StringRef Id, APSInt &Value) {
616 const Expr *ConstExpr = nullptr;
617 return retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr);
618}
619
620// Returns a matcher for symbolic expressions (matches every expression except
621// ingeter constant expressions).
622static ast_matchers::internal::Matcher<Expr> matchSymbolicExpr(StringRef Id) {
623 const std::string SymId = (Id + "-sym").str();
624 return ignoringParenImpCasts(
625 expr(unless(isIntegerConstantExpr())).bind(SymId));
626}
627
628// Retrieves the expression matched by 'matchSymbolicExpr' with name 'Id' and
629// stores it into 'SymExpr'.
630static bool retrieveSymbolicExpr(const MatchFinder::MatchResult &Result,
631 StringRef Id, const Expr *&SymExpr) {
632 const std::string SymId = (Id + "-sym").str();
633 if (const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
634 SymExpr = Node;
635 return true;
636 }
637 return false;
638}
639
640// Match a binary operator between a symbolic expression and an integer constant
641// expression.
642static ast_matchers::internal::Matcher<Expr>
644 const auto BinOpCstExpr =
645 expr(anyOf(binaryOperator(hasAnyOperatorName("+", "|", "&"),
646 hasOperands(matchSymbolicExpr(Id),
648 binaryOperator(hasOperatorName("-"),
649 hasLHS(matchSymbolicExpr(Id)),
650 hasRHS(matchIntegerConstantExpr(Id)))))
651 .bind(Id);
652 return ignoringParenImpCasts(BinOpCstExpr);
653}
654
655// Retrieves sub-expressions matched by 'matchBinOpIntegerConstantExpr' with
656// name 'Id'.
657static bool
658retrieveBinOpIntegerConstantExpr(const MatchFinder::MatchResult &Result,
659 StringRef Id, BinaryOperatorKind &Opcode,
660 const Expr *&Symbol, APSInt &Value) {
661 if (const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
662 Opcode = BinExpr->getOpcode();
663 return retrieveSymbolicExpr(Result, Id, Symbol) &&
664 retrieveIntegerConstantExpr(Result, Id, Value);
665 }
666 return false;
667}
668
669// Matches relational expressions: 'Expr <op> k' (i.e. x < 2, x != 3, 12 <= x).
670static ast_matchers::internal::Matcher<Expr>
672 const std::string CastId = (Id + "-cast").str();
673 const std::string SwapId = (Id + "-swap").str();
674 const std::string NegateId = (Id + "-negate").str();
675 const std::string OverloadId = (Id + "-overload").str();
676 const std::string ConstId = (Id + "-const").str();
677
678 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
679 isComparisonOperator(), expr().bind(Id),
680 anyOf(allOf(hasLHS(matchSymbolicExpr(Id)),
681 hasRHS(matchIntegerConstantExpr(Id))),
682 allOf(hasLHS(matchIntegerConstantExpr(Id)),
683 hasRHS(matchSymbolicExpr(Id)), expr().bind(SwapId)))));
684
685 // A cast can be matched as a comparator to zero. (i.e. if (x) is equivalent
686 // to if (x != 0)).
687 const auto CastExpr =
688 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
689 hasSourceExpression(matchSymbolicExpr(Id)))
690 .bind(CastId);
691
692 const auto NegateRelationalExpr =
693 unaryOperator(hasOperatorName("!"),
694 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
695 .bind(NegateId);
696
697 // Do not bind to double negation.
698 const auto NegateNegateRelationalExpr =
699 unaryOperator(hasOperatorName("!"),
700 hasUnaryOperand(unaryOperator(
701 hasOperatorName("!"),
702 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
703
704 const auto OverloadedOperatorExpr =
705 cxxOperatorCallExpr(
706 hasAnyOverloadedOperatorName("==", "!=", "<", "<=", ">", ">="),
707 // Filter noisy false positives.
708 unless(isMacro()), unless(isInTemplateInstantiation()),
709 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
710 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
711 .bind(OverloadId);
712
713 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
714 NegateNegateRelationalExpr, OverloadedOperatorExpr);
715}
716
717// Checks whether a function param is non constant reference type, and may
718// be modified in the function.
719static bool isNonConstReferenceType(QualType ParamType) {
720 return ParamType->isReferenceType() &&
721 !ParamType.getNonReferenceType().isConstQualified();
722}
723
724// Checks whether the arguments of an overloaded operator can be modified in the
725// function.
726// For operators that take an instance and a constant as arguments, only the
727// first argument (the instance) needs to be checked, since the constant itself
728// is a temporary expression. Whether the second parameter is checked is
729// controlled by the parameter `ParamsToCheckCount`.
730static bool
731canOverloadedOperatorArgsBeModified(const CXXOperatorCallExpr *OperatorCall,
732 bool CheckSecondParam) {
733 const auto *OperatorDecl =
734 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
735 // if we can't find the declaration, conservatively assume it can modify
736 // arguments
737 if (!OperatorDecl)
738 return true;
739
740 const unsigned ParamCount = OperatorDecl->getNumParams();
741
742 // Overloaded operators declared inside a class have only one param.
743 // These functions must be declared const in order to not be able to modify
744 // the instance of the class they are called through.
745 if (ParamCount == 1 &&
746 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
747 return true;
748
749 if (isNonConstReferenceType(OperatorDecl->getParamDecl(0)->getType()))
750 return true;
751
752 return CheckSecondParam && ParamCount == 2 &&
753 isNonConstReferenceType(OperatorDecl->getParamDecl(1)->getType());
754}
755
756// Retrieves sub-expressions matched by 'matchRelationalIntegerConstantExpr'
757// with name 'Id'.
759 const MatchFinder::MatchResult &Result, StringRef Id,
760 const Expr *&OperandExpr, BinaryOperatorKind &Opcode, const Expr *&Symbol,
761 APSInt &Value, const Expr *&ConstExpr) {
762 const std::string CastId = (Id + "-cast").str();
763 const std::string SwapId = (Id + "-swap").str();
764 const std::string NegateId = (Id + "-negate").str();
765 const std::string OverloadId = (Id + "-overload").str();
766
767 if (const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
768 // Operand received with explicit comparator.
769 Opcode = Bin->getOpcode();
770 OperandExpr = Bin;
771
772 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
773 return false;
774 } else if (const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
775 // Operand received with implicit comparator (cast).
776 Opcode = BO_NE;
777 OperandExpr = Cast;
778 Value = APSInt(32, false);
779 } else if (const auto *OverloadedOperatorExpr =
780 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
781 if (canOverloadedOperatorArgsBeModified(OverloadedOperatorExpr, false))
782 return false;
783
784 bool IntegerConstantIsFirstArg = false;
785
786 if (const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
787 if (!Arg->isValueDependent() &&
788 !Arg->isIntegerConstantExpr(*Result.Context)) {
789 IntegerConstantIsFirstArg = true;
790 if (const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
791 if (!Arg->isValueDependent() &&
792 !Arg->isIntegerConstantExpr(*Result.Context))
793 return false;
794 } else {
795 return false;
796 }
797 }
798 } else {
799 return false;
800 }
801
802 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
803 OperandExpr = OverloadedOperatorExpr;
804 Opcode = BinaryOperator::getOverloadedOpcode(
805 OverloadedOperatorExpr->getOperator());
806
807 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
808 return false;
809
810 if (!BinaryOperator::isComparisonOp(Opcode))
811 return false;
812
813 // The call site of this function expects the constant on the RHS,
814 // so change the opcode accordingly.
815 if (IntegerConstantIsFirstArg)
816 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
817
818 return true;
819 } else {
820 return false;
821 }
822
823 if (!retrieveSymbolicExpr(Result, Id, Symbol))
824 return false;
825
826 if (Result.Nodes.getNodeAs<Expr>(SwapId))
827 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
828 if (Result.Nodes.getNodeAs<Expr>(NegateId))
829 Opcode = BinaryOperator::negateComparisonOp(Opcode);
830 return true;
831}
832
833// Checks for expressions like (X == 4) && (Y != 9)
834static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp,
835 const ASTContext *AstCtx) {
836 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
837 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
838
839 if (!LhsBinOp || !RhsBinOp)
840 return false;
841
842 auto IsIntegerConstantExpr = [AstCtx](const Expr *E) {
843 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
844 };
845
846 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
847 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
848 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
849 IsIntegerConstantExpr(RhsBinOp->getRHS())))
850 return true;
851 return false;
852}
853
855 const BinaryOperator *&BinOp, const ASTContext *AstCtx) {
856 if (areSidesBinaryConstExpressions(BinOp, AstCtx))
857 return true;
858
859 const Expr *Lhs = BinOp->getLHS();
860 const Expr *Rhs = BinOp->getRHS();
861
862 if (!Lhs || !Rhs)
863 return false;
864
865 auto IsDefineExpr = [AstCtx](const Expr *E) {
866 const SourceRange Lsr = E->getSourceRange();
867 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
868 !E->isIntegerConstantExpr(*AstCtx))
869 return false;
870 return true;
871 };
872
873 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
874}
875
876// Retrieves integer constant subexpressions from binary operator expressions
877// that have two equivalent sides.
878// E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
879static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp,
880 BinaryOperatorKind &MainOpcode,
881 BinaryOperatorKind &SideOpcode,
882 const Expr *&LhsConst,
883 const Expr *&RhsConst,
884 const ASTContext *AstCtx) {
885 assert(areSidesBinaryConstExpressions(BinOp, AstCtx) &&
886 "Both sides of binary operator must be constant expressions!");
887
888 MainOpcode = BinOp->getOpcode();
889
890 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
891 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
892
893 auto IsIntegerConstantExpr = [AstCtx](const Expr *E) {
894 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
895 };
896
897 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
898 : BinOpLhs->getRHS();
899 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
900 : BinOpRhs->getRHS();
901
902 if (!LhsConst || !RhsConst)
903 return false;
904
905 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
906 "Sides of the binary operator must be equivalent expressions!");
907
908 SideOpcode = BinOpLhs->getOpcode();
909
910 return true;
911}
912
913static bool areStringsSameIgnoreSpaces(const StringRef Left,
914 const StringRef Right) {
915 if (Left == Right)
916 return true;
917
918 // Do running comparison ignoring spaces
919 StringRef L = Left.trim();
920 StringRef R = Right.trim();
921 while (!L.empty() && !R.empty()) {
922 L = L.ltrim();
923 R = R.ltrim();
924 if (L.empty() && R.empty())
925 return true;
926 // If symbol compared are different ==> strings are not the same
927 if (L.front() != R.front())
928 return false;
929 L = L.drop_front();
930 R = R.drop_front();
931 }
932 return L.empty() && R.empty();
933}
934
935static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp,
936 const ASTContext *Context) {
937 if (!BinOp)
938 return false;
939
940 const Expr *Lhs = BinOp->getLHS();
941 const Expr *Rhs = BinOp->getRHS();
942 const SourceManager &SM = Context->getSourceManager();
943
944 const SourceRange Lsr = Lhs->getSourceRange();
945 const SourceRange Rsr = Rhs->getSourceRange();
946 if (Lsr.getBegin().isMacroID()) {
947 // Left is macro so right macro too
948 if (Rsr.getBegin().isMacroID()) {
949 // Both sides are macros so they are same macro or literal
950 const StringRef L = Lexer::getSourceText(
951 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
952 const StringRef R = Lexer::getSourceText(
953 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
954 return areStringsSameIgnoreSpaces(L, R);
955 }
956 // Left is macro but right is not so they are not same macro or literal
957 return false;
958 }
959 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
960 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
961 if (Lil && Ril)
962 return Lil->getValue() == Ril->getValue();
963
964 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
965 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
966 if (Lbl && Rbl)
967 return Lbl->getValue() == Rbl->getValue();
968
969 return false;
970}
971
973 const auto BannedIntegerLiteral =
974 integerLiteral(expandedByMacro(KnownBannedMacroNames));
975 const auto IsInUnevaluatedContext = expr(anyOf(
976 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
977
978 // Binary with equivalent operands, like (X != 2 && X != 2).
979 Finder->addMatcher(
980 traverse(TK_AsIs,
981 binaryOperator(anyOf(isComparisonOperator(),
982 hasAnyOperatorName("-", "/", "%", "|", "&",
983 "^", "&&", "||", "=")),
984 operandsAreEquivalent(),
985 // Filter noisy false positives.
986 unless(isInTemplateInstantiation()),
987 unless(binaryOperatorIsInMacro()),
988 unless(hasAncestor(arraySubscriptExpr())),
989 unless(hasDescendant(BannedIntegerLiteral)),
990 unless(IsInUnevaluatedContext))
991 .bind("binary")),
992 this);
993
994 // Logical or bitwise operator with equivalent nested operands, like (X && Y
995 // && X) or (X && (Y && X))
996 Finder->addMatcher(
997 binaryOperator(hasAnyOperatorName("|", "&", "||", "&&", "^"),
998 nestedOperandsAreEquivalent(),
999 // Filter noisy false positives.
1000 unless(isInTemplateInstantiation()),
1001 unless(binaryOperatorIsInMacro()),
1002 // TODO: if the banned macros are themselves duplicated
1003 unless(hasDescendant(BannedIntegerLiteral)),
1004 unless(IsInUnevaluatedContext))
1005 .bind("nested-duplicates"),
1006 this);
1007
1008 // Conditional (ternary) operator with equivalent operands, like (Y ? X : X).
1009 Finder->addMatcher(
1010 traverse(TK_AsIs,
1011 conditionalOperator(expressionsAreEquivalent(),
1012 // Filter noisy false positives.
1013 unless(conditionalOperatorIsInMacro()),
1014 unless(isInTemplateInstantiation()),
1015 unless(IsInUnevaluatedContext))
1016 .bind("cond")),
1017 this);
1018
1019 // Overloaded operators with equivalent operands.
1020 Finder->addMatcher(
1021 traverse(TK_AsIs,
1022 cxxOperatorCallExpr(
1023 hasAnyOverloadedOperatorName("-", "/", "%", "|", "&", "^",
1024 "==", "!=", "<", "<=", ">",
1025 ">=", "&&", "||", "="),
1026 parametersAreEquivalent(),
1027 // Filter noisy false positives.
1028 unless(isMacro()), unless(isInTemplateInstantiation()),
1029 unless(IsInUnevaluatedContext))
1030 .bind("call")),
1031 this);
1032
1033 // Overloaded operators with equivalent operands.
1034 Finder->addMatcher(
1035 cxxOperatorCallExpr(
1036 hasAnyOverloadedOperatorName("|", "&", "||", "&&", "^"),
1037 nestedParametersAreEquivalent(), argumentCountIs(2),
1038 // Filter noisy false positives.
1039 unless(isMacro()), unless(isInTemplateInstantiation()),
1040 unless(IsInUnevaluatedContext))
1041 .bind("nested-duplicates"),
1042 this);
1043
1044 // Match expressions like: !(1 | 2 | 3)
1045 Finder->addMatcher(
1046 traverse(TK_AsIs,
1047 implicitCastExpr(
1048 hasImplicitDestinationType(isInteger()),
1049 has(unaryOperator(
1050 hasOperatorName("!"),
1051 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1052 hasAnyOperatorName("|", "&"),
1053 hasLHS(anyOf(
1054 binaryOperator(hasAnyOperatorName("|", "&")),
1055 integerLiteral())),
1056 hasRHS(integerLiteral())))))
1057 .bind("logical-bitwise-confusion")),
1058 unless(IsInUnevaluatedContext))),
1059 this);
1060
1061 // Match expressions like: (X << 8) & 0xFF
1062 Finder->addMatcher(
1063 traverse(TK_AsIs,
1064 binaryOperator(
1065 hasOperatorName("&"),
1066 hasOperands(ignoringParenImpCasts(binaryOperator(
1067 hasOperatorName("<<"),
1068 hasRHS(ignoringParenImpCasts(
1069 integerLiteral().bind("shift-const"))))),
1070 ignoringParenImpCasts(
1071 integerLiteral().bind("and-const"))),
1072 unless(IsInUnevaluatedContext))
1073 .bind("left-right-shift-confusion")),
1074 this);
1075
1076 // Match common expressions and apply more checks to find redundant
1077 // sub-expressions.
1078 // a) Expr <op> K1 == K2
1079 // b) Expr <op> K1 == Expr
1080 // c) Expr <op> K1 == Expr <op> K2
1081 // see: 'checkArithmeticExpr' and 'checkBitwiseExpr'
1082 const auto BinOpCstLeft = matchBinOpIntegerConstantExpr("lhs");
1083 const auto BinOpCstRight = matchBinOpIntegerConstantExpr("rhs");
1084 const auto CstRight = matchIntegerConstantExpr("rhs");
1085 const auto SymRight = matchSymbolicExpr("rhs");
1086
1087 // Match expressions like: x <op> 0xFF == 0xF00.
1088 Finder->addMatcher(
1089 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1090 hasOperands(BinOpCstLeft, CstRight),
1091 unless(IsInUnevaluatedContext))
1092 .bind("binop-const-compare-to-const")),
1093 this);
1094
1095 // Match expressions like: x <op> 0xFF == x.
1096 Finder->addMatcher(
1097 traverse(
1098 TK_AsIs,
1099 binaryOperator(isComparisonOperator(),
1100 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1101 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1102 unless(IsInUnevaluatedContext))
1103 .bind("binop-const-compare-to-sym")),
1104 this);
1105
1106 // Match expressions like: x <op> 10 == x <op> 12.
1107 Finder->addMatcher(
1108 traverse(TK_AsIs,
1109 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1110 hasRHS(BinOpCstRight),
1111 // Already reported as redundant.
1112 unless(operandsAreEquivalent()),
1113 unless(IsInUnevaluatedContext))
1114 .bind("binop-const-compare-to-binop-const")),
1115 this);
1116
1117 // Match relational expressions combined with logical operators and find
1118 // redundant sub-expressions.
1119 // see: 'checkRelationalExpr'
1120
1121 // Match expressions like: x < 2 && x > 2.
1122 const auto ComparisonLeft = matchRelationalIntegerConstantExpr("lhs");
1123 const auto ComparisonRight = matchRelationalIntegerConstantExpr("rhs");
1124 Finder->addMatcher(
1125 traverse(TK_AsIs,
1126 binaryOperator(hasAnyOperatorName("||", "&&"),
1127 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1128 // Already reported as redundant.
1129 unless(operandsAreEquivalent()),
1130 unless(IsInUnevaluatedContext))
1131 .bind("comparisons-of-symbol-and-const")),
1132 this);
1133}
1134
1135void RedundantExpressionCheck::checkArithmeticExpr(
1136 const MatchFinder::MatchResult &Result) {
1137 APSInt LhsValue, RhsValue;
1138 const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
1139 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1140
1141 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1142 "binop-const-compare-to-sym")) {
1143 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1144 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1145 LhsValue) ||
1146 !retrieveSymbolicExpr(Result, "rhs", RhsSymbol) ||
1147 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1148 return;
1149
1150 // Check expressions: x + k == x or x - k == x.
1151 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1152 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1153 (LhsValue == 0 && Opcode == BO_NE))
1154 diag(ComparisonOperator->getOperatorLoc(),
1155 "logical expression is always false");
1156 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1157 (LhsValue != 0 && Opcode == BO_NE))
1158 diag(ComparisonOperator->getOperatorLoc(),
1159 "logical expression is always true");
1160 }
1161 } else if (const auto *ComparisonOperator =
1162 Result.Nodes.getNodeAs<BinaryOperator>(
1163 "binop-const-compare-to-binop-const")) {
1164 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1165
1166 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1167 LhsValue) ||
1168 !retrieveBinOpIntegerConstantExpr(Result, "rhs", RhsOpcode, RhsSymbol,
1169 RhsValue) ||
1170 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1171 return;
1172
1173 transformSubToCanonicalAddExpr(LhsOpcode, LhsValue);
1174 transformSubToCanonicalAddExpr(RhsOpcode, RhsValue);
1175
1176 // Check expressions: x + 1 == x + 2 or x + 1 != x + 2.
1177 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1178 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1179 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1180 diag(ComparisonOperator->getOperatorLoc(),
1181 "logical expression is always true");
1182 } else if ((Opcode == BO_EQ &&
1183 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1184 (Opcode == BO_NE &&
1185 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1186 diag(ComparisonOperator->getOperatorLoc(),
1187 "logical expression is always false");
1188 }
1189 }
1190 }
1191}
1192
1193static bool exprEvaluatesToZero(BinaryOperatorKind Opcode,
1194 const APSInt &Value) {
1195 return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
1196}
1197
1198static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode,
1199 const APSInt &Value) {
1200 return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
1201}
1202
1203static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode,
1204 const APSInt &Value) {
1205 return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
1206 ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
1207}
1208
1209void RedundantExpressionCheck::checkBitwiseExpr(
1210 const MatchFinder::MatchResult &Result) {
1211 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1212 "binop-const-compare-to-const")) {
1213 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1214
1215 APSInt LhsValue, RhsValue;
1216 const Expr *LhsSymbol = nullptr;
1217 BinaryOperatorKind LhsOpcode{};
1218 if (!retrieveBinOpIntegerConstantExpr(Result, "lhs", LhsOpcode, LhsSymbol,
1219 LhsValue) ||
1220 !retrieveIntegerConstantExpr(Result, "rhs", RhsValue))
1221 return;
1222
1223 const unsigned ConstantWidth =
1224 std::max(LhsValue.getBitWidth(), RhsValue.getBitWidth());
1225 const llvm::APInt LhsConstant = LhsValue.extOrTrunc(ConstantWidth);
1226 const llvm::APInt RhsConstant = RhsValue.extOrTrunc(ConstantWidth);
1227 const SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1228
1229 // Check expression: x & k1 == k2 (i.e. x & 0xFF == 0xF00)
1230 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1231 if (Opcode == BO_EQ)
1232 diag(Loc, "logical expression is always false");
1233 else if (Opcode == BO_NE)
1234 diag(Loc, "logical expression is always true");
1235 }
1236
1237 // Check expression: x | k1 == k2 (i.e. x | 0xFF == 0xF00)
1238 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1239 if (Opcode == BO_EQ)
1240 diag(Loc, "logical expression is always false");
1241 else if (Opcode == BO_NE)
1242 diag(Loc, "logical expression is always true");
1243 }
1244 } else if (const auto *IneffectiveOperator =
1245 Result.Nodes.getNodeAs<BinaryOperator>(
1246 "ineffective-bitwise")) {
1247 APSInt Value;
1248 const Expr *Sym = nullptr, *ConstExpr = nullptr;
1249
1250 if (!retrieveSymbolicExpr(Result, "ineffective-bitwise", Sym) ||
1251 !retrieveIntegerConstantExpr(Result, "ineffective-bitwise", Value,
1252 ConstExpr))
1253 return;
1254
1255 if ((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
1256 return;
1257
1258 const SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1259
1260 const BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1261 if (exprEvaluatesToZero(Opcode, Value)) {
1262 diag(Loc, "expression always evaluates to 0");
1263 } else if (exprEvaluatesToBitwiseNegatedZero(Opcode, Value)) {
1264 const SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1265 ConstExpr->getEndLoc());
1266 const StringRef ConstExprText = Lexer::getSourceText(
1267 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1268 Result.Context->getLangOpts());
1269
1270 diag(Loc, "expression always evaluates to '%0'") << ConstExprText;
1271
1272 } else if (exprEvaluatesToSymbolic(Opcode, Value)) {
1273 const SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1274
1275 const StringRef ExprText = Lexer::getSourceText(
1276 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1277 Result.Context->getLangOpts());
1278
1279 diag(Loc, "expression always evaluates to '%0'") << ExprText;
1280 }
1281 }
1282}
1283
1284void RedundantExpressionCheck::checkRelationalExpr(
1285 const MatchFinder::MatchResult &Result) {
1286 if (const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1287 "comparisons-of-symbol-and-const")) {
1288 // Matched expressions are: (x <op> k1) <REL> (x <op> k2).
1289 // E.g.: (X < 2) && (X > 4)
1290 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1291
1292 const Expr *LhsExpr = nullptr, *RhsExpr = nullptr;
1293 const Expr *LhsSymbol = nullptr, *RhsSymbol = nullptr;
1294 const Expr *LhsConst = nullptr, *RhsConst = nullptr;
1295 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1296 APSInt LhsValue, RhsValue;
1297
1299 Result, "lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1301 Result, "rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1302 !areEquivalentExpr(LhsSymbol, RhsSymbol))
1303 return;
1304
1305 // Bring expr to a canonical form: smallest constant must be on the left.
1306 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1307 std::swap(LhsExpr, RhsExpr);
1308 std::swap(LhsValue, RhsValue);
1309 std::swap(LhsSymbol, RhsSymbol);
1310 std::swap(LhsOpcode, RhsOpcode);
1311 }
1312
1313 // Constants come from two different macros, or one of them is a macro.
1314 if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
1315 areExprsMacroAndNonMacro(LhsConst, RhsConst))
1316 return;
1317
1318 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1319 areEquivalentRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1320 diag(ComparisonOperator->getOperatorLoc(),
1321 "equivalent expression on both sides of logical operator");
1322 return;
1323 }
1324
1325 if (Opcode == BO_LAnd) {
1326 if (areExclusiveRanges(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1327 diag(ComparisonOperator->getOperatorLoc(),
1328 "logical expression is always false");
1329 } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1330 diag(LhsExpr->getExprLoc(), "expression is redundant");
1331 } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
1332 diag(RhsExpr->getExprLoc(), "expression is redundant");
1333 }
1334 }
1335
1336 if (Opcode == BO_LOr) {
1337 if (rangesFullyCoverDomain(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1338 diag(ComparisonOperator->getOperatorLoc(),
1339 "logical expression is always true");
1340 } else if (rangeSubsumesRange(LhsOpcode, LhsValue, RhsOpcode, RhsValue)) {
1341 diag(RhsExpr->getExprLoc(), "expression is redundant");
1342 } else if (rangeSubsumesRange(RhsOpcode, RhsValue, LhsOpcode, LhsValue)) {
1343 diag(LhsExpr->getExprLoc(), "expression is redundant");
1344 }
1345 }
1346 }
1347}
1348
1349void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
1350 if (const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>("binary")) {
1351 // If the expression's constants are macros, check whether they are
1352 // intentional.
1353
1354 //
1355 // Special case for floating-point representation.
1356 //
1357 // If expressions on both sides of comparison operator are of type float,
1358 // then for some comparison operators no warning shall be
1359 // reported even if the expressions are identical from a symbolic point of
1360 // view. Comparison between expressions, declared variables and literals
1361 // are treated differently.
1362 //
1363 // != and == between float literals that have the same value should NOT
1364 // warn. < > between float literals that have the same value SHOULD warn.
1365 //
1366 // != and == between the same float declaration should NOT warn.
1367 // < > between the same float declaration SHOULD warn.
1368 //
1369 // != and == between eq. expressions that evaluates into float
1370 // should NOT warn.
1371 // < > between eq. expressions that evaluates into float
1372 // should NOT warn.
1373 //
1374 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1375 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1376 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1377 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1378
1379 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1380 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1381 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1382 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1383
1384 if (DeclRef1 && DeclRef2 &&
1385 DeclRef1->getType()->hasFloatingRepresentation() &&
1386 DeclRef2->getType()->hasFloatingRepresentation() &&
1387 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1388 return;
1389 }
1390
1391 if (FloatLit1 && FloatLit2 &&
1392 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1393 OpEqualEQorNE) {
1394 return;
1395 }
1396
1398 BinOp, Result.Context)) {
1399 const Expr *LhsConst = nullptr, *RhsConst = nullptr;
1400 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1401 if (areSidesBinaryConstExpressions(BinOp, Result.Context)) {
1402 if (!retrieveConstExprFromBothSides(BinOp, MainOpcode, SideOpcode,
1403 LhsConst, RhsConst, Result.Context))
1404 return;
1405
1406 if (areExprsFromDifferentMacros(LhsConst, RhsConst, Result.Context) ||
1407 areExprsMacroAndNonMacro(LhsConst, RhsConst))
1408 return;
1409 } else {
1410 if (!areExprsSameMacroOrLiteral(BinOp, Result.Context))
1411 return;
1412 }
1413 }
1414 diag(BinOp->getOperatorLoc(), "both sides of operator are equivalent");
1415 }
1416
1417 if (const auto *CondOp =
1418 Result.Nodes.getNodeAs<ConditionalOperator>("cond")) {
1419 const Expr *TrueExpr = CondOp->getTrueExpr();
1420 const Expr *FalseExpr = CondOp->getFalseExpr();
1421
1422 if (areExprsFromDifferentMacros(TrueExpr, FalseExpr, Result.Context) ||
1423 areExprsMacroAndNonMacro(TrueExpr, FalseExpr))
1424 return;
1425 diag(CondOp->getColonLoc(),
1426 "'true' and 'false' expressions are equivalent");
1427 }
1428
1429 if (const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("call")) {
1431 return;
1432
1433 diag(Call->getOperatorLoc(),
1434 "both sides of overloaded operator are equivalent");
1435 }
1436
1437 if (const auto *Op = Result.Nodes.getNodeAs<Expr>("nested-duplicates")) {
1438 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1439 if (Call && canOverloadedOperatorArgsBeModified(Call, true))
1440 return;
1441
1442 const StringRef Message =
1443 Call ? "overloaded operator has equivalent nested operands"
1444 : "operator has equivalent nested operands";
1445
1446 const auto Diag = diag(Op->getExprLoc(), Message);
1447 for (const auto &KeyValue : Result.Nodes.getMap())
1448 if (StringRef(KeyValue.first).starts_with("duplicate"))
1449 Diag << KeyValue.second.getSourceRange();
1450 }
1451
1452 if (const auto *NegateOperator =
1453 Result.Nodes.getNodeAs<UnaryOperator>("logical-bitwise-confusion")) {
1454 const SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1455
1456 auto Diag =
1457 diag(OperatorLoc,
1458 "ineffective logical negation operator used; did you mean '~'?");
1459 const SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1460
1461 if (!LogicalNotLocation.isMacroID())
1462 Diag << FixItHint::CreateReplacement(
1463 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation), "~");
1464 }
1465
1466 if (const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1467 "left-right-shift-confusion")) {
1468 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
1469 assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
1470 std::optional<llvm::APSInt> ShiftingValue =
1471 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1472
1473 if (!ShiftingValue)
1474 return;
1475
1476 const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
1477 assert(AndConst && "Expr* 'AndCont' is nullptr!");
1478 std::optional<llvm::APSInt> AndValue =
1479 AndConst->getIntegerConstantExpr(*Result.Context);
1480 if (!AndValue)
1481 return;
1482
1483 // If ShiftingConst is shifted left with more bits than the position of the
1484 // leftmost 1 in the bit representation of AndValue, AndConstant is
1485 // ineffective.
1486 if (AndValue->getActiveBits() > *ShiftingValue)
1487 return;
1488
1489 auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1490 "ineffective bitwise and operation");
1491 }
1492
1493 // Check for the following bound expressions:
1494 // - "binop-const-compare-to-sym",
1495 // - "binop-const-compare-to-binop-const",
1496 // Produced message:
1497 // -> "logical expression is always false/true"
1498 checkArithmeticExpr(Result);
1499
1500 // Check for the following bound expression:
1501 // - "binop-const-compare-to-const",
1502 // - "ineffective-bitwise"
1503 // Produced message:
1504 // -> "logical expression is always false/true"
1505 // -> "expression always evaluates to ..."
1506 checkBitwiseExpr(Result);
1507
1508 // Check for te following bound expression:
1509 // - "comparisons-of-symbol-and-const",
1510 // Produced messages:
1511 // -> "equivalent expression on both sides of logical operator",
1512 // -> "logical expression is always false/true"
1513 // -> "expression is redundant"
1514 checkRelationalExpr(Result);
1515}
1516
1517} // namespace clang::tidy::misc
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool areExprsFromDifferentMacros(const Expr *LhsExpr, const Expr *RhsExpr, const ASTContext *AstCtx)
Returns true if both LhsExpr and RhsExpr are macro expressions and they are expanded from different m...
static const TExpr * checkOpKind(const Expr *TheExpr, OverloadedOperatorKind OpKind)
static constexpr StringRef KnownBannedMacroNames[]
static bool areSidesBinaryConstExpressions(const BinaryOperator *&BinOp, const ASTContext *AstCtx)
static bool markDuplicateOperands(const TExpr *TheExpr, ast_matchers::internal::BoundNodesTreeBuilder *Builder, ASTContext &Context)
static bool areEquivalentDeclRefExpr(const DeclRefExpr *L, const DeclRefExpr *R)
static bool collectOperands(const Expr *Part, SmallVector< const Expr *, N > &AllOperands, OverloadedOperatorKind OpKind)
static std::pair< const Expr *, const Expr * > getOperands(const BinaryOperator *Op)
static constexpr StringRef Message
static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp, BinaryOperatorKind &MainOpcode, BinaryOperatorKind &SideOpcode, const Expr *&LhsConst, const Expr *&RhsConst, const ASTContext *AstCtx)
static void transformSubToCanonicalAddExpr(BinaryOperatorKind &Opcode, APSInt &Value)
static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, APSInt &Value, const Expr *&ConstExpr)
static bool retrieveRelationalIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, const Expr *&OperandExpr, BinaryOperatorKind &Opcode, const Expr *&Symbol, APSInt &Value, const Expr *&ConstExpr)
static bool rangeSubsumesRange(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool areExclusiveRanges(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static ast_matchers::internal::Matcher< Expr > matchSymbolicExpr(StringRef Id)
static bool areStringsSameIgnoreSpaces(const StringRef Left, const StringRef Right)
static bool incrementWithoutOverflow(const APSInt &Value, APSInt &Result)
static bool areExprsMacroAndNonMacro(const Expr *&LhsExpr, const Expr *&RhsExpr)
static bool isSameRawIdentifierToken(const Token &T1, const Token &T2, const SourceManager &SM)
static bool areSidesBinaryConstExpressionsOrDefinesOrIntegerConstant(const BinaryOperator *&BinOp, const ASTContext *AstCtx)
static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, const SourceManager &SM)
static bool areEquivalentExpr(const Expr *Left, const Expr *Right)
static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool isNonConstReferenceType(QualType ParamType)
static ast_matchers::internal::Matcher< Expr > matchIntegerConstantExpr(StringRef Id)
static OverloadedOperatorKind getOp(const BinaryOperator *Op)
static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode, const APSInt &Value)
static ast_matchers::internal::Matcher< Expr > matchBinOpIntegerConstantExpr(StringRef Id)
static bool hasSameOperatorParent(const Expr *TheExpr, OverloadedOperatorKind OpKind, ASTContext &Context)
static bool retrieveSymbolicExpr(const MatchFinder::MatchResult &Result, StringRef Id, const Expr *&SymExpr)
static bool areEquivalentRanges(BinaryOperatorKind OpcodeLHS, const APSInt &ValueLHS, BinaryOperatorKind OpcodeRHS, const APSInt &ValueRHS)
static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp, const ASTContext *Context)
static bool retrieveBinOpIntegerConstantExpr(const MatchFinder::MatchResult &Result, StringRef Id, BinaryOperatorKind &Opcode, const Expr *&Symbol, APSInt &Value)
static ast_matchers::internal::Matcher< Expr > matchRelationalIntegerConstantExpr(StringRef Id)
static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, const APSInt &Value)
static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, const APSInt &Value)
static bool canOverloadedOperatorArgsBeModified(const CXXOperatorCallExpr *OperatorCall, bool CheckSecondParam)