clang-tools  14.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 "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Frontend/CompilerInstance.h"
13 #include "clang/Lex/Lexer.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/Casting.h"
17 #include <algorithm>
18 #include <string>
19 
20 using namespace clang::ast_matchers;
21 
22 namespace clang {
23 namespace tidy {
24 namespace bugprone {
25 
26 namespace {
27 
28 AST_MATCHER_P(Expr, hasSideEffect, bool, CheckFunctionCalls) {
29  const Expr *E = &Node;
30 
31  if (const auto *Op = dyn_cast<UnaryOperator>(E)) {
32  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 
41  if (const auto *OpCallExpr = dyn_cast<CXXOperatorCallExpr>(E)) {
42  OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
43  return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
44  OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
45  OpKind == OO_SlashEqual || OpKind == OO_AmpEqual ||
46  OpKind == OO_PipeEqual || OpKind == OO_CaretEqual ||
47  OpKind == OO_LessLessEqual || OpKind == OO_GreaterGreaterEqual ||
48  OpKind == OO_PlusPlus || OpKind == OO_MinusMinus ||
49  OpKind == OO_PercentEqual || OpKind == OO_New ||
50  OpKind == OO_Delete || OpKind == OO_Array_New ||
51  OpKind == OO_Array_Delete;
52  }
53 
54  if (const auto *CExpr = dyn_cast<CallExpr>(E)) {
55  bool Result = CheckFunctionCalls;
56  if (const auto *FuncDecl = CExpr->getDirectCallee()) {
57  if (FuncDecl->getDeclName().isIdentifier() &&
58  FuncDecl->getName() == "__builtin_expect") // exceptions come here
59  Result = false;
60  else if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FuncDecl))
61  Result &= !MethodDecl->isConst();
62  }
63  return Result;
64  }
65 
66  return isa<CXXNewExpr>(E) || isa<CXXDeleteExpr>(E) || isa<CXXThrowExpr>(E);
67 }
68 
69 } // namespace
70 
71 AssertSideEffectCheck::AssertSideEffectCheck(StringRef Name,
72  ClangTidyContext *Context)
73  : ClangTidyCheck(Name, Context),
74  CheckFunctionCalls(Options.get("CheckFunctionCalls", false)),
75  RawAssertList(Options.get("AssertMacros",
76  "assert,NSAssert,NSCAssert")) {
77  StringRef(RawAssertList).split(AssertMacros, ",", -1, false);
78 }
79 
80 // The options are explained in AssertSideEffectCheck.h.
82  Options.store(Opts, "CheckFunctionCalls", CheckFunctionCalls);
83  Options.store(Opts, "AssertMacros", RawAssertList);
84 }
85 
86 void AssertSideEffectCheck::registerMatchers(MatchFinder *Finder) {
87  auto DescendantWithSideEffect =
88  traverse(TK_AsIs, hasDescendant(expr(hasSideEffect(CheckFunctionCalls))));
89  auto ConditionWithSideEffect = hasCondition(DescendantWithSideEffect);
90  Finder->addMatcher(
91  stmt(
92  anyOf(conditionalOperator(ConditionWithSideEffect),
93  ifStmt(ConditionWithSideEffect),
94  unaryOperator(hasOperatorName("!"),
95  hasUnaryOperand(unaryOperator(
96  hasOperatorName("!"),
97  hasUnaryOperand(DescendantWithSideEffect))))))
98  .bind("condStmt"),
99  this);
100 }
101 
102 void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) {
103  const SourceManager &SM = *Result.SourceManager;
104  const LangOptions LangOpts = getLangOpts();
105  SourceLocation Loc = Result.Nodes.getNodeAs<Stmt>("condStmt")->getBeginLoc();
106 
107  StringRef AssertMacroName;
108  while (Loc.isValid() && Loc.isMacroID()) {
109  StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, LangOpts);
110 
111  // Check if this macro is an assert.
112  if (llvm::is_contained(AssertMacros, MacroName)) {
113  AssertMacroName = MacroName;
114  break;
115  }
116  Loc = SM.getImmediateMacroCallerLoc(Loc);
117  }
118  if (AssertMacroName.empty())
119  return;
120 
121  diag(Loc, "side effect in %0() condition discarded in release builds")
122  << AssertMacroName;
123 }
124 
125 } // namespace bugprone
126 } // namespace tidy
127 } // namespace clang
Loc
SourceLocation Loc
Definition: KernelNameRestrictionCheck.cpp:45
clang::tidy::ClangTidyOptions::OptionMap
llvm::StringMap< ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:115
clang::tidy::bugprone::AssertSideEffectCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: AssertSideEffectCheck.cpp:81
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:54
clang::tidy::ClangTidyCheck::getLangOpts
const LangOptions & getLangOpts() const
Returns the language options from the context.
Definition: ClangTidyCheck.h:420
clang::ast_matchers
Definition: AbseilMatcher.h:14
AssertSideEffectCheck.h
clang::tidy::bugprone::AssertSideEffectCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: AssertSideEffectCheck.cpp:102
clang::tidy::bugprone::AssertSideEffectCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: AssertSideEffectCheck.cpp:86
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:416
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:71
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:28
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidyCheck.cpp:25
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::ClangTidyCheck::OptionsView::store
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.
Definition: ClangTidyCheck.cpp:120
clang::tidy::bugprone::AST_MATCHER_P
AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N)
Matches functions that have at least the specified amount of parameters.
Definition: EasilySwappableParametersCheck.cpp:1877