clang-tools 24.0.0git
SimplifyBooleanExprCheck.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 "clang/AST/Expr.h"
11#include "clang/AST/RecursiveASTVisitor.h"
12#include "clang/Basic/DiagnosticIDs.h"
13#include "clang/Lex/Lexer.h"
14#include "llvm/Support/SaveAndRestore.h"
15
16#include <optional>
17#include <string>
18#include <utility>
19
20using namespace clang::ast_matchers;
21
23
24static StringRef getText(const ASTContext &Context, SourceRange Range) {
25 return Lexer::getSourceText(CharSourceRange::getTokenRange(Range),
26 Context.getSourceManager(),
27 Context.getLangOpts());
28}
29
30template <typename T>
31static StringRef getText(const ASTContext &Context, T &Node) {
32 return getText(Context, Node.getSourceRange());
33}
34
35static constexpr char SimplifyOperatorDiagnostic[] =
36 "redundant boolean literal supplied to boolean operator";
37static constexpr char SimplifyConditionDiagnostic[] =
38 "redundant boolean literal in if statement condition";
39static constexpr char SimplifyConditionalReturnDiagnostic[] =
40 "redundant boolean literal in conditional return statement";
41
42static bool needsParensAfterUnaryNegation(const Expr *E) {
43 E = E->IgnoreImpCasts();
44 if (isa<BinaryOperator>(E) || isa<ConditionalOperator>(E))
45 return true;
46
47 if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(E))
48 return Op->getNumArgs() == 2 && Op->getOperator() != OO_Call &&
49 Op->getOperator() != OO_Subscript;
50
51 return false;
52}
53
54static std::pair<BinaryOperatorKind, BinaryOperatorKind> Opposites[] = {
55 {BO_LT, BO_GE}, {BO_GT, BO_LE}, {BO_EQ, BO_NE}};
56
57static StringRef negatedOperator(const BinaryOperator *BinOp) {
58 const BinaryOperatorKind Opcode = BinOp->getOpcode();
59 for (const auto NegatableOp : Opposites) {
60 if (Opcode == NegatableOp.first)
61 return BinaryOperator::getOpcodeStr(NegatableOp.second);
62 if (Opcode == NegatableOp.second)
63 return BinaryOperator::getOpcodeStr(NegatableOp.first);
64 }
65 return {};
66}
67
68static std::pair<OverloadedOperatorKind, StringRef> OperatorNames[] = {
69 {OO_EqualEqual, "=="}, {OO_ExclaimEqual, "!="}, {OO_Less, "<"},
70 {OO_GreaterEqual, ">="}, {OO_Greater, ">"}, {OO_LessEqual, "<="}};
71
72static StringRef getOperatorName(OverloadedOperatorKind OpKind) {
73 for (const auto Name : OperatorNames)
74 if (Name.first == OpKind)
75 return Name.second;
76
77 return {};
78}
79
80static std::pair<OverloadedOperatorKind, OverloadedOperatorKind>
81 OppositeOverloads[] = {{OO_EqualEqual, OO_ExclaimEqual},
82 {OO_Less, OO_GreaterEqual},
83 {OO_Greater, OO_LessEqual}};
84
85static StringRef negatedOperator(const CXXOperatorCallExpr *OpCall) {
86 const OverloadedOperatorKind Opcode = OpCall->getOperator();
87 for (const auto NegatableOp : OppositeOverloads) {
88 if (Opcode == NegatableOp.first)
89 return getOperatorName(NegatableOp.second);
90 if (Opcode == NegatableOp.second)
91 return getOperatorName(NegatableOp.first);
92 }
93 return {};
94}
95
96static std::string asBool(StringRef Text, bool NeedsStaticCast) {
97 if (NeedsStaticCast)
98 return ("static_cast<bool>(" + Text + ")").str();
99
100 return std::string(Text);
101}
102
103static bool needsNullPtrComparison(const Expr *E) {
104 if (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E))
105 return ImpCast->getCastKind() == CK_PointerToBoolean ||
106 ImpCast->getCastKind() == CK_MemberPointerToBoolean;
107
108 return false;
109}
110
111static bool needsZeroComparison(const Expr *E) {
112 if (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E))
113 return ImpCast->getCastKind() == CK_IntegralToBoolean;
114
115 return false;
116}
117
118static bool needsStaticCast(const Expr *E) {
119 if (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E);
120 ImpCast && ImpCast->getCastKind() == CK_UserDefinedConversion &&
121 ImpCast->getSubExpr()->getType()->isBooleanType()) {
122 if (const auto *MemCall =
123 dyn_cast<CXXMemberCallExpr>(ImpCast->getSubExpr())) {
124 if (const auto *MemDecl =
125 dyn_cast<CXXConversionDecl>(MemCall->getMethodDecl());
126 MemDecl && MemDecl->isExplicit())
127 return true;
128 }
129 }
130
131 E = E->IgnoreImpCasts();
132 return !E->getType()->isBooleanType();
133}
134
135static std::string compareExpressionToConstant(const ASTContext &Context,
136 const Expr *E, bool Negated,
137 const char *Constant) {
138 E = E->IgnoreImpCasts();
139 const std::string ExprText =
140 (isa<BinaryOperator>(E) ? ("(" + getText(Context, *E) + ")")
141 : getText(Context, *E))
142 .str();
143 return ExprText + " " + (Negated ? "!=" : "==") + " " + Constant;
144}
145
146static std::string compareExpressionToNullPtr(const ASTContext &Context,
147 const Expr *E, bool Negated) {
148 const char *NullPtr = Context.getLangOpts().CPlusPlus11 ? "nullptr" : "NULL";
149 return compareExpressionToConstant(Context, E, Negated, NullPtr);
150}
151
152static std::string compareExpressionToZero(const ASTContext &Context,
153 const Expr *E, bool Negated) {
154 return compareExpressionToConstant(Context, E, Negated, "0");
155}
156
157static std::string replacementExpression(const ASTContext &Context,
158 bool Negated, const Expr *E) {
159 E = E->IgnoreParenBaseCasts();
160 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
161 E = EC->getSubExpr();
162
163 const bool NeedsStaticCast =
164 Context.getLangOpts().CPlusPlus && needsStaticCast(E);
165 if (Negated) {
166 if (const auto *UnOp = dyn_cast<UnaryOperator>(E);
167 UnOp && UnOp->getOpcode() == UO_LNot) {
168 if (needsNullPtrComparison(UnOp->getSubExpr()))
169 return compareExpressionToNullPtr(Context, UnOp->getSubExpr(), true);
170
171 if (needsZeroComparison(UnOp->getSubExpr()))
172 return compareExpressionToZero(Context, UnOp->getSubExpr(), true);
173
174 return replacementExpression(Context, false, UnOp->getSubExpr());
175 }
176
178 return compareExpressionToNullPtr(Context, E, false);
179
180 if (needsZeroComparison(E))
181 return compareExpressionToZero(Context, E, false);
182
183 StringRef NegatedOperator;
184 const Expr *LHS = nullptr;
185 const Expr *RHS = nullptr;
186 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
187 NegatedOperator = negatedOperator(BinOp);
188 LHS = BinOp->getLHS();
189 RHS = BinOp->getRHS();
190 } else if (const auto *OpExpr = dyn_cast<CXXOperatorCallExpr>(E);
191 OpExpr && OpExpr->getNumArgs() == 2) {
192 NegatedOperator = negatedOperator(OpExpr);
193 LHS = OpExpr->getArg(0);
194 RHS = OpExpr->getArg(1);
195 }
196
197 if (!NegatedOperator.empty() && LHS && RHS)
198 return (asBool((getText(Context, *LHS) + " " + NegatedOperator + " " +
199 getText(Context, *RHS))
200 .str(),
201 NeedsStaticCast));
202
203 const StringRef Text = getText(Context, *E);
204 if (!NeedsStaticCast && needsParensAfterUnaryNegation(E))
205 return ("!(" + Text + ")").str();
206
208 return compareExpressionToNullPtr(Context, E, false);
209
210 if (needsZeroComparison(E))
211 return compareExpressionToZero(Context, E, false);
212
213 return ("!" + asBool(Text, NeedsStaticCast));
214 }
215
216 if (const auto *UnOp = dyn_cast<UnaryOperator>(E);
217 UnOp && UnOp->getOpcode() == UO_LNot) {
218 if (needsNullPtrComparison(UnOp->getSubExpr()))
219 return compareExpressionToNullPtr(Context, UnOp->getSubExpr(), false);
220
221 if (needsZeroComparison(UnOp->getSubExpr()))
222 return compareExpressionToZero(Context, UnOp->getSubExpr(), false);
223 }
224
226 return compareExpressionToNullPtr(Context, E, true);
227
228 if (needsZeroComparison(E))
229 return compareExpressionToZero(Context, E, true);
230
231 return asBool(getText(Context, *E), NeedsStaticCast);
232}
233
234static bool containsDiscardedTokens(const ASTContext &Context,
235 CharSourceRange CharRange) {
236 std::string ReplacementText =
237 Lexer::getSourceText(CharRange, Context.getSourceManager(),
238 Context.getLangOpts())
239 .str();
240 Lexer Lex(CharRange.getBegin(), Context.getLangOpts(), ReplacementText.data(),
241 ReplacementText.data(),
242 ReplacementText.data() + ReplacementText.size());
243 Lex.SetCommentRetentionState(true);
244
245 Token Tok;
246 while (!Lex.LexFromRawLexer(Tok))
247 if (Tok.is(tok::TokenKind::comment) || Tok.is(tok::TokenKind::hash))
248 return true;
249
250 return false;
251}
252
253class SimplifyBooleanExprCheck::Visitor : public RecursiveASTVisitor<Visitor> {
254 using Base = RecursiveASTVisitor<Visitor>;
255
256public:
257 Visitor(SimplifyBooleanExprCheck *Check, ASTContext &Context)
258 : Check(Check), Context(Context) {}
259
260 bool traverse() { return TraverseAST(Context); }
261
262 static bool shouldIgnore(Stmt *S) {
263 switch (S->getStmtClass()) {
264 case Stmt::ImplicitCastExprClass:
265 case Stmt::MaterializeTemporaryExprClass:
266 case Stmt::CXXBindTemporaryExprClass:
267 return true;
268 default:
269 return false;
270 }
271 }
272
273 bool dataTraverseStmtPre(Stmt *S) {
274 if (!S)
275 return true;
276 if (Check->canBeBypassed(S))
277 return false;
278 if (!shouldIgnore(S))
279 StmtStack.push_back(S);
280 return true;
281 }
282
283 bool dataTraverseStmtPost(Stmt *S) {
284 if (S && !shouldIgnore(S)) {
285 assert(StmtStack.back() == S);
286 StmtStack.pop_back();
287 }
288 return true;
289 }
290
291 bool VisitBinaryOperator(const BinaryOperator *Op) const {
292 Check->reportBinOp(Context, Op);
293 return true;
294 }
295
296 // Extracts a bool if an expression is (true|false|!true|!false);
297 static std::optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
298 if (const auto *Bool = dyn_cast<CXXBoolLiteralExpr>(E)) {
299 if (FilterMacro && Bool->getBeginLoc().isMacroID())
300 return std::nullopt;
301 return Bool->getValue();
302 }
303 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E)) {
304 if (FilterMacro && UnaryOp->getBeginLoc().isMacroID())
305 return std::nullopt;
306 if (UnaryOp->getOpcode() == UO_LNot)
307 if (std::optional<bool> Res = getAsBoolLiteral(
308 UnaryOp->getSubExpr()->IgnoreImplicit(), FilterMacro))
309 return !*Res;
310 }
311 return std::nullopt;
312 }
313
314 template <typename Node> struct NodeAndBool {
315 const Node *Item = nullptr;
316 bool Bool = false;
317
318 operator bool() const { return Item != nullptr; }
319 };
320
323
324 /// Detect's return (true|false|!true|!false);
325 static ExprAndBool parseReturnLiteralBool(const Stmt *S) {
326 const auto *RS = dyn_cast<ReturnStmt>(S);
327 if (!RS || !RS->getRetValue())
328 return {};
329 if (std::optional<bool> Ret =
330 getAsBoolLiteral(RS->getRetValue()->IgnoreImplicit(), false)) {
331 return {RS->getRetValue(), *Ret};
332 }
333 return {};
334 }
335
336 /// If \p S is not a \c CompoundStmt, applies F on \p S, otherwise if there is
337 /// only 1 statement in the \c CompoundStmt, applies F on that single
338 /// statement.
339 template <typename Functor>
340 static auto checkSingleStatement(Stmt *S, Functor F) -> decltype(F(S)) {
341 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
342 if (CS->size() == 1)
343 return F(CS->body_front());
344 return {};
345 }
346 return F(S);
347 }
348
349 Stmt *parent() const {
350 return StmtStack.size() < 2 ? nullptr : StmtStack[StmtStack.size() - 2];
351 }
352
353 bool VisitIfStmt(IfStmt *If) {
354 // Skip any if's that have a condition var or an init statement, or are
355 // "if consteval" statements.
356 if (If->hasInitStorage() || If->hasVarStorage() || If->isConsteval())
357 return true;
358 /*
359 * if (true) ThenStmt(); -> ThenStmt();
360 * if (false) ThenStmt(); -> <Empty>;
361 * if (false) ThenStmt(); else ElseStmt() -> ElseStmt();
362 */
363 const Expr *Cond = If->getCond()->IgnoreImplicit();
364 if (std::optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
365 if (*Bool)
366 Check->replaceWithThenStatement(Context, If, Cond);
367 else
368 Check->replaceWithElseStatement(Context, If, Cond);
369 }
370
371 if (If->getElse()) {
372 /*
373 * if (Cond) return true; else return false; -> return Cond;
374 * if (Cond) return false; else return true; -> return !Cond;
375 */
376 if (const ExprAndBool ThenReturnBool =
378 const ExprAndBool ElseReturnBool =
380 if (ElseReturnBool && ThenReturnBool.Bool != ElseReturnBool.Bool) {
381 if (Check->ChainedConditionalReturn ||
382 !isa_and_nonnull<IfStmt>(parent())) {
383 Check->replaceWithReturnCondition(Context, If, ThenReturnBool.Item,
384 ElseReturnBool.Bool);
385 }
386 }
387 } else {
388 /*
389 * if (Cond) A = true; else A = false; -> A = Cond;
390 * if (Cond) A = false; else A = true; -> A = !Cond;
391 */
392 Expr *Var = nullptr;
393 SourceLocation Loc;
394 const auto VarBoolAssignmentMatcher =
395 [&Var, &Loc](const Stmt *S) -> DeclAndBool {
396 const auto *BO = dyn_cast<BinaryOperator>(S);
397 if (!BO || BO->getOpcode() != BO_Assign)
398 return {};
399 std::optional<bool> RightasBool =
400 getAsBoolLiteral(BO->getRHS()->IgnoreImplicit(), false);
401 if (!RightasBool)
402 return {};
403 Expr *IgnImp = BO->getLHS()->IgnoreImplicit();
404 if (!Var) {
405 // We only need to track these for the Then branch.
406 Loc = BO->getRHS()->getBeginLoc();
407 Var = IgnImp;
408 }
409 if (auto *DRE = dyn_cast<DeclRefExpr>(IgnImp))
410 return {DRE->getDecl(), *RightasBool};
411 if (const auto *ME = dyn_cast<MemberExpr>(IgnImp))
412 return {ME->getMemberDecl(), *RightasBool};
413 return {};
414 };
415 if (const DeclAndBool ThenAssignment =
416 checkSingleStatement(If->getThen(), VarBoolAssignmentMatcher)) {
417 const DeclAndBool ElseAssignment =
418 checkSingleStatement(If->getElse(), VarBoolAssignmentMatcher);
419 if (ElseAssignment.Item == ThenAssignment.Item &&
420 ElseAssignment.Bool != ThenAssignment.Bool &&
421 (Check->ChainedConditionalAssignment ||
422 !isa_and_nonnull<IfStmt>(parent()))) {
423 Check->replaceWithAssignment(Context, If, Var, Loc,
424 ElseAssignment.Bool);
425 }
426 }
427 }
428 }
429 return true;
430 }
431
432 bool VisitConditionalOperator(ConditionalOperator *Cond) {
433 /*
434 * Condition ? true : false; -> Condition
435 * Condition ? false : true; -> !Condition;
436 */
437 if (std::optional<bool> Then =
438 getAsBoolLiteral(Cond->getTrueExpr()->IgnoreImplicit(), false)) {
439 if (std::optional<bool> Else =
440 getAsBoolLiteral(Cond->getFalseExpr()->IgnoreImplicit(), false)) {
441 if (*Then != *Else)
442 Check->replaceWithCondition(Context, Cond, *Else);
443 }
444 }
445 return true;
446 }
447
448 bool VisitCompoundStmt(CompoundStmt *CS) {
449 if (CS->size() < 2)
450 return true;
451 bool CurIf = false, PrevIf = false;
452 for (auto First = CS->body_begin(), Second = std::next(First),
453 End = CS->body_end();
454 Second != End; ++Second, ++First) {
455 PrevIf = CurIf;
456 CurIf = isa<IfStmt>(*First);
457 const ExprAndBool TrailingReturnBool = parseReturnLiteralBool(*Second);
458 if (!TrailingReturnBool)
459 continue;
460
461 if (CurIf) {
462 /*
463 * if (Cond) return true; return false; -> return Cond;
464 * if (Cond) return false; return true; -> return !Cond;
465 */
466 auto *If = cast<IfStmt>(*First);
467 if (!If->hasInitStorage() && !If->hasVarStorage() &&
468 !If->isConsteval()) {
469 const ExprAndBool ThenReturnBool =
471 if (ThenReturnBool &&
472 ThenReturnBool.Bool != TrailingReturnBool.Bool) {
473 if ((Check->ChainedConditionalReturn || !PrevIf) &&
474 If->getElse() == nullptr) {
475 Check->replaceCompoundReturnWithCondition(
476 Context, cast<ReturnStmt>(*Second), TrailingReturnBool.Bool,
477 If, ThenReturnBool.Item);
478 }
479 }
480 }
481 } else if (isa<LabelStmt, CaseStmt, DefaultStmt>(*First)) {
482 /*
483 * (case X|label_X|default): if (Cond) return BoolLiteral;
484 * return !BoolLiteral
485 */
486 Stmt *SubStmt =
487 isa<LabelStmt>(*First) ? cast<LabelStmt>(*First)->getSubStmt()
488 : isa<CaseStmt>(*First) ? cast<CaseStmt>(*First)->getSubStmt()
489 : cast<DefaultStmt>(*First)->getSubStmt();
490 auto *SubIf = dyn_cast<IfStmt>(SubStmt);
491 if (SubIf && !SubIf->getElse() && !SubIf->hasInitStorage() &&
492 !SubIf->hasVarStorage() && !SubIf->isConsteval()) {
493 const ExprAndBool ThenReturnBool =
495 if (ThenReturnBool &&
496 ThenReturnBool.Bool != TrailingReturnBool.Bool) {
497 Check->replaceCompoundReturnWithCondition(
498 Context, cast<ReturnStmt>(*Second), TrailingReturnBool.Bool,
499 SubIf, ThenReturnBool.Item);
500 }
501 }
502 }
503 }
504 return true;
505 }
506
507 bool isExpectedUnaryLNot(const Expr *E) {
508 return !Check->canBeBypassed(E) && isa<UnaryOperator>(E) &&
509 cast<UnaryOperator>(E)->getOpcode() == UO_LNot;
510 }
511
512 bool isExpectedBinaryOp(const Expr *E) {
513 const auto *BinaryOp = dyn_cast<BinaryOperator>(E);
514 return !Check->canBeBypassed(E) && BinaryOp && BinaryOp->isLogicalOp() &&
515 BinaryOp->getType()->isBooleanType();
516 }
517
518 template <typename Functor>
519 static bool checkEitherSide(const BinaryOperator *BO, Functor Func) {
520 return Func(BO->getLHS()) || Func(BO->getRHS());
521 }
522
523 bool nestedDemorgan(const Expr *E, unsigned NestingLevel) {
524 const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreUnlessSpelledInSource());
525 if (!BO)
526 return false;
527 if (!BO->getType()->isBooleanType())
528 return false;
529 switch (BO->getOpcode()) {
530 case BO_LT:
531 case BO_GT:
532 case BO_LE:
533 case BO_GE:
534 case BO_EQ:
535 case BO_NE:
536 return true;
537 case BO_LAnd:
538 case BO_LOr:
539 return checkEitherSide(
540 BO,
541 [this](const Expr *E) { return isExpectedUnaryLNot(E); }) ||
542 (NestingLevel &&
543 checkEitherSide(BO, [this, NestingLevel](const Expr *E) {
544 return nestedDemorgan(E, NestingLevel - 1);
545 }));
546 default:
547 return false;
548 }
549 }
550
551 bool TraverseUnaryOperator(UnaryOperator *Op) {
552 if (!Check->SimplifyDeMorgan || Op->getOpcode() != UO_LNot)
553 return Base::TraverseUnaryOperator(Op);
554 const Expr *SubImp = Op->getSubExpr()->IgnoreImplicit();
555 const auto *Parens = dyn_cast<ParenExpr>(SubImp);
556 const Expr *SubExpr =
557 Parens ? Parens->getSubExpr()->IgnoreImplicit() : SubImp;
558 if (!isExpectedBinaryOp(SubExpr))
559 return Base::TraverseUnaryOperator(Op);
560 const auto *BinaryOp = cast<BinaryOperator>(SubExpr);
561 if ((Check->SimplifyDeMorganRelaxed ||
563 BinaryOp,
564 [this](const Expr *E) { return isExpectedUnaryLNot(E); }) ||
566 BinaryOp,
567 [this](const Expr *E) { return nestedDemorgan(E, 1); })) &&
568 Check->reportDeMorgan(Context, Op, BinaryOp, !IsProcessing, parent(),
569 Parens) &&
570 !Check->areDiagsSelfContained()) {
571 const llvm::SaveAndRestore RAII(IsProcessing, true);
572 return Base::TraverseUnaryOperator(Op);
573 }
574
575 return Base::TraverseUnaryOperator(Op);
576 }
577
578private:
579 bool IsProcessing = false;
581 SmallVector<Stmt *, 32> StmtStack;
582 ASTContext &Context;
583};
584
586 ClangTidyContext *Context)
587 : ClangTidyCheck(Name, Context),
588 IgnoreMacros(Options.get("IgnoreMacros", false)),
589 ChainedConditionalReturn(Options.get("ChainedConditionalReturn", false)),
590 ChainedConditionalAssignment(
591 Options.get("ChainedConditionalAssignment", false)),
592 SimplifyDeMorgan(Options.get("SimplifyDeMorgan", true)),
593 SimplifyDeMorganRelaxed(Options.get("SimplifyDeMorganRelaxed", false)) {
594 if (SimplifyDeMorganRelaxed && !SimplifyDeMorgan)
595 configurationDiag("%0: 'SimplifyDeMorganRelaxed' cannot be enabled "
596 "without 'SimplifyDeMorgan' enabled")
597 << Name;
598}
599
600static bool containsBoolLiteral(const Expr *E) {
601 if (!E)
602 return false;
603 E = E->IgnoreParenImpCasts();
604 if (isa<CXXBoolLiteralExpr>(E))
605 return true;
606 if (const auto *BinOp = dyn_cast<BinaryOperator>(E))
607 return containsBoolLiteral(BinOp->getLHS()) ||
608 containsBoolLiteral(BinOp->getRHS());
609 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
610 return containsBoolLiteral(UnaryOp->getSubExpr());
611 return false;
612}
613
614void SimplifyBooleanExprCheck::reportBinOp(const ASTContext &Context,
615 const BinaryOperator *Op) {
616 const auto *LHS = Op->getLHS()->IgnoreParenImpCasts();
617 const auto *RHS = Op->getRHS()->IgnoreParenImpCasts();
618
619 const CXXBoolLiteralExpr *Bool = nullptr;
620 const Expr *Other = nullptr;
621 if ((Bool = dyn_cast<CXXBoolLiteralExpr>(LHS)) != nullptr)
622 Other = RHS;
623 else if ((Bool = dyn_cast<CXXBoolLiteralExpr>(RHS)) != nullptr)
624 Other = LHS;
625 else
626 return;
627
628 if (Bool->getBeginLoc().isMacroID())
629 return;
630
631 // FIXME: why do we need this?
632 if (!isa<CXXBoolLiteralExpr>(Other) && containsBoolLiteral(Other))
633 return;
634
635 const bool BoolValue = Bool->getValue();
636
637 const auto ReplaceWithExpression = [this, &Context, LHS, RHS,
638 Bool](const Expr *ReplaceWith,
639 bool Negated) {
640 const std::string Replacement =
641 replacementExpression(Context, Negated, ReplaceWith);
642 const SourceRange Range(LHS->getBeginLoc(), RHS->getEndLoc());
643 issueDiag(Context, Bool->getBeginLoc(), SimplifyOperatorDiagnostic, Range,
644 Replacement);
645 };
646
647 switch (Op->getOpcode()) {
648 case BO_LAnd:
649 if (BoolValue)
650 // expr && true -> expr
651 ReplaceWithExpression(Other, /*Negated=*/false);
652 else
653 // expr && false -> false
654 ReplaceWithExpression(Bool, /*Negated=*/false);
655 break;
656 case BO_LOr:
657 if (BoolValue)
658 // expr || true -> true
659 ReplaceWithExpression(Bool, /*Negated=*/false);
660 else
661 // expr || false -> expr
662 ReplaceWithExpression(Other, /*Negated=*/false);
663 break;
664 case BO_EQ:
665 // expr == true -> expr, expr == false -> !expr
666 ReplaceWithExpression(Other, /*Negated=*/!BoolValue);
667 break;
668 case BO_NE:
669 // expr != true -> !expr, expr != false -> expr
670 ReplaceWithExpression(Other, /*Negated=*/BoolValue);
671 break;
672 default:
673 break;
674 }
675}
676
678 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
679 Options.store(Opts, "ChainedConditionalReturn", ChainedConditionalReturn);
680 Options.store(Opts, "ChainedConditionalAssignment",
681 ChainedConditionalAssignment);
682 Options.store(Opts, "SimplifyDeMorgan", SimplifyDeMorgan);
683 Options.store(Opts, "SimplifyDeMorganRelaxed", SimplifyDeMorganRelaxed);
684}
685
687 Finder->addMatcher(translationUnitDecl(), this);
688}
689
690void SimplifyBooleanExprCheck::check(const MatchFinder::MatchResult &Result) {
691 Visitor(this, *Result.Context).traverse();
692}
693
694bool SimplifyBooleanExprCheck::canBeBypassed(const Stmt *S) const {
695 return IgnoreMacros && S->getBeginLoc().isMacroID();
696}
697
698/// @brief return true when replacement created.
699bool SimplifyBooleanExprCheck::issueDiag(const ASTContext &Context,
700 SourceLocation Loc,
701 StringRef Description,
702 SourceRange ReplacementRange,
703 StringRef Replacement) {
704 const CharSourceRange CharRange =
705 Lexer::makeFileCharRange(CharSourceRange::getTokenRange(ReplacementRange),
706 Context.getSourceManager(), getLangOpts());
707
708 const DiagnosticBuilder Diag = diag(Loc, Description);
709 const bool HasReplacement = !containsDiscardedTokens(Context, CharRange);
710 if (HasReplacement)
711 Diag << FixItHint::CreateReplacement(CharRange, Replacement);
712 return HasReplacement;
713}
714
715void SimplifyBooleanExprCheck::replaceWithThenStatement(
716 const ASTContext &Context, const IfStmt *IfStatement,
717 const Expr *BoolLiteral) {
718 issueDiag(Context, BoolLiteral->getBeginLoc(), SimplifyConditionDiagnostic,
719 IfStatement->getSourceRange(),
720 getText(Context, *IfStatement->getThen()));
721}
722
723void SimplifyBooleanExprCheck::replaceWithElseStatement(
724 const ASTContext &Context, const IfStmt *IfStatement,
725 const Expr *BoolLiteral) {
726 const Stmt *ElseStatement = IfStatement->getElse();
727 issueDiag(Context, BoolLiteral->getBeginLoc(), SimplifyConditionDiagnostic,
728 IfStatement->getSourceRange(),
729 ElseStatement ? getText(Context, *ElseStatement) : "");
730}
731
732void SimplifyBooleanExprCheck::replaceWithCondition(
733 const ASTContext &Context, const ConditionalOperator *Ternary,
734 bool Negated) {
735 const std::string Replacement =
736 replacementExpression(Context, Negated, Ternary->getCond());
737 issueDiag(Context, Ternary->getTrueExpr()->getBeginLoc(),
738 "redundant boolean literal in ternary expression result",
739 Ternary->getSourceRange(), Replacement);
740}
741
742void SimplifyBooleanExprCheck::replaceWithReturnCondition(
743 const ASTContext &Context, const IfStmt *If, const Expr *BoolLiteral,
744 bool Negated) {
745 const StringRef Terminator = isa<CompoundStmt>(If->getElse()) ? ";" : "";
746 const std::string Condition =
747 replacementExpression(Context, Negated, If->getCond());
748 const std::string Replacement = ("return " + Condition + Terminator).str();
749 const SourceLocation Start = BoolLiteral->getBeginLoc();
750
751 const bool HasReplacement =
752 issueDiag(Context, Start, SimplifyConditionalReturnDiagnostic,
753 If->getSourceRange(), Replacement);
754
755 if (!HasReplacement) {
756 const SourceRange ConditionRange = If->getCond()->getSourceRange();
757 if (ConditionRange.isValid())
758 diag(ConditionRange.getBegin(), "conditions that can be simplified",
759 DiagnosticIDs::Note)
760 << ConditionRange;
761 }
762}
763
764void SimplifyBooleanExprCheck::replaceCompoundReturnWithCondition(
765 const ASTContext &Context, const ReturnStmt *Ret, bool Negated,
766 const IfStmt *If, const Expr *ThenReturn) {
767 const std::string Replacement =
768 "return " + replacementExpression(Context, Negated, If->getCond());
769
770 const bool HasReplacement = issueDiag(
771 Context, ThenReturn->getBeginLoc(), SimplifyConditionalReturnDiagnostic,
772 SourceRange(If->getBeginLoc(), Ret->getEndLoc()), Replacement);
773
774 if (!HasReplacement) {
775 const SourceRange ConditionRange = If->getCond()->getSourceRange();
776 if (ConditionRange.isValid())
777 diag(ConditionRange.getBegin(), "conditions that can be simplified",
778 DiagnosticIDs::Note)
779 << ConditionRange;
780 const SourceRange ReturnRange = Ret->getSourceRange();
781 if (ReturnRange.isValid())
782 diag(ReturnRange.getBegin(), "return statement that can be simplified",
783 DiagnosticIDs::Note)
784 << ReturnRange;
785 }
786}
787
788void SimplifyBooleanExprCheck::replaceWithAssignment(const ASTContext &Context,
789 const IfStmt *IfAssign,
790 const Expr *Var,
791 SourceLocation Loc,
792 bool Negated) {
793 const SourceRange Range = IfAssign->getSourceRange();
794 const StringRef VariableName = getText(Context, *Var);
795 const StringRef Terminator =
796 isa<CompoundStmt>(IfAssign->getElse()) ? ";" : "";
797 const std::string Condition =
798 replacementExpression(Context, Negated, IfAssign->getCond());
799 const std::string Replacement =
800 (VariableName + " = " + Condition + Terminator).str();
801 issueDiag(Context, Loc, "redundant boolean literal in conditional assignment",
802 Range, Replacement);
803}
804
805/// Swaps a \c BinaryOperator opcode from `&&` to `||` or vice-versa.
806static bool flipDemorganOperator(SmallVectorImpl<FixItHint> &Output,
807 const BinaryOperator *BO) {
808 assert(BO->isLogicalOp());
809 if (BO->getOperatorLoc().isMacroID())
810 return true;
811 Output.push_back(FixItHint::CreateReplacement(
812 BO->getOperatorLoc(), BO->getOpcode() == BO_LAnd ? "||" : "&&"));
813 return false;
814}
815
816static BinaryOperatorKind getDemorganFlippedOperator(BinaryOperatorKind BO) {
817 assert(BinaryOperator::isLogicalOp(BO));
818 return BO == BO_LAnd ? BO_LOr : BO_LAnd;
819}
820
821static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
822 const ASTContext &Ctx, const Expr *E,
823 std::optional<BinaryOperatorKind> OuterBO);
824
825/// Inverts \p BinOp, Removing \p Parens if they exist and are safe to remove.
826/// returns \c true if there is any issue building the Fixes, \c false
827/// otherwise.
828static bool
829flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
830 const ASTContext &Ctx, const BinaryOperator *BinOp,
831 std::optional<BinaryOperatorKind> OuterBO,
832 const ParenExpr *Parens = nullptr) {
833 switch (BinOp->getOpcode()) {
834 case BO_LAnd:
835 case BO_LOr: {
836 // if we have 'a && b' or 'a || b', use demorgan to flip it to '!a || !b'
837 // or '!a && !b'.
838 if (flipDemorganOperator(Fixes, BinOp))
839 return true;
840 auto NewOp = getDemorganFlippedOperator(BinOp->getOpcode());
841 if (OuterBO) {
842 // The inner parens are technically needed in a fix for
843 // `!(!A1 && !(A2 || A3)) -> (A1 || (A2 && A3))`,
844 // however this would trip the LogicalOpParentheses warning.
845 // FIXME: Make this user configurable or detect if that warning is
846 // enabled.
847 constexpr bool LogicalOpParentheses = true;
848 if (((*OuterBO == NewOp) || (!LogicalOpParentheses &&
849 (*OuterBO == BO_LOr && NewOp == BO_LAnd))) &&
850 Parens && !Parens->getLParen().isMacroID() &&
851 !Parens->getRParen().isMacroID()) {
852 Fixes.push_back(FixItHint::CreateRemoval(Parens->getLParen()));
853 Fixes.push_back(FixItHint::CreateRemoval(Parens->getRParen()));
854 }
855
856 if (*OuterBO == BO_LAnd && NewOp == BO_LOr && !Parens) {
857 Fixes.push_back(FixItHint::CreateInsertion(BinOp->getBeginLoc(), "("));
858 Fixes.push_back(FixItHint::CreateInsertion(
859 Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0,
860 Ctx.getSourceManager(),
861 Ctx.getLangOpts()),
862 ")"));
863 }
864 }
865 if (flipDemorganSide(Fixes, Ctx, BinOp->getLHS(), NewOp) ||
866 flipDemorganSide(Fixes, Ctx, BinOp->getRHS(), NewOp))
867 return true;
868 return false;
869 };
870 case BO_LT:
871 case BO_GT:
872 case BO_LE:
873 case BO_GE:
874 case BO_EQ:
875 case BO_NE:
876 // For comparison operators, just negate the comparison.
877 if (BinOp->getOperatorLoc().isMacroID())
878 return true;
879 Fixes.push_back(FixItHint::CreateReplacement(
880 BinOp->getOperatorLoc(),
881 BinaryOperator::getOpcodeStr(
882 BinaryOperator::negateComparisonOp(BinOp->getOpcode()))));
883 return false;
884 default:
885 // for any other binary operator, just use logical not and wrap in
886 // parens.
887 if (Parens) {
888 if (Parens->getBeginLoc().isMacroID())
889 return true;
890 Fixes.push_back(FixItHint::CreateInsertion(Parens->getBeginLoc(), "!"));
891 } else {
892 if (BinOp->getBeginLoc().isMacroID() || BinOp->getEndLoc().isMacroID())
893 return true;
894 Fixes.append({FixItHint::CreateInsertion(BinOp->getBeginLoc(), "!("),
895 FixItHint::CreateInsertion(
896 Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0,
897 Ctx.getSourceManager(),
898 Ctx.getLangOpts()),
899 ")")});
900 }
901 break;
902 }
903 return false;
904}
905
906static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
907 const ASTContext &Ctx, const Expr *E,
908 std::optional<BinaryOperatorKind> OuterBO) {
909 if (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->getOpcode() == UO_LNot) {
910 // if we have a not operator, '!a', just remove the '!'.
911 if (cast<UnaryOperator>(E)->getOperatorLoc().isMacroID())
912 return true;
913 Fixes.push_back(
914 FixItHint::CreateRemoval(cast<UnaryOperator>(E)->getOperatorLoc()));
915 return false;
916 }
917 if (const auto *BinOp = dyn_cast<BinaryOperator>(E))
918 return flipDemorganBinaryOperator(Fixes, Ctx, BinOp, OuterBO);
919 if (const auto *Paren = dyn_cast<ParenExpr>(E)) {
920 if (const auto *BinOp = dyn_cast<BinaryOperator>(Paren->getSubExpr()))
921 return flipDemorganBinaryOperator(Fixes, Ctx, BinOp, OuterBO, Paren);
922 }
923 // Fallback case just insert a logical not operator.
924 if (E->getBeginLoc().isMacroID())
925 return true;
926 Fixes.push_back(FixItHint::CreateInsertion(E->getBeginLoc(), "!"));
927 return false;
928}
929
930static bool shouldRemoveParens(const Stmt *Parent,
931 BinaryOperatorKind NewOuterBinary,
932 const ParenExpr *Parens) {
933 if (!Parens)
934 return false;
935 if (!Parent)
936 return true;
937 switch (Parent->getStmtClass()) {
938 case Stmt::BinaryOperatorClass: {
939 const auto *BO = cast<BinaryOperator>(Parent);
940 if (BO->isAssignmentOp())
941 return true;
942 if (BO->isCommaOp())
943 return true;
944 if (BO->getOpcode() == NewOuterBinary)
945 return true;
946 return false;
947 }
948 case Stmt::UnaryOperatorClass:
949 case Stmt::CXXRewrittenBinaryOperatorClass:
950 return false;
951 default:
952 return true;
953 }
954}
955
956bool SimplifyBooleanExprCheck::reportDeMorgan(const ASTContext &Context,
957 const UnaryOperator *Outer,
958 const BinaryOperator *Inner,
959 bool TryOfferFix,
960 const Stmt *Parent,
961 const ParenExpr *Parens) {
962 assert(Outer);
963 assert(Inner);
964 assert(Inner->isLogicalOp());
965
966 const auto Diag =
967 diag(Outer->getBeginLoc(),
968 "boolean expression can be simplified by DeMorgan's theorem");
969 Diag << Outer->getSourceRange();
970 // If we have already fixed this with a previous fix, don't attempt any fixes
971 if (!TryOfferFix)
972 return false;
973 if (Outer->getOperatorLoc().isMacroID())
974 return false;
976 auto NewOpcode = getDemorganFlippedOperator(Inner->getOpcode());
977 if (shouldRemoveParens(Parent, NewOpcode, Parens)) {
978 Fixes.push_back(FixItHint::CreateRemoval(
979 SourceRange(Outer->getOperatorLoc(), Parens->getLParen())));
980 Fixes.push_back(FixItHint::CreateRemoval(Parens->getRParen()));
981 } else {
982 Fixes.push_back(FixItHint::CreateRemoval(Outer->getOperatorLoc()));
983 }
984 if (flipDemorganOperator(Fixes, Inner))
985 return false;
986 if (flipDemorganSide(Fixes, Context, Inner->getLHS(), NewOpcode) ||
987 flipDemorganSide(Fixes, Context, Inner->getRHS(), NewOpcode))
988 return false;
989 Diag << Fixes;
990 return true;
991}
992} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Visitor(SimplifyBooleanExprCheck *Check, ASTContext &Context)
static std::optional< bool > getAsBoolLiteral(const Expr *E, bool FilterMacro)
static bool checkEitherSide(const BinaryOperator *BO, Functor Func)
static auto checkSingleStatement(Stmt *S, Functor F) -> decltype(F(S))
If S is not a CompoundStmt, applies F on S, otherwise if there is only 1 statement in the CompoundStm...
static ExprAndBool parseReturnLiteralBool(const Stmt *S)
Detect's return (true|false|!true|!false);.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
SimplifyBooleanExprCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static std::string replacementExpression(const ASTContext &Context, bool Negated, const Expr *E)
static bool needsZeroComparison(const Expr *E)
static bool containsBoolLiteral(const Expr *E)
static StringRef negatedOperator(const BinaryOperator *BinOp)
static bool shouldRemoveParens(const Stmt *Parent, BinaryOperatorKind NewOuterBinary, const ParenExpr *Parens)
static std::string compareExpressionToConstant(const ASTContext &Context, const Expr *E, bool Negated, const char *Constant)
static std::pair< BinaryOperatorKind, BinaryOperatorKind > Opposites[]
static bool needsParensAfterUnaryNegation(const Expr *E)
static bool containsDiscardedTokens(const ASTContext &Context, CharSourceRange CharRange)
static StringRef getOperatorName(OverloadedOperatorKind OpKind)
static constexpr char SimplifyConditionDiagnostic[]
static bool needsNullPtrComparison(const Expr *E)
static constexpr char SimplifyConditionalReturnDiagnostic[]
static bool flipDemorganOperator(SmallVectorImpl< FixItHint > &Output, const BinaryOperator *BO)
Swaps a BinaryOperator opcode from && to || or vice-versa.
static bool flipDemorganBinaryOperator(SmallVectorImpl< FixItHint > &Fixes, const ASTContext &Ctx, const BinaryOperator *BinOp, std::optional< BinaryOperatorKind > OuterBO, const ParenExpr *Parens=nullptr)
Inverts BinOp, Removing Parens if they exist and are safe to remove.
static constexpr char SimplifyOperatorDiagnostic[]
static bool flipDemorganSide(SmallVectorImpl< FixItHint > &Fixes, const ASTContext &Ctx, const Expr *E, std::optional< BinaryOperatorKind > OuterBO)
static StringRef getText(const ASTContext &Context, SourceRange Range)
static BinaryOperatorKind getDemorganFlippedOperator(BinaryOperatorKind BO)
static std::string asBool(StringRef Text, bool NeedsStaticCast)
static std::pair< OverloadedOperatorKind, OverloadedOperatorKind > OppositeOverloads[]
static std::string compareExpressionToZero(const ASTContext &Context, const Expr *E, bool Negated)
static bool isMacroID(SourceRange R)
static std::string compareExpressionToNullPtr(const ASTContext &Context, const Expr *E, bool Negated)
static std::pair< OverloadedOperatorKind, StringRef > OperatorNames[]
static bool needsStaticCast(const Expr *E)
llvm::StringMap< ClangTidyValue > OptionMap