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/SmallBitVector.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.h"
44 return Value < Result;
48 const DeclRefExpr *R) {
49 if (L->getDecl() != R->getDecl())
52 const PrintingPolicy &Policy =
53 L->getDecl()->getASTContext().getPrintingPolicy();
55 if (L->hasQualifier() && R->hasQualifier()) {
56 std::string LQual, RQual;
57 llvm::raw_string_ostream LOS(LQual), ROS(RQual);
58 L->getQualifier().print(LOS, Policy);
59 R->getQualifier().print(ROS, Policy);
64 if (L->hasExplicitTemplateArgs() != R->hasExplicitTemplateArgs())
66 if (L->hasExplicitTemplateArgs()) {
67 if (L->getNumTemplateArgs() != R->getNumTemplateArgs())
70 return llvm::equal(L->template_arguments(), R->template_arguments(),
71 [&Policy](
const TemplateArgumentLoc &LArg,
72 const TemplateArgumentLoc &RArg) {
73 std::string LStr, RStr;
74 llvm::raw_string_ostream LOS(LStr), ROS(RStr);
75 LArg.getArgument().print(Policy, LOS, true);
76 RArg.getArgument().print(Policy, ROS, true);
85 return !Left && !Right;
87 Left = Left->IgnoreParens();
88 Right = Right->IgnoreParens();
91 if (Left->getStmtClass() != Right->getStmtClass())
95 Expr::const_child_iterator LeftIter = Left->child_begin();
96 Expr::const_child_iterator RightIter = Right->child_begin();
97 while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
99 dyn_cast_or_null<Expr>(*RightIter)))
104 if (LeftIter != Left->child_end() || RightIter != Right->child_end())
108 switch (Left->getStmtClass()) {
112 case Stmt::CharacterLiteralClass:
113 return cast<CharacterLiteral>(Left)->getValue() ==
114 cast<CharacterLiteral>(Right)->getValue();
115 case Stmt::IntegerLiteralClass: {
116 const llvm::APInt LeftLit = cast<IntegerLiteral>(Left)->getValue();
117 const llvm::APInt RightLit = cast<IntegerLiteral>(Right)->getValue();
118 return LeftLit.getBitWidth() == RightLit.getBitWidth() &&
121 case Stmt::FloatingLiteralClass:
122 return cast<FloatingLiteral>(Left)->getValue().bitwiseIsEqual(
123 cast<FloatingLiteral>(Right)->getValue());
124 case Stmt::StringLiteralClass:
125 return cast<StringLiteral>(Left)->getBytes() ==
126 cast<StringLiteral>(Right)->getBytes();
127 case Stmt::CXXOperatorCallExprClass:
128 return cast<CXXOperatorCallExpr>(Left)->getOperator() ==
129 cast<CXXOperatorCallExpr>(Right)->getOperator();
130 case Stmt::DependentScopeDeclRefExprClass:
131 if (cast<DependentScopeDeclRefExpr>(Left)->getDeclName() !=
132 cast<DependentScopeDeclRefExpr>(Right)->getDeclName())
134 return cast<DependentScopeDeclRefExpr>(Left)->getQualifier() ==
135 cast<DependentScopeDeclRefExpr>(Right)->getQualifier();
136 case Stmt::DeclRefExprClass:
138 cast<DeclRefExpr>(Right));
139 case Stmt::MemberExprClass:
140 return cast<MemberExpr>(Left)->getMemberDecl() ==
141 cast<MemberExpr>(Right)->getMemberDecl();
142 case Stmt::CXXFoldExprClass:
143 return cast<CXXFoldExpr>(Left)->getOperator() ==
144 cast<CXXFoldExpr>(Right)->getOperator();
145 case Stmt::CXXFunctionalCastExprClass:
146 case Stmt::CStyleCastExprClass:
147 return cast<ExplicitCastExpr>(Left)->getTypeAsWritten() ==
148 cast<ExplicitCastExpr>(Right)->getTypeAsWritten();
149 case Stmt::CallExprClass:
150 case Stmt::ImplicitCastExprClass:
151 case Stmt::ArraySubscriptExprClass:
153 case Stmt::UnaryOperatorClass:
154 if (cast<UnaryOperator>(Left)->isIncrementDecrementOp())
156 return cast<UnaryOperator>(Left)->getOpcode() ==
157 cast<UnaryOperator>(Right)->getOpcode();
158 case Stmt::BinaryOperatorClass:
159 if (cast<BinaryOperator>(Left)->isAssignmentOp())
161 return cast<BinaryOperator>(Left)->getOpcode() ==
162 cast<BinaryOperator>(Right)->getOpcode();
163 case Stmt::UnaryExprOrTypeTraitExprClass:
164 const auto *LeftUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Left);
165 const auto *RightUnaryExpr = cast<UnaryExprOrTypeTraitExpr>(Right);
166 if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
167 return LeftUnaryExpr->getKind() == RightUnaryExpr->getKind() &&
168 LeftUnaryExpr->getArgumentType() ==
169 RightUnaryExpr->getArgumentType();
170 if (!LeftUnaryExpr->isArgumentType() && !RightUnaryExpr->isArgumentType())
172 RightUnaryExpr->getArgumentExpr());
181 const APSInt &ValueLHS,
182 BinaryOperatorKind OpcodeRHS,
183 const APSInt &ValueRHS) {
184 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
185 "Values must be ordered");
187 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0)
188 return OpcodeLHS == OpcodeRHS;
191 APSInt ValueLhsPlus1;
192 return ((OpcodeLHS == BO_LE && OpcodeRHS == BO_LT) ||
193 (OpcodeLHS == BO_GT && OpcodeRHS == BO_GE)) &&
195 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0;
201 const APSInt &ValueLHS,
202 BinaryOperatorKind OpcodeRHS,
203 const APSInt &ValueRHS) {
204 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
205 "Values must be ordered");
208 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
211 return OpcodeRHS == BO_NE || OpcodeRHS == BO_GT || OpcodeRHS == BO_LT;
213 return OpcodeRHS == BO_EQ;
215 return OpcodeRHS == BO_GT;
217 return OpcodeRHS == BO_LT;
219 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
221 return OpcodeRHS == BO_EQ || OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
228 if ((OpcodeLHS == BO_EQ || OpcodeLHS == BO_LT || OpcodeLHS == BO_LE) &&
229 (OpcodeRHS == BO_EQ || OpcodeRHS == BO_GT || OpcodeRHS == BO_GE))
233 APSInt ValueLhsPlus1;
234 if (OpcodeLHS == BO_GT && OpcodeRHS == BO_LT &&
236 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
245 const APSInt &ValueLHS,
246 BinaryOperatorKind OpcodeRHS,
247 const APSInt &ValueRHS) {
248 assert(APSInt::compareValues(ValueLHS, ValueRHS) <= 0 &&
249 "Values must be ordered");
252 if (APSInt::compareValues(ValueLHS, ValueRHS) == 0) {
255 return OpcodeRHS == BO_NE;
257 return OpcodeRHS == BO_EQ;
259 return OpcodeRHS == BO_GT || OpcodeRHS == BO_GE;
261 return OpcodeRHS == BO_GE;
263 return OpcodeRHS == BO_LT || OpcodeRHS == BO_LE;
265 return OpcodeRHS == BO_LE;
272 APSInt ValueLhsPlus1;
273 if (OpcodeLHS == BO_LE && OpcodeRHS == BO_GE &&
275 APSInt::compareValues(ValueLhsPlus1, ValueRHS) == 0)
279 if ((OpcodeLHS == BO_GT || OpcodeLHS == BO_GE) &&
280 (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE))
285 if (OpcodeLHS == BO_NE && OpcodeRHS == BO_NE)
292 const APSInt &ValueLHS,
293 BinaryOperatorKind OpcodeRHS,
294 const APSInt &ValueRHS) {
295 const int Comparison = APSInt::compareValues(ValueLHS, ValueRHS);
298 return OpcodeRHS == BO_EQ && Comparison == 0;
300 return (OpcodeRHS == BO_NE && Comparison == 0) ||
301 (OpcodeRHS == BO_EQ && Comparison != 0) ||
302 (OpcodeRHS == BO_LT && Comparison >= 0) ||
303 (OpcodeRHS == BO_LE && Comparison > 0) ||
304 (OpcodeRHS == BO_GT && Comparison <= 0) ||
305 (OpcodeRHS == BO_GE && Comparison < 0);
308 return ((OpcodeRHS == BO_LT && Comparison >= 0) ||
309 (OpcodeRHS == BO_LE && Comparison > 0) ||
310 (OpcodeRHS == BO_EQ && Comparison > 0));
312 return ((OpcodeRHS == BO_GT && Comparison <= 0) ||
313 (OpcodeRHS == BO_GE && Comparison < 0) ||
314 (OpcodeRHS == BO_EQ && Comparison < 0));
316 return (OpcodeRHS == BO_LT || OpcodeRHS == BO_LE || OpcodeRHS == BO_EQ) &&
319 return (OpcodeRHS == BO_GT || OpcodeRHS == BO_GE || OpcodeRHS == BO_EQ) &&
328 if (Opcode == BO_Sub) {
335static OverloadedOperatorKind
getOp(
const BinaryOperator *Op) {
336 return BinaryOperator::getOverloadedOperator(Op->getOpcode());
339static OverloadedOperatorKind
getOp(
const CXXOperatorCallExpr *Op) {
340 if (Op->getNumArgs() != 2)
342 return Op->getOperator();
345static std::pair<const Expr *, const Expr *>
347 return {Op->getLHS()->IgnoreParenImpCasts(),
348 Op->getRHS()->IgnoreParenImpCasts()};
351static std::pair<const Expr *, const Expr *>
353 return {Op->getArg(0)->IgnoreParenImpCasts(),
354 Op->getArg(1)->IgnoreParenImpCasts()};
357template <
typename TExpr>
359 OverloadedOperatorKind OpKind) {
360 const auto *AsTExpr = dyn_cast_or_null<TExpr>(TheExpr);
361 if (AsTExpr &&
getOp(AsTExpr) == OpKind)
369template <
typename TExpr,
unsigned N>
372 OverloadedOperatorKind OpKind) {
374 const std::pair<const Expr *, const Expr *> Operands =
getOperands(BinOp);
381 AllOperands.push_back(Part);
385template <
typename TExpr>
387 OverloadedOperatorKind OpKind,
388 ASTContext &Context) {
390 const DynTypedNodeList Parents = Context.getParents(*TheExpr);
391 for (
const DynTypedNode DynParent : Parents) {
392 if (
const auto *Parent = DynParent.get<Expr>()) {
394 isa<ParenExpr>(Parent) || isa<ImplicitCastExpr>(Parent) ||
395 isa<FullExpr>(Parent) || isa<MaterializeTemporaryExpr>(Parent);
407 const SourceManager &SM) {
408 if (T1.getKind() != T2.getKind())
410 if (T1.isNot(tok::raw_identifier))
412 if (T1.getLength() != T2.getLength())
414 return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
415 StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
419 const SourceManager &SM) {
420 return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
428 const ASTContext *AstCtx) {
429 if (!LhsExpr || !RhsExpr)
431 const SourceRange Lsr = LhsExpr->getSourceRange();
432 const SourceRange Rsr = RhsExpr->getSourceRange();
433 if (!Lsr.getBegin().isMacroID() || !Rsr.getBegin().isMacroID())
436 const SourceManager &SM = AstCtx->getSourceManager();
437 const LangOptions &LO = AstCtx->getLangOpts();
439 const std::pair<FileID, unsigned> LsrLocInfo =
440 SM.getDecomposedLoc(SM.getExpansionLoc(Lsr.getBegin()));
441 const std::pair<FileID, unsigned> RsrLocInfo =
442 SM.getDecomposedLoc(SM.getExpansionLoc(Rsr.getBegin()));
443 const llvm::MemoryBufferRef MB = SM.getBufferOrFake(LsrLocInfo.first);
445 const char *LTokenPos = MB.getBufferStart() + LsrLocInfo.second;
446 const char *RTokenPos = MB.getBufferStart() + RsrLocInfo.second;
447 Lexer LRawLex(SM.getLocForStartOfFile(LsrLocInfo.first), LO,
448 MB.getBufferStart(), LTokenPos, MB.getBufferEnd());
449 Lexer RRawLex(SM.getLocForStartOfFile(RsrLocInfo.first), LO,
450 MB.getBufferStart(), RTokenPos, MB.getBufferEnd());
454 LRawLex.LexFromRawLexer(LTok);
455 RRawLex.LexFromRawLexer(RTok);
456 }
while (!LTok.is(tok::eof) && !RTok.is(tok::eof) &&
466 const Expr *&RhsExpr) {
467 if (!LhsExpr || !RhsExpr)
470 const SourceLocation LhsLoc = LhsExpr->getExprLoc();
471 const SourceLocation RhsLoc = RhsExpr->getExprLoc();
473 return LhsLoc.isMacroID() != RhsLoc.isMacroID();
476template <
typename TExpr>
479 ast_matchers::internal::BoundNodesTreeBuilder *Builder,
480 ASTContext &Context) {
481 const OverloadedOperatorKind OpKind =
getOp(TheExpr);
482 if (OpKind == OO_None)
486 const std::pair<const Expr *, const Expr *> Operands =
getOperands(TheExpr);
501 const size_t NumOperands = AllOperands.size();
502 llvm::SmallBitVector Duplicates(NumOperands);
503 for (
size_t I = 0; I < NumOperands; I++) {
506 bool FoundDuplicates =
false;
508 for (
size_t J = I + 1; J < NumOperands; J++) {
509 if (AllOperands[J]->HasSideEffects(Context))
512 const Expr *Lhs = AllOperands[I];
513 const Expr *Rhs = AllOperands[J];
519 FoundDuplicates =
true;
521 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", J)),
522 DynTypedNode::create(*Rhs));
526 Builder->setBinding(SmallString<11>(llvm::formatv(
"duplicate{0}", I)),
527 DynTypedNode::create(*AllOperands[I]));
530 return Duplicates.any();
536 if (Node.isInstantiationDependent())
538 return Node.isIntegerConstantExpr(Finder->getASTContext());
541AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
545AST_MATCHER(BinaryOperator, nestedOperandsAreEquivalent) {
549AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
554 return Node.getNumArgs() == 2 &&
558AST_MATCHER(CXXOperatorCallExpr, nestedParametersAreEquivalent) {
562AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
563 return Node.getOperatorLoc().isMacroID();
566AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
567 return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
570AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<StringRef>, Names) {
571 const SourceManager &SM = Finder->getASTContext().getSourceManager();
572 const LangOptions &LO = Finder->getASTContext().getLangOpts();
573 SourceLocation Loc = Node.getExprLoc();
574 while (Loc.isMacroID()) {
575 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LO);
576 if (llvm::is_contained(Names, MacroName))
578 Loc = SM.getImmediateMacroCallerLoc(Loc);
586static ast_matchers::internal::Matcher<Expr>
588 const std::string CstId = (Id +
"-const").str();
589 return expr(isIntegerConstantExpr()).bind(CstId);
596 StringRef Id, APSInt &Value,
597 const Expr *&ConstExpr) {
598 const std::string CstId = (Id +
"-const").str();
599 ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
602 std::optional<llvm::APSInt> R =
603 ConstExpr->getIntegerConstantExpr(*Result.Context);
612 StringRef Id, APSInt &Value) {
613 const Expr *ConstExpr =
nullptr;
620 const std::string SymId = (Id +
"-sym").str();
621 return ignoringParenImpCasts(
622 expr(unless(isIntegerConstantExpr())).bind(SymId));
628 StringRef Id,
const Expr *&SymExpr) {
629 const std::string SymId = (Id +
"-sym").str();
630 if (
const auto *Node = Result.Nodes.getNodeAs<Expr>(SymId)) {
639static ast_matchers::internal::Matcher<Expr>
641 const auto BinOpCstExpr =
642 expr(anyOf(binaryOperator(hasAnyOperatorName(
"+",
"|",
"&"),
645 binaryOperator(hasOperatorName(
"-"),
649 return ignoringParenImpCasts(BinOpCstExpr);
656 StringRef Id, BinaryOperatorKind &Opcode,
657 const Expr *&Symbol, APSInt &Value) {
658 if (
const auto *BinExpr = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
659 Opcode = BinExpr->getOpcode();
667static ast_matchers::internal::Matcher<Expr>
669 const std::string CastId = (Id +
"-cast").str();
670 const std::string SwapId = (Id +
"-swap").str();
671 const std::string NegateId = (Id +
"-negate").str();
672 const std::string OverloadId = (Id +
"-overload").str();
673 const std::string ConstId = (Id +
"-const").str();
675 const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
676 isComparisonOperator(), expr().bind(Id),
684 const auto CastExpr =
685 implicitCastExpr(hasCastKind(CK_IntegralToBoolean),
689 const auto NegateRelationalExpr =
690 unaryOperator(hasOperatorName(
"!"),
691 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))
695 const auto NegateNegateRelationalExpr =
696 unaryOperator(hasOperatorName(
"!"),
697 hasUnaryOperand(unaryOperator(
698 hasOperatorName(
"!"),
699 hasUnaryOperand(anyOf(CastExpr, RelationalExpr)))));
701 const auto OverloadedOperatorExpr =
703 hasAnyOverloadedOperatorName(
"==",
"!=",
"<",
"<=",
">",
">="),
705 unless(isMacroID()), unless(isInTemplateInstantiation()),
706 anyOf(hasLHS(ignoringParenImpCasts(integerLiteral().bind(ConstId))),
707 hasRHS(ignoringParenImpCasts(integerLiteral().bind(ConstId)))))
710 return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
711 NegateNegateRelationalExpr, OverloadedOperatorExpr);
717 return ParamType->isReferenceType() &&
718 !ParamType.getNonReferenceType().isConstQualified();
729 bool CheckSecondParam) {
730 const auto *OperatorDecl =
731 dyn_cast_or_null<FunctionDecl>(OperatorCall->getCalleeDecl());
737 const unsigned ParamCount = OperatorDecl->getNumParams();
742 if (ParamCount == 1 &&
743 !OperatorDecl->getType()->castAs<FunctionType>()->isConst())
749 return CheckSecondParam && ParamCount == 2 &&
756 const MatchFinder::MatchResult &Result, StringRef Id,
757 const Expr *&OperandExpr, BinaryOperatorKind &Opcode,
const Expr *&Symbol,
758 APSInt &Value,
const Expr *&ConstExpr) {
759 const std::string CastId = (Id +
"-cast").str();
760 const std::string SwapId = (Id +
"-swap").str();
761 const std::string NegateId = (Id +
"-negate").str();
762 const std::string OverloadId = (Id +
"-overload").str();
764 if (
const auto *Bin = Result.Nodes.getNodeAs<BinaryOperator>(Id)) {
766 Opcode = Bin->getOpcode();
771 }
else if (
const auto *Cast = Result.Nodes.getNodeAs<CastExpr>(CastId)) {
775 Value = APSInt(32,
false);
776 }
else if (
const auto *OverloadedOperatorExpr =
777 Result.Nodes.getNodeAs<CXXOperatorCallExpr>(OverloadId)) {
781 bool IntegerConstantIsFirstArg =
false;
783 if (
const auto *Arg = OverloadedOperatorExpr->getArg(1)) {
784 if (!Arg->isValueDependent() &&
785 !Arg->isIntegerConstantExpr(*Result.Context)) {
786 IntegerConstantIsFirstArg =
true;
787 if (
const auto *Arg = OverloadedOperatorExpr->getArg(0)) {
788 if (!Arg->isValueDependent() &&
789 !Arg->isIntegerConstantExpr(*Result.Context))
799 Symbol = OverloadedOperatorExpr->getArg(IntegerConstantIsFirstArg ? 1 : 0);
800 OperandExpr = OverloadedOperatorExpr;
801 Opcode = BinaryOperator::getOverloadedOpcode(
802 OverloadedOperatorExpr->getOperator());
807 if (!BinaryOperator::isComparisonOp(Opcode))
812 if (IntegerConstantIsFirstArg)
813 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
823 if (Result.Nodes.getNodeAs<Expr>(SwapId))
824 Opcode = BinaryOperator::reverseComparisonOp(Opcode);
825 if (Result.Nodes.getNodeAs<Expr>(NegateId))
826 Opcode = BinaryOperator::negateComparisonOp(Opcode);
832 const ASTContext *AstCtx) {
833 const auto *LhsBinOp = dyn_cast<BinaryOperator>(BinOp->getLHS());
834 const auto *RhsBinOp = dyn_cast<BinaryOperator>(BinOp->getRHS());
836 if (!LhsBinOp || !RhsBinOp)
839 const auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
840 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
843 if ((IsIntegerConstantExpr(LhsBinOp->getLHS()) ||
844 IsIntegerConstantExpr(LhsBinOp->getRHS())) &&
845 (IsIntegerConstantExpr(RhsBinOp->getLHS()) ||
846 IsIntegerConstantExpr(RhsBinOp->getRHS())))
852 const BinaryOperator *&BinOp,
const ASTContext *AstCtx) {
856 const Expr *Lhs = BinOp->getLHS();
857 const Expr *Rhs = BinOp->getRHS();
862 const auto IsDefineExpr = [AstCtx](
const Expr *E) {
863 const SourceRange Lsr = E->getSourceRange();
864 if (!Lsr.getBegin().isMacroID() || E->isValueDependent() ||
865 !E->isIntegerConstantExpr(*AstCtx))
870 return IsDefineExpr(Lhs) || IsDefineExpr(Rhs);
877 BinaryOperatorKind &MainOpcode,
878 BinaryOperatorKind &SideOpcode,
879 const Expr *&LhsConst,
880 const Expr *&RhsConst,
881 const ASTContext *AstCtx) {
883 "Both sides of binary operator must be constant expressions!");
885 MainOpcode = BinOp->getOpcode();
887 const auto *BinOpLhs = cast<BinaryOperator>(BinOp->getLHS());
888 const auto *BinOpRhs = cast<BinaryOperator>(BinOp->getRHS());
890 const auto IsIntegerConstantExpr = [AstCtx](
const Expr *E) {
891 return !E->isValueDependent() && E->isIntegerConstantExpr(*AstCtx);
894 LhsConst = IsIntegerConstantExpr(BinOpLhs->getLHS()) ? BinOpLhs->getLHS()
895 : BinOpLhs->getRHS();
896 RhsConst = IsIntegerConstantExpr(BinOpRhs->getLHS()) ? BinOpRhs->getLHS()
897 : BinOpRhs->getRHS();
899 if (!LhsConst || !RhsConst)
902 assert(BinOpLhs->getOpcode() == BinOpRhs->getOpcode() &&
903 "Sides of the binary operator must be equivalent expressions!");
905 SideOpcode = BinOpLhs->getOpcode();
911 const StringRef Right) {
916 StringRef L = Left.trim();
917 StringRef R = Right.trim();
918 while (!L.empty() && !R.empty()) {
921 if (L.empty() && R.empty())
924 if (L.front() != R.front())
929 return L.empty() && R.empty();
933 const ASTContext *Context) {
937 const Expr *Lhs = BinOp->getLHS();
938 const Expr *Rhs = BinOp->getRHS();
939 const SourceManager &SM = Context->getSourceManager();
941 const SourceRange Lsr = Lhs->getSourceRange();
942 const SourceRange Rsr = Rhs->getSourceRange();
943 if (Lsr.getBegin().isMacroID()) {
945 if (Rsr.getBegin().isMacroID()) {
947 const StringRef L = Lexer::getSourceText(
948 CharSourceRange::getTokenRange(Lsr), SM, Context->getLangOpts());
949 const StringRef R = Lexer::getSourceText(
950 CharSourceRange::getTokenRange(Rsr), SM, Context->getLangOpts());
956 const auto *Lil = dyn_cast<IntegerLiteral>(Lhs);
957 const auto *Ril = dyn_cast<IntegerLiteral>(Rhs);
959 return Lil->getValue() == Ril->getValue();
961 const auto *Lbl = dyn_cast<CXXBoolLiteralExpr>(Lhs);
962 const auto *Rbl = dyn_cast<CXXBoolLiteralExpr>(Rhs);
964 return Lbl->getValue() == Rbl->getValue();
970 const auto BannedIntegerLiteral =
972 const auto IsInUnevaluatedContext = expr(anyOf(
973 hasAncestor(expr(hasUnevaluatedContext())), hasAncestor(typeLoc())));
978 binaryOperator(anyOf(isComparisonOperator(),
979 hasAnyOperatorName(
"-",
"/",
"%",
"|",
"&",
980 "^",
"&&",
"||",
"=")),
981 operandsAreEquivalent(),
983 unless(isInTemplateInstantiation()),
984 unless(binaryOperatorIsInMacro()),
985 unless(hasAncestor(arraySubscriptExpr())),
986 unless(hasDescendant(BannedIntegerLiteral)),
987 unless(IsInUnevaluatedContext))
994 binaryOperator(hasAnyOperatorName(
"|",
"&",
"||",
"&&",
"^"),
995 nestedOperandsAreEquivalent(),
997 unless(isInTemplateInstantiation()),
998 unless(binaryOperatorIsInMacro()),
1000 unless(hasDescendant(BannedIntegerLiteral)),
1001 unless(IsInUnevaluatedContext))
1002 .bind(
"nested-duplicates"),
1008 conditionalOperator(expressionsAreEquivalent(),
1010 unless(conditionalOperatorIsInMacro()),
1011 unless(isInTemplateInstantiation()),
1012 unless(IsInUnevaluatedContext))
1019 cxxOperatorCallExpr(
1020 hasAnyOverloadedOperatorName(
"-",
"/",
"%",
"|",
"&",
"^",
1021 "==",
"!=",
"<",
"<=",
">",
1022 ">=",
"&&",
"||",
"="),
1023 parametersAreEquivalent(),
1025 unless(isMacroID()), unless(isInTemplateInstantiation()),
1026 unless(IsInUnevaluatedContext))
1032 cxxOperatorCallExpr(
1033 hasAnyOverloadedOperatorName(
"|",
"&",
"||",
"&&",
"^"),
1034 nestedParametersAreEquivalent(), argumentCountIs(2),
1036 unless(isMacroID()), unless(isInTemplateInstantiation()),
1037 unless(IsInUnevaluatedContext))
1038 .bind(
"nested-duplicates"),
1045 hasImplicitDestinationType(isInteger()),
1047 hasOperatorName(
"!"),
1048 hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
1049 hasAnyOperatorName(
"|",
"&"),
1051 binaryOperator(hasAnyOperatorName(
"|",
"&")),
1053 hasRHS(integerLiteral())))))
1054 .bind(
"logical-bitwise-confusion")),
1055 unless(IsInUnevaluatedContext))),
1062 hasOperatorName(
"&"),
1063 hasOperands(ignoringParenImpCasts(binaryOperator(
1064 hasOperatorName(
"<<"),
1065 hasRHS(ignoringParenImpCasts(
1066 integerLiteral().bind(
"shift-const"))))),
1067 ignoringParenImpCasts(
1068 integerLiteral().bind(
"and-const"))),
1069 unless(IsInUnevaluatedContext))
1070 .bind(
"left-right-shift-confusion")),
1086 traverse(TK_AsIs, binaryOperator(isComparisonOperator(),
1087 hasOperands(BinOpCstLeft, CstRight),
1088 unless(IsInUnevaluatedContext))
1089 .bind(
"binop-const-compare-to-const")),
1096 binaryOperator(isComparisonOperator(),
1097 anyOf(allOf(hasLHS(BinOpCstLeft), hasRHS(SymRight)),
1098 allOf(hasLHS(SymRight), hasRHS(BinOpCstLeft))),
1099 unless(IsInUnevaluatedContext))
1100 .bind(
"binop-const-compare-to-sym")),
1106 binaryOperator(isComparisonOperator(), hasLHS(BinOpCstLeft),
1107 hasRHS(BinOpCstRight),
1109 unless(operandsAreEquivalent()),
1110 unless(IsInUnevaluatedContext))
1111 .bind(
"binop-const-compare-to-binop-const")),
1123 binaryOperator(hasAnyOperatorName(
"||",
"&&"),
1124 hasLHS(ComparisonLeft), hasRHS(ComparisonRight),
1126 unless(operandsAreEquivalent()),
1127 unless(IsInUnevaluatedContext))
1128 .bind(
"comparisons-of-symbol-and-const")),
1132void RedundantExpressionCheck::checkArithmeticExpr(
1133 const MatchFinder::MatchResult &Result) {
1134 APSInt LhsValue, RhsValue;
1135 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1136 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1138 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1139 "binop-const-compare-to-sym")) {
1140 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1148 if (LhsOpcode == BO_Add || LhsOpcode == BO_Sub) {
1149 if ((LhsValue != 0 && Opcode == BO_EQ) ||
1150 (LhsValue == 0 && Opcode == BO_NE))
1151 diag(ComparisonOperator->getOperatorLoc(),
1152 "logical expression is always false");
1153 else if ((LhsValue == 0 && Opcode == BO_EQ) ||
1154 (LhsValue != 0 && Opcode == BO_NE))
1155 diag(ComparisonOperator->getOperatorLoc(),
1156 "logical expression is always true");
1158 }
else if (
const auto *ComparisonOperator =
1159 Result.Nodes.getNodeAs<BinaryOperator>(
1160 "binop-const-compare-to-binop-const")) {
1161 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1174 if (LhsOpcode == BO_Add && RhsOpcode == BO_Add) {
1175 if ((Opcode == BO_EQ && APSInt::compareValues(LhsValue, RhsValue) == 0) ||
1176 (Opcode == BO_NE && APSInt::compareValues(LhsValue, RhsValue) != 0)) {
1177 diag(ComparisonOperator->getOperatorLoc(),
1178 "logical expression is always true");
1179 }
else if ((Opcode == BO_EQ &&
1180 APSInt::compareValues(LhsValue, RhsValue) != 0) ||
1182 APSInt::compareValues(LhsValue, RhsValue) == 0)) {
1183 diag(ComparisonOperator->getOperatorLoc(),
1184 "logical expression is always false");
1191 const APSInt &Value) {
1192 return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
1196 const APSInt &Value) {
1197 return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
1201 const APSInt &Value) {
1202 return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
1203 ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
1206void RedundantExpressionCheck::checkBitwiseExpr(
1207 const MatchFinder::MatchResult &Result) {
1208 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1209 "binop-const-compare-to-const")) {
1210 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1212 APSInt LhsValue, RhsValue;
1213 const Expr *LhsSymbol =
nullptr;
1214 BinaryOperatorKind LhsOpcode{};
1220 const unsigned ConstantWidth =
1221 std::max(LhsValue.getBitWidth(), RhsValue.getBitWidth());
1222 const llvm::APInt LhsConstant = LhsValue.extOrTrunc(ConstantWidth);
1223 const llvm::APInt RhsConstant = RhsValue.extOrTrunc(ConstantWidth);
1224 const SourceLocation Loc = ComparisonOperator->getOperatorLoc();
1227 if (LhsOpcode == BO_And && (LhsConstant & RhsConstant) != RhsConstant) {
1228 if (Opcode == BO_EQ)
1229 diag(Loc,
"logical expression is always false");
1230 else if (Opcode == BO_NE)
1231 diag(Loc,
"logical expression is always true");
1235 if (LhsOpcode == BO_Or && (LhsConstant | RhsConstant) != RhsConstant) {
1236 if (Opcode == BO_EQ)
1237 diag(Loc,
"logical expression is always false");
1238 else if (Opcode == BO_NE)
1239 diag(Loc,
"logical expression is always true");
1241 }
else if (
const auto *IneffectiveOperator =
1242 Result.Nodes.getNodeAs<BinaryOperator>(
1243 "ineffective-bitwise")) {
1245 const Expr *Sym =
nullptr, *ConstExpr =
nullptr;
1252 if ((Value != 0 && ~Value != 0) || Sym->getExprLoc().isMacroID())
1255 const SourceLocation Loc = IneffectiveOperator->getOperatorLoc();
1257 const BinaryOperatorKind Opcode = IneffectiveOperator->getOpcode();
1259 diag(Loc,
"expression always evaluates to 0");
1261 const SourceRange ConstExprRange(ConstExpr->getBeginLoc(),
1262 ConstExpr->getEndLoc());
1263 const StringRef ConstExprText = Lexer::getSourceText(
1264 CharSourceRange::getTokenRange(ConstExprRange), *Result.SourceManager,
1265 Result.Context->getLangOpts());
1267 diag(Loc,
"expression always evaluates to '%0'") << ConstExprText;
1270 const SourceRange SymExprRange(Sym->getBeginLoc(), Sym->getEndLoc());
1272 const StringRef ExprText = Lexer::getSourceText(
1273 CharSourceRange::getTokenRange(SymExprRange), *Result.SourceManager,
1274 Result.Context->getLangOpts());
1276 diag(Loc,
"expression always evaluates to '%0'") << ExprText;
1281void RedundantExpressionCheck::checkRelationalExpr(
1282 const MatchFinder::MatchResult &Result) {
1283 if (
const auto *ComparisonOperator = Result.Nodes.getNodeAs<BinaryOperator>(
1284 "comparisons-of-symbol-and-const")) {
1287 const BinaryOperatorKind Opcode = ComparisonOperator->getOpcode();
1289 const Expr *LhsExpr =
nullptr, *RhsExpr =
nullptr;
1290 const Expr *LhsSymbol =
nullptr, *RhsSymbol =
nullptr;
1291 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1292 BinaryOperatorKind LhsOpcode{}, RhsOpcode{};
1293 APSInt LhsValue, RhsValue;
1296 Result,
"lhs", LhsExpr, LhsOpcode, LhsSymbol, LhsValue, LhsConst) ||
1298 Result,
"rhs", RhsExpr, RhsOpcode, RhsSymbol, RhsValue, RhsConst) ||
1303 if (APSInt::compareValues(LhsValue, RhsValue) > 0) {
1304 std::swap(LhsExpr, RhsExpr);
1305 std::swap(LhsValue, RhsValue);
1306 std::swap(LhsSymbol, RhsSymbol);
1307 std::swap(LhsOpcode, RhsOpcode);
1315 if ((Opcode == BO_LAnd || Opcode == BO_LOr) &&
1317 diag(ComparisonOperator->getOperatorLoc(),
1318 "equivalent expression on both sides of logical operator");
1322 if (Opcode == BO_LAnd) {
1324 diag(ComparisonOperator->getOperatorLoc(),
1325 "logical expression is always false");
1327 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1329 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1333 if (Opcode == BO_LOr) {
1335 diag(ComparisonOperator->getOperatorLoc(),
1336 "logical expression is always true");
1338 diag(RhsExpr->getExprLoc(),
"expression is redundant");
1340 diag(LhsExpr->getExprLoc(),
"expression is redundant");
1347 if (
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binary")) {
1371 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
1372 const Expr *RHS = BinOp->getRHS()->IgnoreParenImpCasts();
1373 const BinaryOperator::Opcode Op = BinOp->getOpcode();
1374 const bool OpEqualEQorNE = ((Op == BO_EQ) || (Op == BO_NE));
1376 const auto *DeclRef1 = dyn_cast<DeclRefExpr>(LHS);
1377 const auto *DeclRef2 = dyn_cast<DeclRefExpr>(RHS);
1378 const auto *FloatLit1 = dyn_cast<FloatingLiteral>(LHS);
1379 const auto *FloatLit2 = dyn_cast<FloatingLiteral>(RHS);
1381 if (DeclRef1 && DeclRef2 &&
1382 DeclRef1->getType()->hasFloatingRepresentation() &&
1383 DeclRef2->getType()->hasFloatingRepresentation() &&
1384 (DeclRef1->getDecl() == DeclRef2->getDecl()) && OpEqualEQorNE) {
1388 if (FloatLit1 && FloatLit2 &&
1389 FloatLit1->getValue().bitwiseIsEqual(FloatLit2->getValue()) &&
1395 BinOp, Result.Context)) {
1396 const Expr *LhsConst =
nullptr, *RhsConst =
nullptr;
1397 BinaryOperatorKind MainOpcode{}, SideOpcode{};
1400 LhsConst, RhsConst, Result.Context))
1411 diag(BinOp->getOperatorLoc(),
"both sides of operator are equivalent");
1414 if (
const auto *CondOp =
1415 Result.Nodes.getNodeAs<ConditionalOperator>(
"cond")) {
1416 const Expr *TrueExpr = CondOp->getTrueExpr();
1417 const Expr *FalseExpr = CondOp->getFalseExpr();
1422 diag(CondOp->getColonLoc(),
1423 "'true' and 'false' expressions are equivalent");
1426 if (
const auto *Call = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(
"call")) {
1430 diag(Call->getOperatorLoc(),
1431 "both sides of overloaded operator are equivalent");
1434 if (
const auto *Op = Result.Nodes.getNodeAs<Expr>(
"nested-duplicates")) {
1435 const auto *Call = dyn_cast<CXXOperatorCallExpr>(Op);
1440 Call ?
"overloaded operator has equivalent nested operands"
1441 :
"operator has equivalent nested operands";
1443 const auto Diag = diag(Op->getExprLoc(),
Message);
1444 for (
const auto &KeyValue : Result.Nodes.getMap())
1445 if (StringRef(KeyValue.first).starts_with(
"duplicate"))
1446 Diag << KeyValue.second.getSourceRange();
1449 if (
const auto *NegateOperator =
1450 Result.Nodes.getNodeAs<UnaryOperator>(
"logical-bitwise-confusion")) {
1451 const SourceLocation OperatorLoc = NegateOperator->getOperatorLoc();
1455 "ineffective logical negation operator used; did you mean '~'?");
1456 const SourceLocation LogicalNotLocation = OperatorLoc.getLocWithOffset(1);
1458 if (!LogicalNotLocation.isMacroID())
1459 Diag << FixItHint::CreateReplacement(
1460 CharSourceRange::getCharRange(OperatorLoc, LogicalNotLocation),
"~");
1463 if (
const auto *BinaryAndExpr = Result.Nodes.getNodeAs<BinaryOperator>(
1464 "left-right-shift-confusion")) {
1465 const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>(
"shift-const");
1466 assert(ShiftingConst &&
"Expr* 'ShiftingConst' is nullptr!");
1467 std::optional<llvm::APSInt> ShiftingValue =
1468 ShiftingConst->getIntegerConstantExpr(*Result.Context);
1473 const auto *AndConst = Result.Nodes.getNodeAs<Expr>(
"and-const");
1474 assert(AndConst &&
"Expr* 'AndCont' is nullptr!");
1475 std::optional<llvm::APSInt> AndValue =
1476 AndConst->getIntegerConstantExpr(*Result.Context);
1483 if (AndValue->getActiveBits() > *ShiftingValue)
1486 const auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
1487 "ineffective bitwise and operation");
1495 checkArithmeticExpr(Result);
1503 checkBitwiseExpr(Result);
1511 checkRelationalExpr(Result);
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)