1 //===---------- ExprSequence.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
9 #include "ExprSequence.h"
10 #include "clang/AST/ParentMapContext.h"
11
12 namespace clang {
13 namespace tidy {
14 namespace utils {
15
16 // Returns the Stmt nodes that are parents of 'S', skipping any potential
17 // intermediate non-Stmt nodes.
18 //
19 // In almost all cases, this function returns a single parent or no parents at
20 // all.
21 //
22 // The case that a Stmt has multiple parents is rare but does actually occur in
23 // the parts of the AST that we're interested in. Specifically, InitListExpr
24 // nodes cause ASTContext::getParent() to return multiple parents for certain
25 // nodes in their subtree because RecursiveASTVisitor visits both the syntactic
26 // and semantic forms of InitListExpr, and the parent-child relationships are
27 // different between the two forms.
getParentStmts(const Stmt * S,ASTContext * Context)28 static SmallVector<const Stmt *, 1> getParentStmts(const Stmt *S,
29 ASTContext *Context) {
30 SmallVector<const Stmt *, 1> Result;
31
32 TraversalKindScope RAII(*Context, ast_type_traits::TK_AsIs);
33 DynTypedNodeList Parents = Context->getParents(*S);
34
35 SmallVector<ast_type_traits::DynTypedNode, 1> NodesToProcess(Parents.begin(),
36 Parents.end());
37
38 while (!NodesToProcess.empty()) {
39 ast_type_traits::DynTypedNode Node = NodesToProcess.back();
40 NodesToProcess.pop_back();
41
42 if (const auto *S = Node.get<Stmt>()) {
43 Result.push_back(S);
44 } else {
45 Parents = Context->getParents(Node);
46 NodesToProcess.append(Parents.begin(), Parents.end());
47 }
48 }
49
50 return Result;
51 }
52
53 namespace {
isDescendantOrEqual(const Stmt * Descendant,const Stmt * Ancestor,ASTContext * Context)54 bool isDescendantOrEqual(const Stmt *Descendant, const Stmt *Ancestor,
55 ASTContext *Context) {
56 if (Descendant == Ancestor)
57 return true;
58 for (const Stmt *Parent : getParentStmts(Descendant, Context)) {
59 if (isDescendantOrEqual(Parent, Ancestor, Context))
60 return true;
61 }
62
63 return false;
64 }
65 }
66
ExprSequence(const CFG * TheCFG,const Stmt * Root,ASTContext * TheContext)67 ExprSequence::ExprSequence(const CFG *TheCFG, const Stmt *Root,
68 ASTContext *TheContext)
69 : Context(TheContext), Root(Root) {
70 for (const auto &SyntheticStmt : TheCFG->synthetic_stmts()) {
71 SyntheticStmtSourceMap[SyntheticStmt.first] = SyntheticStmt.second;
72 }
73 }
74
inSequence(const Stmt * Before,const Stmt * After) const75 bool ExprSequence::inSequence(const Stmt *Before, const Stmt *After) const {
76 Before = resolveSyntheticStmt(Before);
77 After = resolveSyntheticStmt(After);
78
79 // If 'After' is in the subtree of the siblings that follow 'Before' in the
80 // chain of successors, we know that 'After' is sequenced after 'Before'.
81 for (const Stmt *Successor = getSequenceSuccessor(Before); Successor;
82 Successor = getSequenceSuccessor(Successor)) {
83 if (isDescendantOrEqual(After, Successor, Context))
84 return true;
85 }
86
87 // If 'After' is a parent of 'Before' or is sequenced after one of these
88 // parents, we know that it is sequenced after 'Before'.
89 for (const Stmt *Parent : getParentStmts(Before, Context)) {
90 if (Parent == After || inSequence(Parent, After))
91 return true;
92 }
93
94 return false;
95 }
96
potentiallyAfter(const Stmt * After,const Stmt * Before) const97 bool ExprSequence::potentiallyAfter(const Stmt *After,
98 const Stmt *Before) const {
99 return !inSequence(After, Before);
100 }
101
getSequenceSuccessor(const Stmt * S) const102 const Stmt *ExprSequence::getSequenceSuccessor(const Stmt *S) const {
103 for (const Stmt *Parent : getParentStmts(S, Context)) {
104 // If a statement has multiple parents, make sure we're using the parent
105 // that lies within the sub-tree under Root.
106 if (!isDescendantOrEqual(Parent, Root, Context))
107 continue;
108
109 if (const auto *BO = dyn_cast<BinaryOperator>(Parent)) {
110 // Comma operator: Right-hand side is sequenced after the left-hand side.
111 if (BO->getLHS() == S && BO->getOpcode() == BO_Comma)
112 return BO->getRHS();
113 } else if (const auto *InitList = dyn_cast<InitListExpr>(Parent)) {
114 // Initializer list: Each initializer clause is sequenced after the
115 // clauses that precede it.
116 for (unsigned I = 1; I < InitList->getNumInits(); ++I) {
117 if (InitList->getInit(I - 1) == S)
118 return InitList->getInit(I);
119 }
120 } else if (const auto *Compound = dyn_cast<CompoundStmt>(Parent)) {
121 // Compound statement: Each sub-statement is sequenced after the
122 // statements that precede it.
123 const Stmt *Previous = nullptr;
124 for (const auto *Child : Compound->body()) {
125 if (Previous == S)
126 return Child;
127 Previous = Child;
128 }
129 } else if (const auto *TheDeclStmt = dyn_cast<DeclStmt>(Parent)) {
130 // Declaration: Every initializer expression is sequenced after the
131 // initializer expressions that precede it.
132 const Expr *PreviousInit = nullptr;
133 for (const Decl *TheDecl : TheDeclStmt->decls()) {
134 if (const auto *TheVarDecl = dyn_cast<VarDecl>(TheDecl)) {
135 if (const Expr *Init = TheVarDecl->getInit()) {
136 if (PreviousInit == S)
137 return Init;
138 PreviousInit = Init;
139 }
140 }
141 }
142 } else if (const auto *ForRange = dyn_cast<CXXForRangeStmt>(Parent)) {
143 // Range-based for: Loop variable declaration is sequenced before the
144 // body. (We need this rule because these get placed in the same
145 // CFGBlock.)
146 if (S == ForRange->getLoopVarStmt())
147 return ForRange->getBody();
148 } else if (const auto *TheIfStmt = dyn_cast<IfStmt>(Parent)) {
149 // If statement:
150 // - Sequence init statement before variable declaration, if present;
151 // before condition evaluation, otherwise.
152 // - Sequence variable declaration (along with the expression used to
153 // initialize it) before the evaluation of the condition.
154 if (S == TheIfStmt->getInit()) {
155 if (TheIfStmt->getConditionVariableDeclStmt() != nullptr)
156 return TheIfStmt->getConditionVariableDeclStmt();
157 return TheIfStmt->getCond();
158 }
159 if (S == TheIfStmt->getConditionVariableDeclStmt())
160 return TheIfStmt->getCond();
161 } else if (const auto *TheSwitchStmt = dyn_cast<SwitchStmt>(Parent)) {
162 // Ditto for switch statements.
163 if (S == TheSwitchStmt->getInit()) {
164 if (TheSwitchStmt->getConditionVariableDeclStmt() != nullptr)
165 return TheSwitchStmt->getConditionVariableDeclStmt();
166 return TheSwitchStmt->getCond();
167 }
168 if (S == TheSwitchStmt->getConditionVariableDeclStmt())
169 return TheSwitchStmt->getCond();
170 } else if (const auto *TheWhileStmt = dyn_cast<WhileStmt>(Parent)) {
171 // While statement: Sequence variable declaration (along with the
172 // expression used to initialize it) before the evaluation of the
173 // condition.
174 if (S == TheWhileStmt->getConditionVariableDeclStmt())
175 return TheWhileStmt->getCond();
176 }
177 }
178
179 return nullptr;
180 }
181
resolveSyntheticStmt(const Stmt * S) const182 const Stmt *ExprSequence::resolveSyntheticStmt(const Stmt *S) const {
183 if (SyntheticStmtSourceMap.count(S))
184 return SyntheticStmtSourceMap.lookup(S);
185 return S;
186 }
187
StmtToBlockMap(const CFG * TheCFG,ASTContext * TheContext)188 StmtToBlockMap::StmtToBlockMap(const CFG *TheCFG, ASTContext *TheContext)
189 : Context(TheContext) {
190 for (const auto *B : *TheCFG) {
191 for (const auto &Elem : *B) {
192 if (Optional<CFGStmt> S = Elem.getAs<CFGStmt>())
193 Map[S->getStmt()] = B;
194 }
195 }
196 }
197
blockContainingStmt(const Stmt * S) const198 const CFGBlock *StmtToBlockMap::blockContainingStmt(const Stmt *S) const {
199 while (!Map.count(S)) {
200 SmallVector<const Stmt *, 1> Parents = getParentStmts(S, Context);
201 if (Parents.empty())
202 return nullptr;
203 S = Parents[0];
204 }
205
206 return Map.lookup(S);
207 }
208
209 } // namespace utils
210 } // namespace tidy
211 } // namespace clang
212