clang-tools 22.0.0git
AssertSideEffectCheck.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"
12#include "clang/AST/ASTContext.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/Lexer.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringRef.h"
18#include <string>
19
20using namespace clang::ast_matchers;
21
22namespace clang::tidy::bugprone {
23
24namespace {
25
26AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
27 clang::ast_matchers::internal::Matcher<NamedDecl>,
28 IgnoredFunctionsMatcher) {
29 const Expr *E = &Node;
30
31 if (const auto *Op = dyn_cast<UnaryOperator>(E)) {
32 const UnaryOperator::Opcode OC = Op->getOpcode();
33 return OC == UO_PostInc || OC == UO_PostDec || OC == UO_PreInc ||
34 OC == UO_PreDec;
35 }
36
37 if (const auto *Op = dyn_cast<BinaryOperator>(E))
38 return Op->isAssignmentOp();
39
40 if (const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E)) {
41 if (const auto *MethodDecl =
42 dyn_cast_or_null<CXXMethodDecl>(OpCallExpr->getDirectCallee()))
43 if (MethodDecl->isConst())
44 return false;
45
46 const OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
47 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
48 OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
49 OpKind == OO_SlashEqual || OpKind == OO_AmpEqual ||
50 OpKind == OO_PipeEqual || OpKind == OO_CaretEqual ||
51 OpKind == OO_LessLessEqual || OpKind == OO_GreaterGreaterEqual ||
52 OpKind == OO_LessLess || OpKind == OO_GreaterGreater ||
53 OpKind == OO_PlusPlus || OpKind == OO_MinusMinus ||
54 OpKind == OO_PercentEqual || OpKind == OO_New ||
55 OpKind == OO_Delete || OpKind == OO_Array_New ||
56 OpKind == OO_Array_Delete;
57 }
58
59 if (const auto *CExpr = dyn_cast<CallExpr>(E)) {
60 if (!CheckFunctionCalls)
61 return false;
62 if (const auto *FuncDecl = CExpr->getDirectCallee()) {
63 if (FuncDecl->getDeclName().isIdentifier() &&
64 IgnoredFunctionsMatcher.matches(*FuncDecl, Finder,
65 Builder)) // exceptions come here
66 return false;
67 for (size_t I = 0; I < FuncDecl->getNumParams(); I++) {
68 const ParmVarDecl *P = FuncDecl->getParamDecl(I);
69 const Expr *ArgExpr =
70 I < CExpr->getNumArgs() ? CExpr->getArg(I) : nullptr;
71 const QualType PT = P->getType().getCanonicalType();
72 if (ArgExpr && !ArgExpr->isXValue() && PT->isReferenceType() &&
73 !PT.getNonReferenceType().isConstQualified())
74 return true;
75 }
76 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
77 return !MethodDecl->isConst();
78 }
79 return true;
80 }
81
82 return isa<CXXNewExpr>(E) || isa<CXXDeleteExpr>(E) || isa<CXXThrowExpr>(E);
83}
84
85} // namespace
86
88 ClangTidyContext *Context)
89 : ClangTidyCheck(Name, Context),
90 CheckFunctionCalls(Options.get("CheckFunctionCalls", false)),
91 RawAssertList(Options.get("AssertMacros", "assert,NSAssert,NSCAssert")),
92 IgnoredFunctions(utils::options::parseListPair(
93 "__builtin_expect;", Options.get("IgnoredFunctions", ""))) {
94 RawAssertList.split(AssertMacros, ",", -1, false);
95}
96
97// The options are explained in AssertSideEffectCheck.h.
99 Options.store(Opts, "CheckFunctionCalls", CheckFunctionCalls);
100 Options.store(Opts, "AssertMacros", RawAssertList);
101 Options.store(Opts, "IgnoredFunctions",
102 utils::options::serializeStringList(IgnoredFunctions));
103}
104
106 auto IgnoredFunctionsMatcher =
107 matchers::matchesAnyListedRegexName(IgnoredFunctions);
108
109 auto DescendantWithSideEffect =
110 traverse(TK_AsIs, hasDescendant(expr(hasSideEffect(
111 CheckFunctionCalls, IgnoredFunctionsMatcher))));
112 auto ConditionWithSideEffect = hasCondition(DescendantWithSideEffect);
113 Finder->addMatcher(
114 stmt(
115 anyOf(conditionalOperator(ConditionWithSideEffect),
116 ifStmt(ConditionWithSideEffect),
117 unaryOperator(hasOperatorName("!"),
118 hasUnaryOperand(unaryOperator(
119 hasOperatorName("!"),
120 hasUnaryOperand(DescendantWithSideEffect))))))
121 .bind("condStmt"),
122 this);
123}
124
125void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) {
126 const SourceManager &SM = *Result.SourceManager;
127 const LangOptions LangOpts = getLangOpts();
128 SourceLocation Loc = Result.Nodes.getNodeAs<Stmt>("condStmt")->getBeginLoc();
129
130 StringRef AssertMacroName;
131 while (Loc.isValid() && Loc.isMacroID()) {
132 const StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts);
133 Loc = SM.getImmediateMacroCallerLoc(Loc);
134
135 // Check if this macro is an assert.
136 if (llvm::is_contained(AssertMacros, MacroName)) {
137 AssertMacroName = MacroName;
138 break;
139 }
140 }
141 if (AssertMacroName.empty())
142 return;
143
144 diag(Loc, "side effect in %0() condition discarded in release builds")
145 << AssertMacroName;
146}
147
148} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
AssertSideEffectCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]