clang-tools 19.0.0git
AssertSideEffectCheck.cpp
Go to the documentation of this file.
1//===--- AssertSideEffectCheck.cpp - clang-tidy ---------------------------===//
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 "../utils/OptionsUtils.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 "llvm/Support/Casting.h"
19#include <algorithm>
20#include <string>
21
22using namespace clang::ast_matchers;
23
24namespace clang::tidy::bugprone {
25
26namespace {
27
28AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
29 clang::ast_matchers::internal::Matcher<NamedDecl>,
30 IgnoredFunctionsMatcher) {
31 const Expr *E = &Node;
32
33 if (const auto *Op = dyn_cast<UnaryOperator>(E)) {
34 UnaryOperator::Opcode OC = Op->getOpcode();
35 return OC == UO_PostInc || OC == UO_PostDec || OC == UO_PreInc ||
36 OC == UO_PreDec;
37 }
38
39 if (const auto *Op = dyn_cast<BinaryOperator>(E)) {
40 return Op->isAssignmentOp();
41 }
42
43 if (const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E)) {
44 if (const auto *MethodDecl =
45 dyn_cast_or_null<CXXMethodDecl>(OpCallExpr->getDirectCallee()))
46 if (MethodDecl->isConst())
47 return false;
48
49 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
50 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
51 OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
52 OpKind == OO_SlashEqual || OpKind == OO_AmpEqual ||
53 OpKind == OO_PipeEqual || OpKind == OO_CaretEqual ||
54 OpKind == OO_LessLessEqual || OpKind == OO_GreaterGreaterEqual ||
55 OpKind == OO_LessLess || OpKind == OO_GreaterGreater ||
56 OpKind == OO_PlusPlus || OpKind == OO_MinusMinus ||
57 OpKind == OO_PercentEqual || OpKind == OO_New ||
58 OpKind == OO_Delete || OpKind == OO_Array_New ||
59 OpKind == OO_Array_Delete;
60 }
61
62 if (const auto *CExpr = dyn_cast<CallExpr>(E)) {
63 bool Result = CheckFunctionCalls;
64 if (const auto *FuncDecl = CExpr->getDirectCallee()) {
65 if (FuncDecl->getDeclName().isIdentifier() &&
66 IgnoredFunctionsMatcher.matches(*FuncDecl, Finder,
67 Builder)) // exceptions come here
68 Result = false;
69 else if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
70 Result &= !MethodDecl->isConst();
71 }
72 return Result;
73 }
74
75 return isa<CXXNewExpr>(E) || isa<CXXDeleteExpr>(E) || isa<CXXThrowExpr>(E);
76}
77
78} // namespace
79
81 ClangTidyContext *Context)
82 : ClangTidyCheck(Name, Context),
83 CheckFunctionCalls(Options.get("CheckFunctionCalls", false)),
84 RawAssertList(Options.get("AssertMacros", "assert,NSAssert,NSCAssert")),
85 IgnoredFunctions(utils::options::parseListPair(
86 "__builtin_expect;", Options.get("IgnoredFunctions", ""))) {
87 StringRef(RawAssertList).split(AssertMacros, ",", -1, false);
88}
89
90// The options are explained in AssertSideEffectCheck.h.
92 Options.store(Opts, "CheckFunctionCalls", CheckFunctionCalls);
93 Options.store(Opts, "AssertMacros", RawAssertList);
94 Options.store(Opts, "IgnoredFunctions",
95 utils::options::serializeStringList(IgnoredFunctions));
96}
97
98void AssertSideEffectCheck::registerMatchers(MatchFinder *Finder) {
99 auto IgnoredFunctionsMatcher =
100 matchers::matchesAnyListedName(IgnoredFunctions);
101
102 auto DescendantWithSideEffect =
103 traverse(TK_AsIs, hasDescendant(expr(hasSideEffect(
104 CheckFunctionCalls, IgnoredFunctionsMatcher))));
105 auto ConditionWithSideEffect = hasCondition(DescendantWithSideEffect);
106 Finder->addMatcher(
107 stmt(
108 anyOf(conditionalOperator(ConditionWithSideEffect),
109 ifStmt(ConditionWithSideEffect),
110 unaryOperator(hasOperatorName("!"),
111 hasUnaryOperand(unaryOperator(
112 hasOperatorName("!"),
113 hasUnaryOperand(DescendantWithSideEffect))))))
114 .bind("condStmt"),
115 this);
116}
117
118void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) {
119 const SourceManager &SM = *Result.SourceManager;
120 const LangOptions LangOpts = getLangOpts();
121 SourceLocation Loc = Result.Nodes.getNodeAs<Stmt>("condStmt")->getBeginLoc();
122
123 StringRef AssertMacroName;
124 while (Loc.isValid() && Loc.isMacroID()) {
125 StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts);
126 Loc = SM.getImmediateMacroCallerLoc(Loc);
127
128 // Check if this macro is an assert.
129 if (llvm::is_contained(AssertMacros, MacroName)) {
130 AssertMacroName = MacroName;
131 break;
132 }
133 }
134 if (AssertMacroName.empty())
135 return;
136
137 diag(Loc, "side effect in %0() condition discarded in release builds")
138 << AssertMacroName;
139}
140
141} // namespace clang::tidy::bugprone
const Expr * E
llvm::SmallString< 256U > Name
CodeCompletionBuilder Builder
SourceLocation Loc
std::string MacroName
Definition: Preamble.cpp:240
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
AssertSideEffectCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(llvm::ArrayRef< StringRef > NameList)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap