1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
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 // This file defines the CFG and CFGBuilder classes for representing and
10 // building Control-Flow Graphs (CFGs) from ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Analysis/CFG.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/OperationKinds.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtVisitor.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Analysis/ConstructionContext.h"
31 #include "clang/Analysis/Support/BumpVector.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/JsonSupport.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/APSInt.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/Optional.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/SetVector.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/Support/Allocator.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/DOTGraphTraits.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/SaveAndRestore.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <cassert>
58 #include <memory>
59 #include <string>
60 #include <tuple>
61 #include <utility>
62 #include <vector>
63
64 using namespace clang;
65
GetEndLoc(Decl * D)66 static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(D))
68 if (Expr *Ex = VD->getInit())
69 return Ex->getSourceRange().getEnd();
70 return D->getLocation();
71 }
72
73 /// Returns true on constant values based around a single IntegerLiteral.
74 /// Allow for use of parentheses, integer casts, and negative signs.
IsIntegerLiteralConstantExpr(const Expr * E)75 static bool IsIntegerLiteralConstantExpr(const Expr *E) {
76 // Allow parentheses
77 E = E->IgnoreParens();
78
79 // Allow conversions to different integer kind.
80 if (const auto *CE = dyn_cast<CastExpr>(E)) {
81 if (CE->getCastKind() != CK_IntegralCast)
82 return false;
83 E = CE->getSubExpr();
84 }
85
86 // Allow negative numbers.
87 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
88 if (UO->getOpcode() != UO_Minus)
89 return false;
90 E = UO->getSubExpr();
91 }
92
93 return isa<IntegerLiteral>(E);
94 }
95
96 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
97 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
98 /// returns nullptr.
tryTransformToIntOrEnumConstant(const Expr * E)99 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
100 E = E->IgnoreParens();
101 if (IsIntegerLiteralConstantExpr(E))
102 return E;
103 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
104 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
105 return nullptr;
106 }
107
108 /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
109 /// NumExpr is an integer literal or an enum constant.
110 ///
111 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
112 /// null.
113 static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
tryNormalizeBinaryOperator(const BinaryOperator * B)114 tryNormalizeBinaryOperator(const BinaryOperator *B) {
115 BinaryOperatorKind Op = B->getOpcode();
116
117 const Expr *MaybeDecl = B->getLHS();
118 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
119 // Expr looked like `0 == Foo` instead of `Foo == 0`
120 if (Constant == nullptr) {
121 // Flip the operator
122 if (Op == BO_GT)
123 Op = BO_LT;
124 else if (Op == BO_GE)
125 Op = BO_LE;
126 else if (Op == BO_LT)
127 Op = BO_GT;
128 else if (Op == BO_LE)
129 Op = BO_GE;
130
131 MaybeDecl = B->getRHS();
132 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
133 }
134
135 return std::make_tuple(MaybeDecl, Op, Constant);
136 }
137
138 /// For an expression `x == Foo && x == Bar`, this determines whether the
139 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
140 /// literals.
141 ///
142 /// It's an error to pass this arguments that are not either IntegerLiterals
143 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
areExprTypesCompatible(const Expr * E1,const Expr * E2)144 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
145 // User intent isn't clear if they're mixing int literals with enum
146 // constants.
147 if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
148 return false;
149
150 // Integer literal comparisons, regardless of literal type, are acceptable.
151 if (!isa<DeclRefExpr>(E1))
152 return true;
153
154 // IntegerLiterals are handled above and only EnumConstantDecls are expected
155 // beyond this point
156 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
157 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
158 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
159
160 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
161 const DeclContext *DC1 = Decl1->getDeclContext();
162 const DeclContext *DC2 = Decl2->getDeclContext();
163
164 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
165 return DC1 == DC2;
166 }
167
168 namespace {
169
170 class CFGBuilder;
171
172 /// The CFG builder uses a recursive algorithm to build the CFG. When
173 /// we process an expression, sometimes we know that we must add the
174 /// subexpressions as block-level expressions. For example:
175 ///
176 /// exp1 || exp2
177 ///
178 /// When processing the '||' expression, we know that exp1 and exp2
179 /// need to be added as block-level expressions, even though they
180 /// might not normally need to be. AddStmtChoice records this
181 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
182 /// the builder has an option not to add a subexpression as a
183 /// block-level expression.
184 class AddStmtChoice {
185 public:
186 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
187
AddStmtChoice(Kind a_kind=NotAlwaysAdd)188 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
189
190 bool alwaysAdd(CFGBuilder &builder,
191 const Stmt *stmt) const;
192
193 /// Return a copy of this object, except with the 'always-add' bit
194 /// set as specified.
withAlwaysAdd(bool alwaysAdd) const195 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
196 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
197 }
198
199 private:
200 Kind kind;
201 };
202
203 /// LocalScope - Node in tree of local scopes created for C++ implicit
204 /// destructor calls generation. It contains list of automatic variables
205 /// declared in the scope and link to position in previous scope this scope
206 /// began in.
207 ///
208 /// The process of creating local scopes is as follows:
209 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
210 /// - Before processing statements in scope (e.g. CompoundStmt) create
211 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
212 /// and set CFGBuilder::ScopePos to the end of new scope,
213 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
214 /// at this VarDecl,
215 /// - For every normal (without jump) end of scope add to CFGBlock destructors
216 /// for objects in the current scope,
217 /// - For every jump add to CFGBlock destructors for objects
218 /// between CFGBuilder::ScopePos and local scope position saved for jump
219 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
220 /// jump target position will be on the path to root from CFGBuilder::ScopePos
221 /// (adding any variable that doesn't need constructor to be called to
222 /// LocalScope can break this assumption),
223 ///
224 class LocalScope {
225 public:
226 friend class const_iterator;
227
228 using AutomaticVarsTy = BumpVector<VarDecl *>;
229
230 /// const_iterator - Iterates local scope backwards and jumps to previous
231 /// scope on reaching the beginning of currently iterated scope.
232 class const_iterator {
233 const LocalScope* Scope = nullptr;
234
235 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
236 /// Invalid iterator (with null Scope) has VarIter equal to 0.
237 unsigned VarIter = 0;
238
239 public:
240 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
241 /// Incrementing invalid iterator is allowed and will result in invalid
242 /// iterator.
243 const_iterator() = default;
244
245 /// Create valid iterator. In case when S.Prev is an invalid iterator and
246 /// I is equal to 0, this will create invalid iterator.
const_iterator(const LocalScope & S,unsigned I)247 const_iterator(const LocalScope& S, unsigned I)
248 : Scope(&S), VarIter(I) {
249 // Iterator to "end" of scope is not allowed. Handle it by going up
250 // in scopes tree possibly up to invalid iterator in the root.
251 if (VarIter == 0 && Scope)
252 *this = Scope->Prev;
253 }
254
operator ->() const255 VarDecl *const* operator->() const {
256 assert(Scope && "Dereferencing invalid iterator is not allowed");
257 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
258 return &Scope->Vars[VarIter - 1];
259 }
260
getFirstVarInScope() const261 const VarDecl *getFirstVarInScope() const {
262 assert(Scope && "Dereferencing invalid iterator is not allowed");
263 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
264 return Scope->Vars[0];
265 }
266
operator *() const267 VarDecl *operator*() const {
268 return *this->operator->();
269 }
270
operator ++()271 const_iterator &operator++() {
272 if (!Scope)
273 return *this;
274
275 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
276 --VarIter;
277 if (VarIter == 0)
278 *this = Scope->Prev;
279 return *this;
280 }
operator ++(int)281 const_iterator operator++(int) {
282 const_iterator P = *this;
283 ++*this;
284 return P;
285 }
286
operator ==(const const_iterator & rhs) const287 bool operator==(const const_iterator &rhs) const {
288 return Scope == rhs.Scope && VarIter == rhs.VarIter;
289 }
operator !=(const const_iterator & rhs) const290 bool operator!=(const const_iterator &rhs) const {
291 return !(*this == rhs);
292 }
293
operator bool() const294 explicit operator bool() const {
295 return *this != const_iterator();
296 }
297
298 int distance(const_iterator L);
299 const_iterator shared_parent(const_iterator L);
pointsToFirstDeclaredVar()300 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
301 };
302
303 private:
304 BumpVectorContext ctx;
305
306 /// Automatic variables in order of declaration.
307 AutomaticVarsTy Vars;
308
309 /// Iterator to variable in previous scope that was declared just before
310 /// begin of this scope.
311 const_iterator Prev;
312
313 public:
314 /// Constructs empty scope linked to previous scope in specified place.
LocalScope(BumpVectorContext ctx,const_iterator P)315 LocalScope(BumpVectorContext ctx, const_iterator P)
316 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
317
318 /// Begin of scope in direction of CFG building (backwards).
begin() const319 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
320
addVar(VarDecl * VD)321 void addVar(VarDecl *VD) {
322 Vars.push_back(VD, ctx);
323 }
324 };
325
326 } // namespace
327
328 /// distance - Calculates distance from this to L. L must be reachable from this
329 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
330 /// number of scopes between this and L.
distance(LocalScope::const_iterator L)331 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
332 int D = 0;
333 const_iterator F = *this;
334 while (F.Scope != L.Scope) {
335 assert(F != const_iterator() &&
336 "L iterator is not reachable from F iterator.");
337 D += F.VarIter;
338 F = F.Scope->Prev;
339 }
340 D += F.VarIter - L.VarIter;
341 return D;
342 }
343
344 /// Calculates the closest parent of this iterator
345 /// that is in a scope reachable through the parents of L.
346 /// I.e. when using 'goto' from this to L, the lifetime of all variables
347 /// between this and shared_parent(L) end.
348 LocalScope::const_iterator
shared_parent(LocalScope::const_iterator L)349 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
350 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
351 while (true) {
352 ScopesOfL.insert(L.Scope);
353 if (L == const_iterator())
354 break;
355 L = L.Scope->Prev;
356 }
357
358 const_iterator F = *this;
359 while (true) {
360 if (ScopesOfL.count(F.Scope))
361 return F;
362 assert(F != const_iterator() &&
363 "L iterator is not reachable from F iterator.");
364 F = F.Scope->Prev;
365 }
366 }
367
368 namespace {
369
370 /// Structure for specifying position in CFG during its build process. It
371 /// consists of CFGBlock that specifies position in CFG and
372 /// LocalScope::const_iterator that specifies position in LocalScope graph.
373 struct BlockScopePosPair {
374 CFGBlock *block = nullptr;
375 LocalScope::const_iterator scopePosition;
376
377 BlockScopePosPair() = default;
BlockScopePosPair__anon4992f0f40211::BlockScopePosPair378 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
379 : block(b), scopePosition(scopePos) {}
380 };
381
382 /// TryResult - a class representing a variant over the values
383 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
384 /// and is used by the CFGBuilder to decide if a branch condition
385 /// can be decided up front during CFG construction.
386 class TryResult {
387 int X = -1;
388
389 public:
390 TryResult() = default;
TryResult(bool b)391 TryResult(bool b) : X(b ? 1 : 0) {}
392
isTrue() const393 bool isTrue() const { return X == 1; }
isFalse() const394 bool isFalse() const { return X == 0; }
isKnown() const395 bool isKnown() const { return X >= 0; }
396
negate()397 void negate() {
398 assert(isKnown());
399 X ^= 0x1;
400 }
401 };
402
403 } // namespace
404
bothKnownTrue(TryResult R1,TryResult R2)405 static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
406 if (!R1.isKnown() || !R2.isKnown())
407 return TryResult();
408 return TryResult(R1.isTrue() && R2.isTrue());
409 }
410
411 namespace {
412
413 class reverse_children {
414 llvm::SmallVector<Stmt *, 12> childrenBuf;
415 ArrayRef<Stmt *> children;
416
417 public:
418 reverse_children(Stmt *S);
419
420 using iterator = ArrayRef<Stmt *>::reverse_iterator;
421
begin() const422 iterator begin() const { return children.rbegin(); }
end() const423 iterator end() const { return children.rend(); }
424 };
425
426 } // namespace
427
reverse_children(Stmt * S)428 reverse_children::reverse_children(Stmt *S) {
429 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
430 children = CE->getRawSubExprs();
431 return;
432 }
433 switch (S->getStmtClass()) {
434 // Note: Fill in this switch with more cases we want to optimize.
435 case Stmt::InitListExprClass: {
436 InitListExpr *IE = cast<InitListExpr>(S);
437 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
438 IE->getNumInits());
439 return;
440 }
441 default:
442 break;
443 }
444
445 // Default case for all other statements.
446 for (Stmt *SubStmt : S->children())
447 childrenBuf.push_back(SubStmt);
448
449 // This needs to be done *after* childrenBuf has been populated.
450 children = childrenBuf;
451 }
452
453 namespace {
454
455 /// CFGBuilder - This class implements CFG construction from an AST.
456 /// The builder is stateful: an instance of the builder should be used to only
457 /// construct a single CFG.
458 ///
459 /// Example usage:
460 ///
461 /// CFGBuilder builder;
462 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
463 ///
464 /// CFG construction is done via a recursive walk of an AST. We actually parse
465 /// the AST in reverse order so that the successor of a basic block is
466 /// constructed prior to its predecessor. This allows us to nicely capture
467 /// implicit fall-throughs without extra basic blocks.
468 class CFGBuilder {
469 using JumpTarget = BlockScopePosPair;
470 using JumpSource = BlockScopePosPair;
471
472 ASTContext *Context;
473 std::unique_ptr<CFG> cfg;
474
475 // Current block.
476 CFGBlock *Block = nullptr;
477
478 // Block after the current block.
479 CFGBlock *Succ = nullptr;
480
481 JumpTarget ContinueJumpTarget;
482 JumpTarget BreakJumpTarget;
483 JumpTarget SEHLeaveJumpTarget;
484 CFGBlock *SwitchTerminatedBlock = nullptr;
485 CFGBlock *DefaultCaseBlock = nullptr;
486
487 // This can point either to a try or a __try block. The frontend forbids
488 // mixing both kinds in one function, so having one for both is enough.
489 CFGBlock *TryTerminatedBlock = nullptr;
490
491 // Current position in local scope.
492 LocalScope::const_iterator ScopePos;
493
494 // LabelMap records the mapping from Label expressions to their jump targets.
495 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
496 LabelMapTy LabelMap;
497
498 // A list of blocks that end with a "goto" that must be backpatched to their
499 // resolved targets upon completion of CFG construction.
500 using BackpatchBlocksTy = std::vector<JumpSource>;
501 BackpatchBlocksTy BackpatchBlocks;
502
503 // A list of labels whose address has been taken (for indirect gotos).
504 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
505 LabelSetTy AddressTakenLabels;
506
507 // Information about the currently visited C++ object construction site.
508 // This is set in the construction trigger and read when the constructor
509 // or a function that returns an object by value is being visited.
510 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
511 ConstructionContextMap;
512
513 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
514 DeclsWithEndedScopeSetTy DeclsWithEndedScope;
515
516 bool badCFG = false;
517 const CFG::BuildOptions &BuildOpts;
518
519 // State to track for building switch statements.
520 bool switchExclusivelyCovered = false;
521 Expr::EvalResult *switchCond = nullptr;
522
523 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
524 const Stmt *lastLookup = nullptr;
525
526 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
527 // during construction of branches for chained logical operators.
528 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
529 CachedBoolEvalsTy CachedBoolEvals;
530
531 public:
CFGBuilder(ASTContext * astContext,const CFG::BuildOptions & buildOpts)532 explicit CFGBuilder(ASTContext *astContext,
533 const CFG::BuildOptions &buildOpts)
534 : Context(astContext), cfg(new CFG()), // crew a new CFG
535 ConstructionContextMap(), BuildOpts(buildOpts) {}
536
537
538 // buildCFG - Used by external clients to construct the CFG.
539 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
540
541 bool alwaysAdd(const Stmt *stmt);
542
543 private:
544 // Visitors to walk an AST and construct the CFG.
545 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
546 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
547 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
548 CFGBlock *VisitBreakStmt(BreakStmt *B);
549 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
550 CFGBlock *VisitCaseStmt(CaseStmt *C);
551 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
552 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
553 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
554 AddStmtChoice asc);
555 CFGBlock *VisitContinueStmt(ContinueStmt *C);
556 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
557 AddStmtChoice asc);
558 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
559 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
560 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
561 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
562 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
563 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
564 AddStmtChoice asc);
565 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
566 AddStmtChoice asc);
567 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
568 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
569 CFGBlock *VisitDeclStmt(DeclStmt *DS);
570 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
571 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
572 CFGBlock *VisitDoStmt(DoStmt *D);
573 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
574 AddStmtChoice asc, bool ExternallyDestructed);
575 CFGBlock *VisitForStmt(ForStmt *F);
576 CFGBlock *VisitGotoStmt(GotoStmt *G);
577 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
578 CFGBlock *VisitIfStmt(IfStmt *I);
579 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
580 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
581 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
582 CFGBlock *VisitLabelStmt(LabelStmt *L);
583 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
584 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
585 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
586 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
587 Stmt *Term,
588 CFGBlock *TrueBlock,
589 CFGBlock *FalseBlock);
590 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
591 AddStmtChoice asc);
592 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
593 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
594 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
595 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
596 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
597 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
598 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
599 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
600 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
601 CFGBlock *VisitReturnStmt(Stmt *S);
602 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
603 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
604 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
605 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
606 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
607 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
608 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
609 AddStmtChoice asc);
610 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
611 CFGBlock *VisitWhileStmt(WhileStmt *W);
612
613 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
614 bool ExternallyDestructed = false);
615 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
616 CFGBlock *VisitChildren(Stmt *S);
617 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
618 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
619 AddStmtChoice asc);
620
maybeAddScopeBeginForVarDecl(CFGBlock * B,const VarDecl * VD,const Stmt * S)621 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
622 const Stmt *S) {
623 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
624 appendScopeBegin(B, VD, S);
625 }
626
627 /// When creating the CFG for temporary destructors, we want to mirror the
628 /// branch structure of the corresponding constructor calls.
629 /// Thus, while visiting a statement for temporary destructors, we keep a
630 /// context to keep track of the following information:
631 /// - whether a subexpression is executed unconditionally
632 /// - if a subexpression is executed conditionally, the first
633 /// CXXBindTemporaryExpr we encounter in that subexpression (which
634 /// corresponds to the last temporary destructor we have to call for this
635 /// subexpression) and the CFG block at that point (which will become the
636 /// successor block when inserting the decision point).
637 ///
638 /// That way, we can build the branch structure for temporary destructors as
639 /// follows:
640 /// 1. If a subexpression is executed unconditionally, we add the temporary
641 /// destructor calls to the current block.
642 /// 2. If a subexpression is executed conditionally, when we encounter a
643 /// CXXBindTemporaryExpr:
644 /// a) If it is the first temporary destructor call in the subexpression,
645 /// we remember the CXXBindTemporaryExpr and the current block in the
646 /// TempDtorContext; we start a new block, and insert the temporary
647 /// destructor call.
648 /// b) Otherwise, add the temporary destructor call to the current block.
649 /// 3. When we finished visiting a conditionally executed subexpression,
650 /// and we found at least one temporary constructor during the visitation
651 /// (2.a has executed), we insert a decision block that uses the
652 /// CXXBindTemporaryExpr as terminator, and branches to the current block
653 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
654 /// branches to the stored successor.
655 struct TempDtorContext {
656 TempDtorContext() = default;
TempDtorContext__anon4992f0f40411::CFGBuilder::TempDtorContext657 TempDtorContext(TryResult KnownExecuted)
658 : IsConditional(true), KnownExecuted(KnownExecuted) {}
659
660 /// Returns whether we need to start a new branch for a temporary destructor
661 /// call. This is the case when the temporary destructor is
662 /// conditionally executed, and it is the first one we encounter while
663 /// visiting a subexpression - other temporary destructors at the same level
664 /// will be added to the same block and are executed under the same
665 /// condition.
needsTempDtorBranch__anon4992f0f40411::CFGBuilder::TempDtorContext666 bool needsTempDtorBranch() const {
667 return IsConditional && !TerminatorExpr;
668 }
669
670 /// Remember the successor S of a temporary destructor decision branch for
671 /// the corresponding CXXBindTemporaryExpr E.
setDecisionPoint__anon4992f0f40411::CFGBuilder::TempDtorContext672 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
673 Succ = S;
674 TerminatorExpr = E;
675 }
676
677 const bool IsConditional = false;
678 const TryResult KnownExecuted = true;
679 CFGBlock *Succ = nullptr;
680 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
681 };
682
683 // Visitors to walk an AST and generate destructors of temporaries in
684 // full expression.
685 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
686 TempDtorContext &Context);
687 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
688 TempDtorContext &Context);
689 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
690 bool ExternallyDestructed,
691 TempDtorContext &Context);
692 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
693 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
694 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
695 AbstractConditionalOperator *E, bool ExternallyDestructed,
696 TempDtorContext &Context);
697 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
698 CFGBlock *FalseSucc = nullptr);
699
700 // NYS == Not Yet Supported
NYS()701 CFGBlock *NYS() {
702 badCFG = true;
703 return Block;
704 }
705
706 // Remember to apply the construction context based on the current \p Layer
707 // when constructing the CFG element for \p CE.
708 void consumeConstructionContext(const ConstructionContextLayer *Layer,
709 Expr *E);
710
711 // Scan \p Child statement to find constructors in it, while keeping in mind
712 // that its parent statement is providing a partial construction context
713 // described by \p Layer. If a constructor is found, it would be assigned
714 // the context based on the layer. If an additional construction context layer
715 // is found, the function recurses into that.
716 void findConstructionContexts(const ConstructionContextLayer *Layer,
717 Stmt *Child);
718
719 // Scan all arguments of a call expression for a construction context.
720 // These sorts of call expressions don't have a common superclass,
721 // hence strict duck-typing.
722 template <typename CallLikeExpr,
723 typename = typename std::enable_if<
724 std::is_same<CallLikeExpr, CallExpr>::value ||
725 std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
726 std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
findConstructionContextsForArguments(CallLikeExpr * E)727 void findConstructionContextsForArguments(CallLikeExpr *E) {
728 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
729 Expr *Arg = E->getArg(i);
730 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
731 findConstructionContexts(
732 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
733 ConstructionContextItem(E, i)),
734 Arg);
735 }
736 }
737
738 // Unset the construction context after consuming it. This is done immediately
739 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
740 // there's no need to do this manually in every Visit... function.
741 void cleanupConstructionContext(Expr *E);
742
autoCreateBlock()743 void autoCreateBlock() { if (!Block) Block = createBlock(); }
744 CFGBlock *createBlock(bool add_successor = true);
745 CFGBlock *createNoReturnBlock();
746
addStmt(Stmt * S)747 CFGBlock *addStmt(Stmt *S) {
748 return Visit(S, AddStmtChoice::AlwaysAdd);
749 }
750
751 CFGBlock *addInitializer(CXXCtorInitializer *I);
752 void addLoopExit(const Stmt *LoopStmt);
753 void addAutomaticObjDtors(LocalScope::const_iterator B,
754 LocalScope::const_iterator E, Stmt *S);
755 void addLifetimeEnds(LocalScope::const_iterator B,
756 LocalScope::const_iterator E, Stmt *S);
757 void addAutomaticObjHandling(LocalScope::const_iterator B,
758 LocalScope::const_iterator E, Stmt *S);
759 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
760 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
761 Stmt *S);
762
763 void getDeclsWithEndedScope(LocalScope::const_iterator B,
764 LocalScope::const_iterator E, Stmt *S);
765
766 // Local scopes creation.
767 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
768
769 void addLocalScopeForStmt(Stmt *S);
770 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
771 LocalScope* Scope = nullptr);
772 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
773
774 void addLocalScopeAndDtors(Stmt *S);
775
retrieveAndCleanupConstructionContext(Expr * E)776 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
777 if (!BuildOpts.AddRichCXXConstructors)
778 return nullptr;
779
780 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
781 if (!Layer)
782 return nullptr;
783
784 cleanupConstructionContext(E);
785 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
786 Layer);
787 }
788
789 // Interface to CFGBlock - adding CFGElements.
790
appendStmt(CFGBlock * B,const Stmt * S)791 void appendStmt(CFGBlock *B, const Stmt *S) {
792 if (alwaysAdd(S) && cachedEntry)
793 cachedEntry->second = B;
794
795 // All block-level expressions should have already been IgnoreParens()ed.
796 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
797 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
798 }
799
appendConstructor(CFGBlock * B,CXXConstructExpr * CE)800 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
801 if (const ConstructionContext *CC =
802 retrieveAndCleanupConstructionContext(CE)) {
803 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
804 return;
805 }
806
807 // No valid construction context found. Fall back to statement.
808 B->appendStmt(CE, cfg->getBumpVectorContext());
809 }
810
appendCall(CFGBlock * B,CallExpr * CE)811 void appendCall(CFGBlock *B, CallExpr *CE) {
812 if (alwaysAdd(CE) && cachedEntry)
813 cachedEntry->second = B;
814
815 if (const ConstructionContext *CC =
816 retrieveAndCleanupConstructionContext(CE)) {
817 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
818 return;
819 }
820
821 // No valid construction context found. Fall back to statement.
822 B->appendStmt(CE, cfg->getBumpVectorContext());
823 }
824
appendInitializer(CFGBlock * B,CXXCtorInitializer * I)825 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
826 B->appendInitializer(I, cfg->getBumpVectorContext());
827 }
828
appendNewAllocator(CFGBlock * B,CXXNewExpr * NE)829 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
830 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
831 }
832
appendBaseDtor(CFGBlock * B,const CXXBaseSpecifier * BS)833 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
834 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
835 }
836
appendMemberDtor(CFGBlock * B,FieldDecl * FD)837 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
838 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
839 }
840
appendObjCMessage(CFGBlock * B,ObjCMessageExpr * ME)841 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
842 if (alwaysAdd(ME) && cachedEntry)
843 cachedEntry->second = B;
844
845 if (const ConstructionContext *CC =
846 retrieveAndCleanupConstructionContext(ME)) {
847 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
848 return;
849 }
850
851 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
852 cfg->getBumpVectorContext());
853 }
854
appendTemporaryDtor(CFGBlock * B,CXXBindTemporaryExpr * E)855 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
856 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
857 }
858
appendAutomaticObjDtor(CFGBlock * B,VarDecl * VD,Stmt * S)859 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
860 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
861 }
862
appendLifetimeEnds(CFGBlock * B,VarDecl * VD,Stmt * S)863 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
864 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
865 }
866
appendLoopExit(CFGBlock * B,const Stmt * LoopStmt)867 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
868 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
869 }
870
appendDeleteDtor(CFGBlock * B,CXXRecordDecl * RD,CXXDeleteExpr * DE)871 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
872 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
873 }
874
875 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
876 LocalScope::const_iterator B, LocalScope::const_iterator E);
877
878 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
879 LocalScope::const_iterator B,
880 LocalScope::const_iterator E);
881
882 const VarDecl *
883 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
884 LocalScope::const_iterator B,
885 LocalScope::const_iterator E);
886
addSuccessor(CFGBlock * B,CFGBlock * S,bool IsReachable=true)887 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
888 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
889 cfg->getBumpVectorContext());
890 }
891
892 /// Add a reachable successor to a block, with the alternate variant that is
893 /// unreachable.
addSuccessor(CFGBlock * B,CFGBlock * ReachableBlock,CFGBlock * AltBlock)894 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
895 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
896 cfg->getBumpVectorContext());
897 }
898
appendScopeBegin(CFGBlock * B,const VarDecl * VD,const Stmt * S)899 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
900 if (BuildOpts.AddScopes)
901 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
902 }
903
prependScopeBegin(CFGBlock * B,const VarDecl * VD,const Stmt * S)904 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
905 if (BuildOpts.AddScopes)
906 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
907 }
908
appendScopeEnd(CFGBlock * B,const VarDecl * VD,const Stmt * S)909 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
910 if (BuildOpts.AddScopes)
911 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
912 }
913
prependScopeEnd(CFGBlock * B,const VarDecl * VD,const Stmt * S)914 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
915 if (BuildOpts.AddScopes)
916 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
917 }
918
919 /// Find a relational comparison with an expression evaluating to a
920 /// boolean and a constant other than 0 and 1.
921 /// e.g. if ((x < y) == 10)
checkIncorrectRelationalOperator(const BinaryOperator * B)922 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
923 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
924 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
925
926 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
927 const Expr *BoolExpr = RHSExpr;
928 bool IntFirst = true;
929 if (!IntLiteral) {
930 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
931 BoolExpr = LHSExpr;
932 IntFirst = false;
933 }
934
935 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
936 return TryResult();
937
938 llvm::APInt IntValue = IntLiteral->getValue();
939 if ((IntValue == 1) || (IntValue == 0))
940 return TryResult();
941
942 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
943 !IntValue.isNegative();
944
945 BinaryOperatorKind Bok = B->getOpcode();
946 if (Bok == BO_GT || Bok == BO_GE) {
947 // Always true for 10 > bool and bool > -1
948 // Always false for -1 > bool and bool > 10
949 return TryResult(IntFirst == IntLarger);
950 } else {
951 // Always true for -1 < bool and bool < 10
952 // Always false for 10 < bool and bool < -1
953 return TryResult(IntFirst != IntLarger);
954 }
955 }
956
957 /// Find an incorrect equality comparison. Either with an expression
958 /// evaluating to a boolean and a constant other than 0 and 1.
959 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
960 /// true/false e.q. (x & 8) == 4.
checkIncorrectEqualityOperator(const BinaryOperator * B)961 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
962 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
963 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
964
965 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
966 const Expr *BoolExpr = RHSExpr;
967
968 if (!IntLiteral) {
969 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
970 BoolExpr = LHSExpr;
971 }
972
973 if (!IntLiteral)
974 return TryResult();
975
976 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
977 if (BitOp && (BitOp->getOpcode() == BO_And ||
978 BitOp->getOpcode() == BO_Or)) {
979 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
980 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
981
982 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
983
984 if (!IntLiteral2)
985 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
986
987 if (!IntLiteral2)
988 return TryResult();
989
990 llvm::APInt L1 = IntLiteral->getValue();
991 llvm::APInt L2 = IntLiteral2->getValue();
992 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
993 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
994 if (BuildOpts.Observer)
995 BuildOpts.Observer->compareBitwiseEquality(B,
996 B->getOpcode() != BO_EQ);
997 TryResult(B->getOpcode() != BO_EQ);
998 }
999 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
1000 llvm::APInt IntValue = IntLiteral->getValue();
1001 if ((IntValue == 1) || (IntValue == 0)) {
1002 return TryResult();
1003 }
1004 return TryResult(B->getOpcode() != BO_EQ);
1005 }
1006
1007 return TryResult();
1008 }
1009
analyzeLogicOperatorCondition(BinaryOperatorKind Relation,const llvm::APSInt & Value1,const llvm::APSInt & Value2)1010 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
1011 const llvm::APSInt &Value1,
1012 const llvm::APSInt &Value2) {
1013 assert(Value1.isSigned() == Value2.isSigned());
1014 switch (Relation) {
1015 default:
1016 return TryResult();
1017 case BO_EQ:
1018 return TryResult(Value1 == Value2);
1019 case BO_NE:
1020 return TryResult(Value1 != Value2);
1021 case BO_LT:
1022 return TryResult(Value1 < Value2);
1023 case BO_LE:
1024 return TryResult(Value1 <= Value2);
1025 case BO_GT:
1026 return TryResult(Value1 > Value2);
1027 case BO_GE:
1028 return TryResult(Value1 >= Value2);
1029 }
1030 }
1031
1032 /// Find a pair of comparison expressions with or without parentheses
1033 /// with a shared variable and constants and a logical operator between them
1034 /// that always evaluates to either true or false.
1035 /// e.g. if (x != 3 || x != 4)
checkIncorrectLogicOperator(const BinaryOperator * B)1036 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1037 assert(B->isLogicalOp());
1038 const BinaryOperator *LHS =
1039 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
1040 const BinaryOperator *RHS =
1041 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
1042 if (!LHS || !RHS)
1043 return {};
1044
1045 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
1046 return {};
1047
1048 const Expr *DeclExpr1;
1049 const Expr *NumExpr1;
1050 BinaryOperatorKind BO1;
1051 std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
1052
1053 if (!DeclExpr1 || !NumExpr1)
1054 return {};
1055
1056 const Expr *DeclExpr2;
1057 const Expr *NumExpr2;
1058 BinaryOperatorKind BO2;
1059 std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
1060
1061 if (!DeclExpr2 || !NumExpr2)
1062 return {};
1063
1064 // Check that it is the same variable on both sides.
1065 if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
1066 return {};
1067
1068 // Make sure the user's intent is clear (e.g. they're comparing against two
1069 // int literals, or two things from the same enum)
1070 if (!areExprTypesCompatible(NumExpr1, NumExpr2))
1071 return {};
1072
1073 Expr::EvalResult L1Result, L2Result;
1074 if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
1075 !NumExpr2->EvaluateAsInt(L2Result, *Context))
1076 return {};
1077
1078 llvm::APSInt L1 = L1Result.Val.getInt();
1079 llvm::APSInt L2 = L2Result.Val.getInt();
1080
1081 // Can't compare signed with unsigned or with different bit width.
1082 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
1083 return {};
1084
1085 // Values that will be used to determine if result of logical
1086 // operator is always true/false
1087 const llvm::APSInt Values[] = {
1088 // Value less than both Value1 and Value2
1089 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1090 // L1
1091 L1,
1092 // Value between Value1 and Value2
1093 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1094 L1.isUnsigned()),
1095 // L2
1096 L2,
1097 // Value greater than both Value1 and Value2
1098 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1099 };
1100
1101 // Check whether expression is always true/false by evaluating the following
1102 // * variable x is less than the smallest literal.
1103 // * variable x is equal to the smallest literal.
1104 // * Variable x is between smallest and largest literal.
1105 // * Variable x is equal to the largest literal.
1106 // * Variable x is greater than largest literal.
1107 bool AlwaysTrue = true, AlwaysFalse = true;
1108 // Track value of both subexpressions. If either side is always
1109 // true/false, another warning should have already been emitted.
1110 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
1111 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
1112 for (const llvm::APSInt &Value : Values) {
1113 TryResult Res1, Res2;
1114 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1115 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1116
1117 if (!Res1.isKnown() || !Res2.isKnown())
1118 return {};
1119
1120 if (B->getOpcode() == BO_LAnd) {
1121 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1122 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1123 } else {
1124 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1125 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1126 }
1127
1128 LHSAlwaysTrue &= Res1.isTrue();
1129 LHSAlwaysFalse &= Res1.isFalse();
1130 RHSAlwaysTrue &= Res2.isTrue();
1131 RHSAlwaysFalse &= Res2.isFalse();
1132 }
1133
1134 if (AlwaysTrue || AlwaysFalse) {
1135 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
1136 !RHSAlwaysFalse && BuildOpts.Observer)
1137 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1138 return TryResult(AlwaysTrue);
1139 }
1140 return {};
1141 }
1142
1143 /// A bitwise-or with a non-zero constant always evaluates to true.
checkIncorrectBitwiseOrOperator(const BinaryOperator * B)1144 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
1145 const Expr *LHSConstant =
1146 tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
1147 const Expr *RHSConstant =
1148 tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
1149
1150 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
1151 return {};
1152
1153 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
1154
1155 Expr::EvalResult Result;
1156 if (!Constant->EvaluateAsInt(Result, *Context))
1157 return {};
1158
1159 if (Result.Val.getInt() == 0)
1160 return {};
1161
1162 if (BuildOpts.Observer)
1163 BuildOpts.Observer->compareBitwiseOr(B);
1164
1165 return TryResult(true);
1166 }
1167
1168 /// Try and evaluate an expression to an integer constant.
tryEvaluate(Expr * S,Expr::EvalResult & outResult)1169 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1170 if (!BuildOpts.PruneTriviallyFalseEdges)
1171 return false;
1172 return !S->isTypeDependent() &&
1173 !S->isValueDependent() &&
1174 S->EvaluateAsRValue(outResult, *Context);
1175 }
1176
1177 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1178 /// if we can evaluate to a known value, otherwise return -1.
tryEvaluateBool(Expr * S)1179 TryResult tryEvaluateBool(Expr *S) {
1180 if (!BuildOpts.PruneTriviallyFalseEdges ||
1181 S->isTypeDependent() || S->isValueDependent())
1182 return {};
1183
1184 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1185 if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
1186 // Check the cache first.
1187 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1188 if (I != CachedBoolEvals.end())
1189 return I->second; // already in map;
1190
1191 // Retrieve result at first, or the map might be updated.
1192 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1193 CachedBoolEvals[S] = Result; // update or insert
1194 return Result;
1195 }
1196 else {
1197 switch (Bop->getOpcode()) {
1198 default: break;
1199 // For 'x & 0' and 'x * 0', we can determine that
1200 // the value is always false.
1201 case BO_Mul:
1202 case BO_And: {
1203 // If either operand is zero, we know the value
1204 // must be false.
1205 Expr::EvalResult LHSResult;
1206 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1207 llvm::APSInt IntVal = LHSResult.Val.getInt();
1208 if (!IntVal.getBoolValue()) {
1209 return TryResult(false);
1210 }
1211 }
1212 Expr::EvalResult RHSResult;
1213 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1214 llvm::APSInt IntVal = RHSResult.Val.getInt();
1215 if (!IntVal.getBoolValue()) {
1216 return TryResult(false);
1217 }
1218 }
1219 }
1220 break;
1221 }
1222 }
1223 }
1224
1225 return evaluateAsBooleanConditionNoCache(S);
1226 }
1227
1228 /// Evaluate as boolean \param E without using the cache.
evaluateAsBooleanConditionNoCache(Expr * E)1229 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1230 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1231 if (Bop->isLogicalOp()) {
1232 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1233 if (LHS.isKnown()) {
1234 // We were able to evaluate the LHS, see if we can get away with not
1235 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1236 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1237 return LHS.isTrue();
1238
1239 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1240 if (RHS.isKnown()) {
1241 if (Bop->getOpcode() == BO_LOr)
1242 return LHS.isTrue() || RHS.isTrue();
1243 else
1244 return LHS.isTrue() && RHS.isTrue();
1245 }
1246 } else {
1247 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1248 if (RHS.isKnown()) {
1249 // We can't evaluate the LHS; however, sometimes the result
1250 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1251 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1252 return RHS.isTrue();
1253 } else {
1254 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1255 if (BopRes.isKnown())
1256 return BopRes.isTrue();
1257 }
1258 }
1259
1260 return {};
1261 } else if (Bop->isEqualityOp()) {
1262 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1263 if (BopRes.isKnown())
1264 return BopRes.isTrue();
1265 } else if (Bop->isRelationalOp()) {
1266 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1267 if (BopRes.isKnown())
1268 return BopRes.isTrue();
1269 } else if (Bop->getOpcode() == BO_Or) {
1270 TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
1271 if (BopRes.isKnown())
1272 return BopRes.isTrue();
1273 }
1274 }
1275
1276 bool Result;
1277 if (E->EvaluateAsBooleanCondition(Result, *Context))
1278 return Result;
1279
1280 return {};
1281 }
1282
1283 bool hasTrivialDestructor(VarDecl *VD);
1284 };
1285
1286 } // namespace
1287
alwaysAdd(CFGBuilder & builder,const Stmt * stmt) const1288 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1289 const Stmt *stmt) const {
1290 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1291 }
1292
alwaysAdd(const Stmt * stmt)1293 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1294 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1295
1296 if (!BuildOpts.forcedBlkExprs)
1297 return shouldAdd;
1298
1299 if (lastLookup == stmt) {
1300 if (cachedEntry) {
1301 assert(cachedEntry->first == stmt);
1302 return true;
1303 }
1304 return shouldAdd;
1305 }
1306
1307 lastLookup = stmt;
1308
1309 // Perform the lookup!
1310 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1311
1312 if (!fb) {
1313 // No need to update 'cachedEntry', since it will always be null.
1314 assert(!cachedEntry);
1315 return shouldAdd;
1316 }
1317
1318 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1319 if (itr == fb->end()) {
1320 cachedEntry = nullptr;
1321 return shouldAdd;
1322 }
1323
1324 cachedEntry = &*itr;
1325 return true;
1326 }
1327
1328 // FIXME: Add support for dependent-sized array types in C++?
1329 // Does it even make sense to build a CFG for an uninstantiated template?
FindVA(const Type * t)1330 static const VariableArrayType *FindVA(const Type *t) {
1331 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1332 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1333 if (vat->getSizeExpr())
1334 return vat;
1335
1336 t = vt->getElementType().getTypePtr();
1337 }
1338
1339 return nullptr;
1340 }
1341
consumeConstructionContext(const ConstructionContextLayer * Layer,Expr * E)1342 void CFGBuilder::consumeConstructionContext(
1343 const ConstructionContextLayer *Layer, Expr *E) {
1344 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1345 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
1346 if (const ConstructionContextLayer *PreviouslyStoredLayer =
1347 ConstructionContextMap.lookup(E)) {
1348 (void)PreviouslyStoredLayer;
1349 // We might have visited this child when we were finding construction
1350 // contexts within its parents.
1351 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
1352 "Already within a different construction context!");
1353 } else {
1354 ConstructionContextMap[E] = Layer;
1355 }
1356 }
1357
findConstructionContexts(const ConstructionContextLayer * Layer,Stmt * Child)1358 void CFGBuilder::findConstructionContexts(
1359 const ConstructionContextLayer *Layer, Stmt *Child) {
1360 if (!BuildOpts.AddRichCXXConstructors)
1361 return;
1362
1363 if (!Child)
1364 return;
1365
1366 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1367 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1368 Layer);
1369 };
1370
1371 switch(Child->getStmtClass()) {
1372 case Stmt::CXXConstructExprClass:
1373 case Stmt::CXXTemporaryObjectExprClass: {
1374 // Support pre-C++17 copy elision AST.
1375 auto *CE = cast<CXXConstructExpr>(Child);
1376 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
1377 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1378 }
1379
1380 consumeConstructionContext(Layer, CE);
1381 break;
1382 }
1383 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1384 // FIXME: An isa<> would look much better but this whole switch is a
1385 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1386 case Stmt::CallExprClass:
1387 case Stmt::CXXMemberCallExprClass:
1388 case Stmt::CXXOperatorCallExprClass:
1389 case Stmt::UserDefinedLiteralClass:
1390 case Stmt::ObjCMessageExprClass: {
1391 auto *E = cast<Expr>(Child);
1392 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1393 consumeConstructionContext(Layer, E);
1394 break;
1395 }
1396 case Stmt::ExprWithCleanupsClass: {
1397 auto *Cleanups = cast<ExprWithCleanups>(Child);
1398 findConstructionContexts(Layer, Cleanups->getSubExpr());
1399 break;
1400 }
1401 case Stmt::CXXFunctionalCastExprClass: {
1402 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
1403 findConstructionContexts(Layer, Cast->getSubExpr());
1404 break;
1405 }
1406 case Stmt::ImplicitCastExprClass: {
1407 auto *Cast = cast<ImplicitCastExpr>(Child);
1408 // Should we support other implicit cast kinds?
1409 switch (Cast->getCastKind()) {
1410 case CK_NoOp:
1411 case CK_ConstructorConversion:
1412 findConstructionContexts(Layer, Cast->getSubExpr());
1413 break;
1414 default:
1415 break;
1416 }
1417 break;
1418 }
1419 case Stmt::CXXBindTemporaryExprClass: {
1420 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
1421 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1422 break;
1423 }
1424 case Stmt::MaterializeTemporaryExprClass: {
1425 // Normally we don't want to search in MaterializeTemporaryExpr because
1426 // it indicates the beginning of a temporary object construction context,
1427 // so it shouldn't be found in the middle. However, if it is the beginning
1428 // of an elidable copy or move construction context, we need to include it.
1429 if (Layer->getItem().getKind() ==
1430 ConstructionContextItem::ElidableConstructorKind) {
1431 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1432 findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
1433 }
1434 break;
1435 }
1436 case Stmt::ConditionalOperatorClass: {
1437 auto *CO = cast<ConditionalOperator>(Child);
1438 if (Layer->getItem().getKind() !=
1439 ConstructionContextItem::MaterializationKind) {
1440 // If the object returned by the conditional operator is not going to be a
1441 // temporary object that needs to be immediately materialized, then
1442 // it must be C++17 with its mandatory copy elision. Do not yet promise
1443 // to support this case.
1444 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1445 Context->getLangOpts().CPlusPlus17);
1446 break;
1447 }
1448 findConstructionContexts(Layer, CO->getLHS());
1449 findConstructionContexts(Layer, CO->getRHS());
1450 break;
1451 }
1452 case Stmt::InitListExprClass: {
1453 auto *ILE = cast<InitListExpr>(Child);
1454 if (ILE->isTransparent()) {
1455 findConstructionContexts(Layer, ILE->getInit(0));
1456 break;
1457 }
1458 // TODO: Handle other cases. For now, fail to find construction contexts.
1459 break;
1460 }
1461 default:
1462 break;
1463 }
1464 }
1465
cleanupConstructionContext(Expr * E)1466 void CFGBuilder::cleanupConstructionContext(Expr *E) {
1467 assert(BuildOpts.AddRichCXXConstructors &&
1468 "We should not be managing construction contexts!");
1469 assert(ConstructionContextMap.count(E) &&
1470 "Cannot exit construction context without the context!");
1471 ConstructionContextMap.erase(E);
1472 }
1473
1474
1475 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1476 /// arbitrary statement. Examples include a single expression or a function
1477 /// body (compound statement). The ownership of the returned CFG is
1478 /// transferred to the caller. If CFG construction fails, this method returns
1479 /// NULL.
buildCFG(const Decl * D,Stmt * Statement)1480 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1481 assert(cfg.get());
1482 if (!Statement)
1483 return nullptr;
1484
1485 // Create an empty block that will serve as the exit block for the CFG. Since
1486 // this is the first block added to the CFG, it will be implicitly registered
1487 // as the exit block.
1488 Succ = createBlock();
1489 assert(Succ == &cfg->getExit());
1490 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1491
1492 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1493 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1494
1495 if (BuildOpts.AddImplicitDtors)
1496 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1497 addImplicitDtorsForDestructor(DD);
1498
1499 // Visit the statements and create the CFG.
1500 CFGBlock *B = addStmt(Statement);
1501
1502 if (badCFG)
1503 return nullptr;
1504
1505 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1506 // are ignored unless the object is of the most derived class.
1507 // class VBase { VBase() = default; VBase(int) {} };
1508 // class A : virtual public VBase { A() : VBase(0) {} };
1509 // class B : public A {};
1510 // B b; // Constructor calls in order: VBase(), A(), B().
1511 // // VBase(0) is ignored because A isn't the most derived class.
1512 // This may result in the virtual base(s) being already initialized at this
1513 // point, in which case we should jump right onto non-virtual bases and
1514 // fields. To handle this, make a CFG branch. We only need to add one such
1515 // branch per constructor, since the Standard states that all virtual bases
1516 // shall be initialized before non-virtual bases and direct data members.
1517 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1518 CFGBlock *VBaseSucc = nullptr;
1519 for (auto *I : llvm::reverse(CD->inits())) {
1520 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1521 I->isBaseInitializer() && I->isBaseVirtual()) {
1522 // We've reached the first virtual base init while iterating in reverse
1523 // order. Make a new block for virtual base initializers so that we
1524 // could skip them.
1525 VBaseSucc = Succ = B ? B : &cfg->getExit();
1526 Block = createBlock();
1527 }
1528 B = addInitializer(I);
1529 if (badCFG)
1530 return nullptr;
1531 }
1532 if (VBaseSucc) {
1533 // Make a branch block for potentially skipping virtual base initializers.
1534 Succ = VBaseSucc;
1535 B = createBlock();
1536 B->setTerminator(
1537 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1538 addSuccessor(B, Block, true);
1539 }
1540 }
1541
1542 if (B)
1543 Succ = B;
1544
1545 // Backpatch the gotos whose label -> block mappings we didn't know when we
1546 // encountered them.
1547 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1548 E = BackpatchBlocks.end(); I != E; ++I ) {
1549
1550 CFGBlock *B = I->block;
1551 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1552 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1553 // If there is no target for the goto, then we are looking at an
1554 // incomplete AST. Handle this by not registering a successor.
1555 if (LI == LabelMap.end())
1556 continue;
1557 JumpTarget JT = LI->second;
1558 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1559 JT.scopePosition);
1560 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1561 JT.scopePosition);
1562 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
1563 B, I->scopePosition, JT.scopePosition);
1564 appendScopeBegin(JT.block, VD, G);
1565 addSuccessor(B, JT.block);
1566 };
1567 if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1568 CFGBlock *Successor = (I+1)->block;
1569 for (auto *L : G->labels()) {
1570 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1571 // If there is no target for the goto, then we are looking at an
1572 // incomplete AST. Handle this by not registering a successor.
1573 if (LI == LabelMap.end())
1574 continue;
1575 JumpTarget JT = LI->second;
1576 // Successor has been added, so skip it.
1577 if (JT.block == Successor)
1578 continue;
1579 addSuccessor(B, JT.block);
1580 }
1581 I++;
1582 }
1583 }
1584
1585 // Add successors to the Indirect Goto Dispatch block (if we have one).
1586 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1587 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1588 E = AddressTakenLabels.end(); I != E; ++I ) {
1589 // Lookup the target block.
1590 LabelMapTy::iterator LI = LabelMap.find(*I);
1591
1592 // If there is no target block that contains label, then we are looking
1593 // at an incomplete AST. Handle this by not registering a successor.
1594 if (LI == LabelMap.end()) continue;
1595
1596 addSuccessor(B, LI->second.block);
1597 }
1598
1599 // Create an empty entry block that has no predecessors.
1600 cfg->setEntry(createBlock());
1601
1602 if (BuildOpts.AddRichCXXConstructors)
1603 assert(ConstructionContextMap.empty() &&
1604 "Not all construction contexts were cleaned up!");
1605
1606 return std::move(cfg);
1607 }
1608
1609 /// createBlock - Used to lazily create blocks that are connected
1610 /// to the current (global) succcessor.
createBlock(bool add_successor)1611 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1612 CFGBlock *B = cfg->createBlock();
1613 if (add_successor && Succ)
1614 addSuccessor(B, Succ);
1615 return B;
1616 }
1617
1618 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1619 /// CFG. It is *not* connected to the current (global) successor, and instead
1620 /// directly tied to the exit block in order to be reachable.
createNoReturnBlock()1621 CFGBlock *CFGBuilder::createNoReturnBlock() {
1622 CFGBlock *B = createBlock(false);
1623 B->setHasNoReturnElement();
1624 addSuccessor(B, &cfg->getExit(), Succ);
1625 return B;
1626 }
1627
1628 /// addInitializer - Add C++ base or member initializer element to CFG.
addInitializer(CXXCtorInitializer * I)1629 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1630 if (!BuildOpts.AddInitializers)
1631 return Block;
1632
1633 bool HasTemporaries = false;
1634
1635 // Destructors of temporaries in initialization expression should be called
1636 // after initialization finishes.
1637 Expr *Init = I->getInit();
1638 if (Init) {
1639 HasTemporaries = isa<ExprWithCleanups>(Init);
1640
1641 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1642 // Generate destructors for temporaries in initialization expression.
1643 TempDtorContext Context;
1644 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1645 /*ExternallyDestructed=*/false, Context);
1646 }
1647 }
1648
1649 autoCreateBlock();
1650 appendInitializer(Block, I);
1651
1652 if (Init) {
1653 findConstructionContexts(
1654 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
1655 Init);
1656
1657 if (HasTemporaries) {
1658 // For expression with temporaries go directly to subexpression to omit
1659 // generating destructors for the second time.
1660 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1661 }
1662 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1663 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1664 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1665 // may cause the same Expr to appear more than once in the CFG. Doing it
1666 // here is safe because there's only one initializer per field.
1667 autoCreateBlock();
1668 appendStmt(Block, Default);
1669 if (Stmt *Child = Default->getExpr())
1670 if (CFGBlock *R = Visit(Child))
1671 Block = R;
1672 return Block;
1673 }
1674 }
1675 return Visit(Init);
1676 }
1677
1678 return Block;
1679 }
1680
1681 /// Retrieve the type of the temporary object whose lifetime was
1682 /// extended by a local reference with the given initializer.
getReferenceInitTemporaryType(const Expr * Init,bool * FoundMTE=nullptr)1683 static QualType getReferenceInitTemporaryType(const Expr *Init,
1684 bool *FoundMTE = nullptr) {
1685 while (true) {
1686 // Skip parentheses.
1687 Init = Init->IgnoreParens();
1688
1689 // Skip through cleanups.
1690 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1691 Init = EWC->getSubExpr();
1692 continue;
1693 }
1694
1695 // Skip through the temporary-materialization expression.
1696 if (const MaterializeTemporaryExpr *MTE
1697 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1698 Init = MTE->getSubExpr();
1699 if (FoundMTE)
1700 *FoundMTE = true;
1701 continue;
1702 }
1703
1704 // Skip sub-object accesses into rvalues.
1705 SmallVector<const Expr *, 2> CommaLHSs;
1706 SmallVector<SubobjectAdjustment, 2> Adjustments;
1707 const Expr *SkippedInit =
1708 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1709 if (SkippedInit != Init) {
1710 Init = SkippedInit;
1711 continue;
1712 }
1713
1714 break;
1715 }
1716
1717 return Init->getType();
1718 }
1719
1720 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1721 // ended by ReturnStmt, GotoStmt or ThrowExpr.
addLoopExit(const Stmt * LoopStmt)1722 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1723 if(!BuildOpts.AddLoopExit)
1724 return;
1725 autoCreateBlock();
1726 appendLoopExit(Block, LoopStmt);
1727 }
1728
getDeclsWithEndedScope(LocalScope::const_iterator B,LocalScope::const_iterator E,Stmt * S)1729 void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
1730 LocalScope::const_iterator E, Stmt *S) {
1731 if (!BuildOpts.AddScopes)
1732 return;
1733
1734 if (B == E)
1735 return;
1736
1737 // To go from B to E, one first goes up the scopes from B to P
1738 // then sideways in one scope from P to P' and then down
1739 // the scopes from P' to E.
1740 // The lifetime of all objects between B and P end.
1741 LocalScope::const_iterator P = B.shared_parent(E);
1742 int Dist = B.distance(P);
1743 if (Dist <= 0)
1744 return;
1745
1746 for (LocalScope::const_iterator I = B; I != P; ++I)
1747 if (I.pointsToFirstDeclaredVar())
1748 DeclsWithEndedScope.insert(*I);
1749 }
1750
addAutomaticObjHandling(LocalScope::const_iterator B,LocalScope::const_iterator E,Stmt * S)1751 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1752 LocalScope::const_iterator E,
1753 Stmt *S) {
1754 getDeclsWithEndedScope(B, E, S);
1755 if (BuildOpts.AddScopes)
1756 addScopesEnd(B, E, S);
1757 if (BuildOpts.AddImplicitDtors)
1758 addAutomaticObjDtors(B, E, S);
1759 if (BuildOpts.AddLifetime)
1760 addLifetimeEnds(B, E, S);
1761 }
1762
1763 /// Add to current block automatic objects that leave the scope.
addLifetimeEnds(LocalScope::const_iterator B,LocalScope::const_iterator E,Stmt * S)1764 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1765 LocalScope::const_iterator E, Stmt *S) {
1766 if (!BuildOpts.AddLifetime)
1767 return;
1768
1769 if (B == E)
1770 return;
1771
1772 // To go from B to E, one first goes up the scopes from B to P
1773 // then sideways in one scope from P to P' and then down
1774 // the scopes from P' to E.
1775 // The lifetime of all objects between B and P end.
1776 LocalScope::const_iterator P = B.shared_parent(E);
1777 int dist = B.distance(P);
1778 if (dist <= 0)
1779 return;
1780
1781 // We need to perform the scope leaving in reverse order
1782 SmallVector<VarDecl *, 10> DeclsTrivial;
1783 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1784 DeclsTrivial.reserve(dist);
1785 DeclsNonTrivial.reserve(dist);
1786
1787 for (LocalScope::const_iterator I = B; I != P; ++I)
1788 if (hasTrivialDestructor(*I))
1789 DeclsTrivial.push_back(*I);
1790 else
1791 DeclsNonTrivial.push_back(*I);
1792
1793 autoCreateBlock();
1794 // object with trivial destructor end their lifetime last (when storage
1795 // duration ends)
1796 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1797 E = DeclsTrivial.rend();
1798 I != E; ++I)
1799 appendLifetimeEnds(Block, *I, S);
1800
1801 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1802 I = DeclsNonTrivial.rbegin(),
1803 E = DeclsNonTrivial.rend();
1804 I != E; ++I)
1805 appendLifetimeEnds(Block, *I, S);
1806 }
1807
1808 /// Add to current block markers for ending scopes.
addScopesEnd(LocalScope::const_iterator B,LocalScope::const_iterator E,Stmt * S)1809 void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
1810 LocalScope::const_iterator E, Stmt *S) {
1811 // If implicit destructors are enabled, we'll add scope ends in
1812 // addAutomaticObjDtors.
1813 if (BuildOpts.AddImplicitDtors)
1814 return;
1815
1816 autoCreateBlock();
1817
1818 for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
1819 I != E; ++I)
1820 appendScopeEnd(Block, *I, S);
1821
1822 return;
1823 }
1824
1825 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1826 /// for objects in range of local scope positions. Use S as trigger statement
1827 /// for destructors.
addAutomaticObjDtors(LocalScope::const_iterator B,LocalScope::const_iterator E,Stmt * S)1828 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1829 LocalScope::const_iterator E, Stmt *S) {
1830 if (!BuildOpts.AddImplicitDtors)
1831 return;
1832
1833 if (B == E)
1834 return;
1835
1836 // We need to append the destructors in reverse order, but any one of them
1837 // may be a no-return destructor which changes the CFG. As a result, buffer
1838 // this sequence up and replay them in reverse order when appending onto the
1839 // CFGBlock(s).
1840 SmallVector<VarDecl*, 10> Decls;
1841 Decls.reserve(B.distance(E));
1842 for (LocalScope::const_iterator I = B; I != E; ++I)
1843 Decls.push_back(*I);
1844
1845 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1846 E = Decls.rend();
1847 I != E; ++I) {
1848 if (hasTrivialDestructor(*I)) {
1849 // If AddScopes is enabled and *I is a first variable in a scope, add a
1850 // ScopeEnd marker in a Block.
1851 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
1852 autoCreateBlock();
1853 appendScopeEnd(Block, *I, S);
1854 }
1855 continue;
1856 }
1857 // If this destructor is marked as a no-return destructor, we need to
1858 // create a new block for the destructor which does not have as a successor
1859 // anything built thus far: control won't flow out of this block.
1860 QualType Ty = (*I)->getType();
1861 if (Ty->isReferenceType()) {
1862 Ty = getReferenceInitTemporaryType((*I)->getInit());
1863 }
1864 Ty = Context->getBaseElementType(Ty);
1865
1866 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1867 Block = createNoReturnBlock();
1868 else
1869 autoCreateBlock();
1870
1871 // Add ScopeEnd just after automatic obj destructor.
1872 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
1873 appendScopeEnd(Block, *I, S);
1874 appendAutomaticObjDtor(Block, *I, S);
1875 }
1876 }
1877
1878 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1879 /// base and member objects in destructor.
addImplicitDtorsForDestructor(const CXXDestructorDecl * DD)1880 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1881 assert(BuildOpts.AddImplicitDtors &&
1882 "Can be called only when dtors should be added");
1883 const CXXRecordDecl *RD = DD->getParent();
1884
1885 // At the end destroy virtual base objects.
1886 for (const auto &VI : RD->vbases()) {
1887 // TODO: Add a VirtualBaseBranch to see if the most derived class
1888 // (which is different from the current class) is responsible for
1889 // destroying them.
1890 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1891 if (!CD->hasTrivialDestructor()) {
1892 autoCreateBlock();
1893 appendBaseDtor(Block, &VI);
1894 }
1895 }
1896
1897 // Before virtual bases destroy direct base objects.
1898 for (const auto &BI : RD->bases()) {
1899 if (!BI.isVirtual()) {
1900 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1901 if (!CD->hasTrivialDestructor()) {
1902 autoCreateBlock();
1903 appendBaseDtor(Block, &BI);
1904 }
1905 }
1906 }
1907
1908 // First destroy member objects.
1909 for (auto *FI : RD->fields()) {
1910 // Check for constant size array. Set type to array element type.
1911 QualType QT = FI->getType();
1912 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1913 if (AT->getSize() == 0)
1914 continue;
1915 QT = AT->getElementType();
1916 }
1917
1918 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1919 if (!CD->hasTrivialDestructor()) {
1920 autoCreateBlock();
1921 appendMemberDtor(Block, FI);
1922 }
1923 }
1924 }
1925
1926 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1927 /// way return valid LocalScope object.
createOrReuseLocalScope(LocalScope * Scope)1928 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1929 if (Scope)
1930 return Scope;
1931 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1932 return new (alloc.Allocate<LocalScope>())
1933 LocalScope(BumpVectorContext(alloc), ScopePos);
1934 }
1935
1936 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1937 /// that should create implicit scope (e.g. if/else substatements).
addLocalScopeForStmt(Stmt * S)1938 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1939 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1940 !BuildOpts.AddScopes)
1941 return;
1942
1943 LocalScope *Scope = nullptr;
1944
1945 // For compound statement we will be creating explicit scope.
1946 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1947 for (auto *BI : CS->body()) {
1948 Stmt *SI = BI->stripLabelLikeStatements();
1949 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1950 Scope = addLocalScopeForDeclStmt(DS, Scope);
1951 }
1952 return;
1953 }
1954
1955 // For any other statement scope will be implicit and as such will be
1956 // interesting only for DeclStmt.
1957 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1958 addLocalScopeForDeclStmt(DS);
1959 }
1960
1961 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1962 /// reuse Scope if not NULL.
addLocalScopeForDeclStmt(DeclStmt * DS,LocalScope * Scope)1963 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1964 LocalScope* Scope) {
1965 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1966 !BuildOpts.AddScopes)
1967 return Scope;
1968
1969 for (auto *DI : DS->decls())
1970 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1971 Scope = addLocalScopeForVarDecl(VD, Scope);
1972 return Scope;
1973 }
1974
hasTrivialDestructor(VarDecl * VD)1975 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1976 // Check for const references bound to temporary. Set type to pointee.
1977 QualType QT = VD->getType();
1978 if (QT->isReferenceType()) {
1979 // Attempt to determine whether this declaration lifetime-extends a
1980 // temporary.
1981 //
1982 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1983 // temporaries, and a single declaration can extend multiple temporaries.
1984 // We should look at the storage duration on each nested
1985 // MaterializeTemporaryExpr instead.
1986
1987 const Expr *Init = VD->getInit();
1988 if (!Init) {
1989 // Probably an exception catch-by-reference variable.
1990 // FIXME: It doesn't really mean that the object has a trivial destructor.
1991 // Also are there other cases?
1992 return true;
1993 }
1994
1995 // Lifetime-extending a temporary?
1996 bool FoundMTE = false;
1997 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
1998 if (!FoundMTE)
1999 return true;
2000 }
2001
2002 // Check for constant size array. Set type to array element type.
2003 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2004 if (AT->getSize() == 0)
2005 return true;
2006 QT = AT->getElementType();
2007 }
2008
2009 // Check if type is a C++ class with non-trivial destructor.
2010 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2011 return !CD->hasDefinition() || CD->hasTrivialDestructor();
2012 return true;
2013 }
2014
2015 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2016 /// create add scope for automatic objects and temporary objects bound to
2017 /// const reference. Will reuse Scope if not NULL.
addLocalScopeForVarDecl(VarDecl * VD,LocalScope * Scope)2018 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
2019 LocalScope* Scope) {
2020 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
2021 "AddImplicitDtors and AddLifetime cannot be used at the same time");
2022 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2023 !BuildOpts.AddScopes)
2024 return Scope;
2025
2026 // Check if variable is local.
2027 switch (VD->getStorageClass()) {
2028 case SC_None:
2029 case SC_Auto:
2030 case SC_Register:
2031 break;
2032 default: return Scope;
2033 }
2034
2035 if (BuildOpts.AddImplicitDtors) {
2036 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
2037 // Add the variable to scope
2038 Scope = createOrReuseLocalScope(Scope);
2039 Scope->addVar(VD);
2040 ScopePos = Scope->begin();
2041 }
2042 return Scope;
2043 }
2044
2045 assert(BuildOpts.AddLifetime);
2046 // Add the variable to scope
2047 Scope = createOrReuseLocalScope(Scope);
2048 Scope->addVar(VD);
2049 ScopePos = Scope->begin();
2050 return Scope;
2051 }
2052
2053 /// addLocalScopeAndDtors - For given statement add local scope for it and
2054 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
addLocalScopeAndDtors(Stmt * S)2055 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
2056 LocalScope::const_iterator scopeBeginPos = ScopePos;
2057 addLocalScopeForStmt(S);
2058 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
2059 }
2060
2061 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
2062 /// variables with automatic storage duration to CFGBlock's elements vector.
2063 /// Elements will be prepended to physical beginning of the vector which
2064 /// happens to be logical end. Use blocks terminator as statement that specifies
2065 /// destructors call site.
2066 /// FIXME: This mechanism for adding automatic destructors doesn't handle
2067 /// no-return destructors properly.
prependAutomaticObjDtorsWithTerminator(CFGBlock * Blk,LocalScope::const_iterator B,LocalScope::const_iterator E)2068 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
2069 LocalScope::const_iterator B, LocalScope::const_iterator E) {
2070 if (!BuildOpts.AddImplicitDtors)
2071 return;
2072 BumpVectorContext &C = cfg->getBumpVectorContext();
2073 CFGBlock::iterator InsertPos
2074 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
2075 for (LocalScope::const_iterator I = B; I != E; ++I)
2076 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
2077 Blk->getTerminatorStmt());
2078 }
2079
2080 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
2081 /// variables with automatic storage duration to CFGBlock's elements vector.
2082 /// Elements will be prepended to physical beginning of the vector which
2083 /// happens to be logical end. Use blocks terminator as statement that specifies
2084 /// where lifetime ends.
prependAutomaticObjLifetimeWithTerminator(CFGBlock * Blk,LocalScope::const_iterator B,LocalScope::const_iterator E)2085 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
2086 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2087 if (!BuildOpts.AddLifetime)
2088 return;
2089 BumpVectorContext &C = cfg->getBumpVectorContext();
2090 CFGBlock::iterator InsertPos =
2091 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
2092 for (LocalScope::const_iterator I = B; I != E; ++I) {
2093 InsertPos =
2094 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
2095 }
2096 }
2097
2098 /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
2099 /// variables with automatic storage duration to CFGBlock's elements vector.
2100 /// Elements will be prepended to physical beginning of the vector which
2101 /// happens to be logical end. Use blocks terminator as statement that specifies
2102 /// where scope ends.
2103 const VarDecl *
prependAutomaticObjScopeEndWithTerminator(CFGBlock * Blk,LocalScope::const_iterator B,LocalScope::const_iterator E)2104 CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
2105 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2106 if (!BuildOpts.AddScopes)
2107 return nullptr;
2108 BumpVectorContext &C = cfg->getBumpVectorContext();
2109 CFGBlock::iterator InsertPos =
2110 Blk->beginScopeEndInsert(Blk->end(), 1, C);
2111 LocalScope::const_iterator PlaceToInsert = B;
2112 for (LocalScope::const_iterator I = B; I != E; ++I)
2113 PlaceToInsert = I;
2114 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
2115 return *PlaceToInsert;
2116 }
2117
2118 /// Visit - Walk the subtree of a statement and add extra
2119 /// blocks for ternary operators, &&, and ||. We also process "," and
2120 /// DeclStmts (which may contain nested control-flow).
Visit(Stmt * S,AddStmtChoice asc,bool ExternallyDestructed)2121 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
2122 bool ExternallyDestructed) {
2123 if (!S) {
2124 badCFG = true;
2125 return nullptr;
2126 }
2127
2128 if (Expr *E = dyn_cast<Expr>(S))
2129 S = E->IgnoreParens();
2130
2131 if (Context->getLangOpts().OpenMP)
2132 if (auto *D = dyn_cast<OMPExecutableDirective>(S))
2133 return VisitOMPExecutableDirective(D, asc);
2134
2135 switch (S->getStmtClass()) {
2136 default:
2137 return VisitStmt(S, asc);
2138
2139 case Stmt::ImplicitValueInitExprClass:
2140 if (BuildOpts.OmitImplicitValueInitializers)
2141 return Block;
2142 return VisitStmt(S, asc);
2143
2144 case Stmt::InitListExprClass:
2145 return VisitInitListExpr(cast<InitListExpr>(S), asc);
2146
2147 case Stmt::AddrLabelExprClass:
2148 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
2149
2150 case Stmt::BinaryConditionalOperatorClass:
2151 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2152
2153 case Stmt::BinaryOperatorClass:
2154 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
2155
2156 case Stmt::BlockExprClass:
2157 return VisitBlockExpr(cast<BlockExpr>(S), asc);
2158
2159 case Stmt::BreakStmtClass:
2160 return VisitBreakStmt(cast<BreakStmt>(S));
2161
2162 case Stmt::CallExprClass:
2163 case Stmt::CXXOperatorCallExprClass:
2164 case Stmt::CXXMemberCallExprClass:
2165 case Stmt::UserDefinedLiteralClass:
2166 return VisitCallExpr(cast<CallExpr>(S), asc);
2167
2168 case Stmt::CaseStmtClass:
2169 return VisitCaseStmt(cast<CaseStmt>(S));
2170
2171 case Stmt::ChooseExprClass:
2172 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
2173
2174 case Stmt::CompoundStmtClass:
2175 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
2176
2177 case Stmt::ConditionalOperatorClass:
2178 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
2179
2180 case Stmt::ContinueStmtClass:
2181 return VisitContinueStmt(cast<ContinueStmt>(S));
2182
2183 case Stmt::CXXCatchStmtClass:
2184 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2185
2186 case Stmt::ExprWithCleanupsClass:
2187 return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
2188 asc, ExternallyDestructed);
2189
2190 case Stmt::CXXDefaultArgExprClass:
2191 case Stmt::CXXDefaultInitExprClass:
2192 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2193 // called function's declaration, not by the caller. If we simply add
2194 // this expression to the CFG, we could end up with the same Expr
2195 // appearing multiple times.
2196 // PR13385 / <rdar://problem/12156507>
2197 //
2198 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2199 // expression to be used in the same function (through aggregate
2200 // initialization).
2201 return VisitStmt(S, asc);
2202
2203 case Stmt::CXXBindTemporaryExprClass:
2204 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2205
2206 case Stmt::CXXConstructExprClass:
2207 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2208
2209 case Stmt::CXXNewExprClass:
2210 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2211
2212 case Stmt::CXXDeleteExprClass:
2213 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2214
2215 case Stmt::CXXFunctionalCastExprClass:
2216 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2217
2218 case Stmt::CXXTemporaryObjectExprClass:
2219 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2220
2221 case Stmt::CXXThrowExprClass:
2222 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
2223
2224 case Stmt::CXXTryStmtClass:
2225 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
2226
2227 case Stmt::CXXForRangeStmtClass:
2228 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2229
2230 case Stmt::DeclStmtClass:
2231 return VisitDeclStmt(cast<DeclStmt>(S));
2232
2233 case Stmt::DefaultStmtClass:
2234 return VisitDefaultStmt(cast<DefaultStmt>(S));
2235
2236 case Stmt::DoStmtClass:
2237 return VisitDoStmt(cast<DoStmt>(S));
2238
2239 case Stmt::ForStmtClass:
2240 return VisitForStmt(cast<ForStmt>(S));
2241
2242 case Stmt::GotoStmtClass:
2243 return VisitGotoStmt(cast<GotoStmt>(S));
2244
2245 case Stmt::GCCAsmStmtClass:
2246 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2247
2248 case Stmt::IfStmtClass:
2249 return VisitIfStmt(cast<IfStmt>(S));
2250
2251 case Stmt::ImplicitCastExprClass:
2252 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
2253
2254 case Stmt::ConstantExprClass:
2255 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2256
2257 case Stmt::IndirectGotoStmtClass:
2258 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
2259
2260 case Stmt::LabelStmtClass:
2261 return VisitLabelStmt(cast<LabelStmt>(S));
2262
2263 case Stmt::LambdaExprClass:
2264 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2265
2266 case Stmt::MaterializeTemporaryExprClass:
2267 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2268 asc);
2269
2270 case Stmt::MemberExprClass:
2271 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2272
2273 case Stmt::NullStmtClass:
2274 return Block;
2275
2276 case Stmt::ObjCAtCatchStmtClass:
2277 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2278
2279 case Stmt::ObjCAutoreleasePoolStmtClass:
2280 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2281
2282 case Stmt::ObjCAtSynchronizedStmtClass:
2283 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
2284
2285 case Stmt::ObjCAtThrowStmtClass:
2286 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
2287
2288 case Stmt::ObjCAtTryStmtClass:
2289 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
2290
2291 case Stmt::ObjCForCollectionStmtClass:
2292 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
2293
2294 case Stmt::ObjCMessageExprClass:
2295 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2296
2297 case Stmt::OpaqueValueExprClass:
2298 return Block;
2299
2300 case Stmt::PseudoObjectExprClass:
2301 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2302
2303 case Stmt::ReturnStmtClass:
2304 case Stmt::CoreturnStmtClass:
2305 return VisitReturnStmt(S);
2306
2307 case Stmt::SEHExceptStmtClass:
2308 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2309
2310 case Stmt::SEHFinallyStmtClass:
2311 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2312
2313 case Stmt::SEHLeaveStmtClass:
2314 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2315
2316 case Stmt::SEHTryStmtClass:
2317 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2318
2319 case Stmt::UnaryExprOrTypeTraitExprClass:
2320 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2321 asc);
2322
2323 case Stmt::StmtExprClass:
2324 return VisitStmtExpr(cast<StmtExpr>(S), asc);
2325
2326 case Stmt::SwitchStmtClass:
2327 return VisitSwitchStmt(cast<SwitchStmt>(S));
2328
2329 case Stmt::UnaryOperatorClass:
2330 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2331
2332 case Stmt::WhileStmtClass:
2333 return VisitWhileStmt(cast<WhileStmt>(S));
2334 }
2335 }
2336
VisitStmt(Stmt * S,AddStmtChoice asc)2337 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
2338 if (asc.alwaysAdd(*this, S)) {
2339 autoCreateBlock();
2340 appendStmt(Block, S);
2341 }
2342
2343 return VisitChildren(S);
2344 }
2345
2346 /// VisitChildren - Visit the children of a Stmt.
VisitChildren(Stmt * S)2347 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2348 CFGBlock *B = Block;
2349
2350 // Visit the children in their reverse order so that they appear in
2351 // left-to-right (natural) order in the CFG.
2352 reverse_children RChildren(S);
2353 for (Stmt *Child : RChildren) {
2354 if (Child)
2355 if (CFGBlock *R = Visit(Child))
2356 B = R;
2357 }
2358 return B;
2359 }
2360
VisitInitListExpr(InitListExpr * ILE,AddStmtChoice asc)2361 CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
2362 if (asc.alwaysAdd(*this, ILE)) {
2363 autoCreateBlock();
2364 appendStmt(Block, ILE);
2365 }
2366 CFGBlock *B = Block;
2367
2368 reverse_children RChildren(ILE);
2369 for (Stmt *Child : RChildren) {
2370 if (!Child)
2371 continue;
2372 if (CFGBlock *R = Visit(Child))
2373 B = R;
2374 if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
2375 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
2376 if (Stmt *Child = DIE->getExpr())
2377 if (CFGBlock *R = Visit(Child))
2378 B = R;
2379 }
2380 }
2381 return B;
2382 }
2383
VisitAddrLabelExpr(AddrLabelExpr * A,AddStmtChoice asc)2384 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2385 AddStmtChoice asc) {
2386 AddressTakenLabels.insert(A->getLabel());
2387
2388 if (asc.alwaysAdd(*this, A)) {
2389 autoCreateBlock();
2390 appendStmt(Block, A);
2391 }
2392
2393 return Block;
2394 }
2395
VisitUnaryOperator(UnaryOperator * U,AddStmtChoice asc)2396 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
2397 AddStmtChoice asc) {
2398 if (asc.alwaysAdd(*this, U)) {
2399 autoCreateBlock();
2400 appendStmt(Block, U);
2401 }
2402
2403 if (U->getOpcode() == UO_LNot)
2404 tryEvaluateBool(U->getSubExpr()->IgnoreParens());
2405
2406 return Visit(U->getSubExpr(), AddStmtChoice());
2407 }
2408
VisitLogicalOperator(BinaryOperator * B)2409 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2410 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2411 appendStmt(ConfluenceBlock, B);
2412
2413 if (badCFG)
2414 return nullptr;
2415
2416 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2417 ConfluenceBlock).first;
2418 }
2419
2420 std::pair<CFGBlock*, CFGBlock*>
VisitLogicalOperator(BinaryOperator * B,Stmt * Term,CFGBlock * TrueBlock,CFGBlock * FalseBlock)2421 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2422 Stmt *Term,
2423 CFGBlock *TrueBlock,
2424 CFGBlock *FalseBlock) {
2425 // Introspect the RHS. If it is a nested logical operation, we recursively
2426 // build the CFG using this function. Otherwise, resort to default
2427 // CFG construction behavior.
2428 Expr *RHS = B->getRHS()->IgnoreParens();
2429 CFGBlock *RHSBlock, *ExitBlock;
2430
2431 do {
2432 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2433 if (B_RHS->isLogicalOp()) {
2434 std::tie(RHSBlock, ExitBlock) =
2435 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2436 break;
2437 }
2438
2439 // The RHS is not a nested logical operation. Don't push the terminator
2440 // down further, but instead visit RHS and construct the respective
2441 // pieces of the CFG, and link up the RHSBlock with the terminator
2442 // we have been provided.
2443 ExitBlock = RHSBlock = createBlock(false);
2444
2445 // Even though KnownVal is only used in the else branch of the next
2446 // conditional, tryEvaluateBool performs additional checking on the
2447 // Expr, so it should be called unconditionally.
2448 TryResult KnownVal = tryEvaluateBool(RHS);
2449 if (!KnownVal.isKnown())
2450 KnownVal = tryEvaluateBool(B);
2451
2452 if (!Term) {
2453 assert(TrueBlock == FalseBlock);
2454 addSuccessor(RHSBlock, TrueBlock);
2455 }
2456 else {
2457 RHSBlock->setTerminator(Term);
2458 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2459 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
2460 }
2461
2462 Block = RHSBlock;
2463 RHSBlock = addStmt(RHS);
2464 }
2465 while (false);
2466
2467 if (badCFG)
2468 return std::make_pair(nullptr, nullptr);
2469
2470 // Generate the blocks for evaluating the LHS.
2471 Expr *LHS = B->getLHS()->IgnoreParens();
2472
2473 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2474 if (B_LHS->isLogicalOp()) {
2475 if (B->getOpcode() == BO_LOr)
2476 FalseBlock = RHSBlock;
2477 else
2478 TrueBlock = RHSBlock;
2479
2480 // For the LHS, treat 'B' as the terminator that we want to sink
2481 // into the nested branch. The RHS always gets the top-most
2482 // terminator.
2483 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2484 }
2485
2486 // Create the block evaluating the LHS.
2487 // This contains the '&&' or '||' as the terminator.
2488 CFGBlock *LHSBlock = createBlock(false);
2489 LHSBlock->setTerminator(B);
2490
2491 Block = LHSBlock;
2492 CFGBlock *EntryLHSBlock = addStmt(LHS);
2493
2494 if (badCFG)
2495 return std::make_pair(nullptr, nullptr);
2496
2497 // See if this is a known constant.
2498 TryResult KnownVal = tryEvaluateBool(LHS);
2499
2500 // Now link the LHSBlock with RHSBlock.
2501 if (B->getOpcode() == BO_LOr) {
2502 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2503 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
2504 } else {
2505 assert(B->getOpcode() == BO_LAnd);
2506 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2507 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
2508 }
2509
2510 return std::make_pair(EntryLHSBlock, ExitBlock);
2511 }
2512
VisitBinaryOperator(BinaryOperator * B,AddStmtChoice asc)2513 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2514 AddStmtChoice asc) {
2515 // && or ||
2516 if (B->isLogicalOp())
2517 return VisitLogicalOperator(B);
2518
2519 if (B->getOpcode() == BO_Comma) { // ,
2520 autoCreateBlock();
2521 appendStmt(Block, B);
2522 addStmt(B->getRHS());
2523 return addStmt(B->getLHS());
2524 }
2525
2526 if (B->isAssignmentOp()) {
2527 if (asc.alwaysAdd(*this, B)) {
2528 autoCreateBlock();
2529 appendStmt(Block, B);
2530 }
2531 Visit(B->getLHS());
2532 return Visit(B->getRHS());
2533 }
2534
2535 if (asc.alwaysAdd(*this, B)) {
2536 autoCreateBlock();
2537 appendStmt(Block, B);
2538 }
2539
2540 if (B->isEqualityOp() || B->isRelationalOp())
2541 tryEvaluateBool(B);
2542
2543 CFGBlock *RBlock = Visit(B->getRHS());
2544 CFGBlock *LBlock = Visit(B->getLHS());
2545 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2546 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2547 // return RBlock. Otherwise we'll incorrectly return NULL.
2548 return (LBlock ? LBlock : RBlock);
2549 }
2550
VisitNoRecurse(Expr * E,AddStmtChoice asc)2551 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2552 if (asc.alwaysAdd(*this, E)) {
2553 autoCreateBlock();
2554 appendStmt(Block, E);
2555 }
2556 return Block;
2557 }
2558
VisitBreakStmt(BreakStmt * B)2559 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2560 // "break" is a control-flow statement. Thus we stop processing the current
2561 // block.
2562 if (badCFG)
2563 return nullptr;
2564
2565 // Now create a new block that ends with the break statement.
2566 Block = createBlock(false);
2567 Block->setTerminator(B);
2568
2569 // If there is no target for the break, then we are looking at an incomplete
2570 // AST. This means that the CFG cannot be constructed.
2571 if (BreakJumpTarget.block) {
2572 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
2573 addSuccessor(Block, BreakJumpTarget.block);
2574 } else
2575 badCFG = true;
2576
2577 return Block;
2578 }
2579
CanThrow(Expr * E,ASTContext & Ctx)2580 static bool CanThrow(Expr *E, ASTContext &Ctx) {
2581 QualType Ty = E->getType();
2582 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
2583 Ty = Ty->getPointeeType();
2584
2585 const FunctionType *FT = Ty->getAs<FunctionType>();
2586 if (FT) {
2587 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
2588 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
2589 Proto->isNothrow())
2590 return false;
2591 }
2592 return true;
2593 }
2594
VisitCallExpr(CallExpr * C,AddStmtChoice asc)2595 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2596 // Compute the callee type.
2597 QualType calleeType = C->getCallee()->getType();
2598 if (calleeType == Context->BoundMemberTy) {
2599 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2600
2601 // We should only get a null bound type if processing a dependent
2602 // CFG. Recover by assuming nothing.
2603 if (!boundType.isNull()) calleeType = boundType;
2604 }
2605
2606 // If this is a call to a no-return function, this stops the block here.
2607 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2608
2609 bool AddEHEdge = false;
2610
2611 // Languages without exceptions are assumed to not throw.
2612 if (Context->getLangOpts().Exceptions) {
2613 if (BuildOpts.AddEHEdges)
2614 AddEHEdge = true;
2615 }
2616
2617 // If this is a call to a builtin function, it might not actually evaluate
2618 // its arguments. Don't add them to the CFG if this is the case.
2619 bool OmitArguments = false;
2620
2621 if (FunctionDecl *FD = C->getDirectCallee()) {
2622 // TODO: Support construction contexts for variadic function arguments.
2623 // These are a bit problematic and not very useful because passing
2624 // C++ objects as C-style variadic arguments doesn't work in general
2625 // (see [expr.call]).
2626 if (!FD->isVariadic())
2627 findConstructionContextsForArguments(C);
2628
2629 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
2630 NoReturn = true;
2631 if (FD->hasAttr<NoThrowAttr>())
2632 AddEHEdge = false;
2633 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2634 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
2635 OmitArguments = true;
2636 }
2637
2638 if (!CanThrow(C->getCallee(), *Context))
2639 AddEHEdge = false;
2640
2641 if (OmitArguments) {
2642 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2643 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2644 autoCreateBlock();
2645 appendStmt(Block, C);
2646 return Visit(C->getCallee());
2647 }
2648
2649 if (!NoReturn && !AddEHEdge) {
2650 autoCreateBlock();
2651 appendCall(Block, C);
2652
2653 return VisitChildren(C);
2654 }
2655
2656 if (Block) {
2657 Succ = Block;
2658 if (badCFG)
2659 return nullptr;
2660 }
2661
2662 if (NoReturn)
2663 Block = createNoReturnBlock();
2664 else
2665 Block = createBlock();
2666
2667 appendCall(Block, C);
2668
2669 if (AddEHEdge) {
2670 // Add exceptional edges.
2671 if (TryTerminatedBlock)
2672 addSuccessor(Block, TryTerminatedBlock);
2673 else
2674 addSuccessor(Block, &cfg->getExit());
2675 }
2676
2677 return VisitChildren(C);
2678 }
2679
VisitChooseExpr(ChooseExpr * C,AddStmtChoice asc)2680 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2681 AddStmtChoice asc) {
2682 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2683 appendStmt(ConfluenceBlock, C);
2684 if (badCFG)
2685 return nullptr;
2686
2687 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2688 Succ = ConfluenceBlock;
2689 Block = nullptr;
2690 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2691 if (badCFG)
2692 return nullptr;
2693
2694 Succ = ConfluenceBlock;
2695 Block = nullptr;
2696 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2697 if (badCFG)
2698 return nullptr;
2699
2700 Block = createBlock(false);
2701 // See if this is a known constant.
2702 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2703 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2704 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2705 Block->setTerminator(C);
2706 return addStmt(C->getCond());
2707 }
2708
VisitCompoundStmt(CompoundStmt * C,bool ExternallyDestructed)2709 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed) {
2710 LocalScope::const_iterator scopeBeginPos = ScopePos;
2711 addLocalScopeForStmt(C);
2712
2713 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2714 // If the body ends with a ReturnStmt, the dtors will be added in
2715 // VisitReturnStmt.
2716 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2717 }
2718
2719 CFGBlock *LastBlock = Block;
2720
2721 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2722 I != E; ++I ) {
2723 // If we hit a segment of code just containing ';' (NullStmts), we can
2724 // get a null block back. In such cases, just use the LastBlock
2725 CFGBlock *newBlock = Visit(*I, AddStmtChoice::AlwaysAdd,
2726 ExternallyDestructed);
2727
2728 if (newBlock)
2729 LastBlock = newBlock;
2730
2731 if (badCFG)
2732 return nullptr;
2733
2734 ExternallyDestructed = false;
2735 }
2736
2737 return LastBlock;
2738 }
2739
VisitConditionalOperator(AbstractConditionalOperator * C,AddStmtChoice asc)2740 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2741 AddStmtChoice asc) {
2742 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2743 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2744
2745 // Create the confluence block that will "merge" the results of the ternary
2746 // expression.
2747 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2748 appendStmt(ConfluenceBlock, C);
2749 if (badCFG)
2750 return nullptr;
2751
2752 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2753
2754 // Create a block for the LHS expression if there is an LHS expression. A
2755 // GCC extension allows LHS to be NULL, causing the condition to be the
2756 // value that is returned instead.
2757 // e.g: x ?: y is shorthand for: x ? x : y;
2758 Succ = ConfluenceBlock;
2759 Block = nullptr;
2760 CFGBlock *LHSBlock = nullptr;
2761 const Expr *trueExpr = C->getTrueExpr();
2762 if (trueExpr != opaqueValue) {
2763 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2764 if (badCFG)
2765 return nullptr;
2766 Block = nullptr;
2767 }
2768 else
2769 LHSBlock = ConfluenceBlock;
2770
2771 // Create the block for the RHS expression.
2772 Succ = ConfluenceBlock;
2773 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2774 if (badCFG)
2775 return nullptr;
2776
2777 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2778 if (BinaryOperator *Cond =
2779 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2780 if (Cond->isLogicalOp())
2781 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2782
2783 // Create the block that will contain the condition.
2784 Block = createBlock(false);
2785
2786 // See if this is a known constant.
2787 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2788 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2789 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2790 Block->setTerminator(C);
2791 Expr *condExpr = C->getCond();
2792
2793 if (opaqueValue) {
2794 // Run the condition expression if it's not trivially expressed in
2795 // terms of the opaque value (or if there is no opaque value).
2796 if (condExpr != opaqueValue)
2797 addStmt(condExpr);
2798
2799 // Before that, run the common subexpression if there was one.
2800 // At least one of this or the above will be run.
2801 return addStmt(BCO->getCommon());
2802 }
2803
2804 return addStmt(condExpr);
2805 }
2806
VisitDeclStmt(DeclStmt * DS)2807 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2808 // Check if the Decl is for an __label__. If so, elide it from the
2809 // CFG entirely.
2810 if (isa<LabelDecl>(*DS->decl_begin()))
2811 return Block;
2812
2813 // This case also handles static_asserts.
2814 if (DS->isSingleDecl())
2815 return VisitDeclSubExpr(DS);
2816
2817 CFGBlock *B = nullptr;
2818
2819 // Build an individual DeclStmt for each decl.
2820 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2821 E = DS->decl_rend();
2822 I != E; ++I) {
2823
2824 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2825 // automatically freed with the CFG.
2826 DeclGroupRef DG(*I);
2827 Decl *D = *I;
2828 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2829 cfg->addSyntheticDeclStmt(DSNew, DS);
2830
2831 // Append the fake DeclStmt to block.
2832 B = VisitDeclSubExpr(DSNew);
2833 }
2834
2835 return B;
2836 }
2837
2838 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2839 /// DeclStmts and initializers in them.
VisitDeclSubExpr(DeclStmt * DS)2840 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2841 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2842 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2843
2844 if (!VD) {
2845 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2846 // runtime semantics.
2847 return Block;
2848 }
2849
2850 bool HasTemporaries = false;
2851
2852 // Guard static initializers under a branch.
2853 CFGBlock *blockAfterStaticInit = nullptr;
2854
2855 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2856 // For static variables, we need to create a branch to track
2857 // whether or not they are initialized.
2858 if (Block) {
2859 Succ = Block;
2860 Block = nullptr;
2861 if (badCFG)
2862 return nullptr;
2863 }
2864 blockAfterStaticInit = Succ;
2865 }
2866
2867 // Destructors of temporaries in initialization expression should be called
2868 // after initialization finishes.
2869 Expr *Init = VD->getInit();
2870 if (Init) {
2871 HasTemporaries = isa<ExprWithCleanups>(Init);
2872
2873 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2874 // Generate destructors for temporaries in initialization expression.
2875 TempDtorContext Context;
2876 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2877 /*ExternallyDestructed=*/true, Context);
2878 }
2879 }
2880
2881 autoCreateBlock();
2882 appendStmt(Block, DS);
2883
2884 findConstructionContexts(
2885 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
2886 Init);
2887
2888 // Keep track of the last non-null block, as 'Block' can be nulled out
2889 // if the initializer expression is something like a 'while' in a
2890 // statement-expression.
2891 CFGBlock *LastBlock = Block;
2892
2893 if (Init) {
2894 if (HasTemporaries) {
2895 // For expression with temporaries go directly to subexpression to omit
2896 // generating destructors for the second time.
2897 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2898 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2899 LastBlock = newBlock;
2900 }
2901 else {
2902 if (CFGBlock *newBlock = Visit(Init))
2903 LastBlock = newBlock;
2904 }
2905 }
2906
2907 // If the type of VD is a VLA, then we must process its size expressions.
2908 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2909 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2910 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2911 LastBlock = newBlock;
2912 }
2913
2914 maybeAddScopeBeginForVarDecl(Block, VD, DS);
2915
2916 // Remove variable from local scope.
2917 if (ScopePos && VD == *ScopePos)
2918 ++ScopePos;
2919
2920 CFGBlock *B = LastBlock;
2921 if (blockAfterStaticInit) {
2922 Succ = B;
2923 Block = createBlock(false);
2924 Block->setTerminator(DS);
2925 addSuccessor(Block, blockAfterStaticInit);
2926 addSuccessor(Block, B);
2927 B = Block;
2928 }
2929
2930 return B;
2931 }
2932
VisitIfStmt(IfStmt * I)2933 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2934 // We may see an if statement in the middle of a basic block, or it may be the
2935 // first statement we are processing. In either case, we create a new basic
2936 // block. First, we create the blocks for the then...else statements, and
2937 // then we create the block containing the if statement. If we were in the
2938 // middle of a block, we stop processing that block. That block is then the
2939 // implicit successor for the "then" and "else" clauses.
2940
2941 // Save local scope position because in case of condition variable ScopePos
2942 // won't be restored when traversing AST.
2943 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2944
2945 // Create local scope for C++17 if init-stmt if one exists.
2946 if (Stmt *Init = I->getInit())
2947 addLocalScopeForStmt(Init);
2948
2949 // Create local scope for possible condition variable.
2950 // Store scope position. Add implicit destructor.
2951 if (VarDecl *VD = I->getConditionVariable())
2952 addLocalScopeForVarDecl(VD);
2953
2954 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
2955
2956 // The block we were processing is now finished. Make it the successor
2957 // block.
2958 if (Block) {
2959 Succ = Block;
2960 if (badCFG)
2961 return nullptr;
2962 }
2963
2964 // Process the false branch.
2965 CFGBlock *ElseBlock = Succ;
2966
2967 if (Stmt *Else = I->getElse()) {
2968 SaveAndRestore<CFGBlock*> sv(Succ);
2969
2970 // NULL out Block so that the recursive call to Visit will
2971 // create a new basic block.
2972 Block = nullptr;
2973
2974 // If branch is not a compound statement create implicit scope
2975 // and add destructors.
2976 if (!isa<CompoundStmt>(Else))
2977 addLocalScopeAndDtors(Else);
2978
2979 ElseBlock = addStmt(Else);
2980
2981 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2982 ElseBlock = sv.get();
2983 else if (Block) {
2984 if (badCFG)
2985 return nullptr;
2986 }
2987 }
2988
2989 // Process the true branch.
2990 CFGBlock *ThenBlock;
2991 {
2992 Stmt *Then = I->getThen();
2993 assert(Then);
2994 SaveAndRestore<CFGBlock*> sv(Succ);
2995 Block = nullptr;
2996
2997 // If branch is not a compound statement create implicit scope
2998 // and add destructors.
2999 if (!isa<CompoundStmt>(Then))
3000 addLocalScopeAndDtors(Then);
3001
3002 ThenBlock = addStmt(Then);
3003
3004 if (!ThenBlock) {
3005 // We can reach here if the "then" body has all NullStmts.
3006 // Create an empty block so we can distinguish between true and false
3007 // branches in path-sensitive analyses.
3008 ThenBlock = createBlock(false);
3009 addSuccessor(ThenBlock, sv.get());
3010 } else if (Block) {
3011 if (badCFG)
3012 return nullptr;
3013 }
3014 }
3015
3016 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
3017 // having these handle the actual control-flow jump. Note that
3018 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
3019 // we resort to the old control-flow behavior. This special handling
3020 // removes infeasible paths from the control-flow graph by having the
3021 // control-flow transfer of '&&' or '||' go directly into the then/else
3022 // blocks directly.
3023 BinaryOperator *Cond =
3024 I->getConditionVariable()
3025 ? nullptr
3026 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
3027 CFGBlock *LastBlock;
3028 if (Cond && Cond->isLogicalOp())
3029 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
3030 else {
3031 // Now create a new block containing the if statement.
3032 Block = createBlock(false);
3033
3034 // Set the terminator of the new block to the If statement.
3035 Block->setTerminator(I);
3036
3037 // See if this is a known constant.
3038 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
3039
3040 // Add the successors. If we know that specific branches are
3041 // unreachable, inform addSuccessor() of that knowledge.
3042 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
3043 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
3044
3045 // Add the condition as the last statement in the new block. This may
3046 // create new blocks as the condition may contain control-flow. Any newly
3047 // created blocks will be pointed to be "Block".
3048 LastBlock = addStmt(I->getCond());
3049
3050 // If the IfStmt contains a condition variable, add it and its
3051 // initializer to the CFG.
3052 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
3053 autoCreateBlock();
3054 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
3055 }
3056 }
3057
3058 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3059 if (Stmt *Init = I->getInit()) {
3060 autoCreateBlock();
3061 LastBlock = addStmt(Init);
3062 }
3063
3064 return LastBlock;
3065 }
3066
VisitReturnStmt(Stmt * S)3067 CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
3068 // If we were in the middle of a block we stop processing that block.
3069 //
3070 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3071 // means that the code afterwards is DEAD (unreachable). We still keep
3072 // a basic block for that code; a simple "mark-and-sweep" from the entry
3073 // block will be able to report such dead blocks.
3074 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
3075
3076 // Create the new block.
3077 Block = createBlock(false);
3078
3079 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
3080
3081 if (auto *R = dyn_cast<ReturnStmt>(S))
3082 findConstructionContexts(
3083 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
3084 R->getRetValue());
3085
3086 // If the one of the destructors does not return, we already have the Exit
3087 // block as a successor.
3088 if (!Block->hasNoReturnElement())
3089 addSuccessor(Block, &cfg->getExit());
3090
3091 // Add the return statement to the block.
3092 appendStmt(Block, S);
3093
3094 // Visit children
3095 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
3096 if (Expr *O = RS->getRetValue())
3097 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
3098 return Block;
3099 } else { // co_return
3100 return VisitChildren(S);
3101 }
3102 }
3103
VisitSEHExceptStmt(SEHExceptStmt * ES)3104 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3105 // SEHExceptStmt are treated like labels, so they are the first statement in a
3106 // block.
3107
3108 // Save local scope position because in case of exception variable ScopePos
3109 // won't be restored when traversing AST.
3110 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3111
3112 addStmt(ES->getBlock());
3113 CFGBlock *SEHExceptBlock = Block;
3114 if (!SEHExceptBlock)
3115 SEHExceptBlock = createBlock();
3116
3117 appendStmt(SEHExceptBlock, ES);
3118
3119 // Also add the SEHExceptBlock as a label, like with regular labels.
3120 SEHExceptBlock->setLabel(ES);
3121
3122 // Bail out if the CFG is bad.
3123 if (badCFG)
3124 return nullptr;
3125
3126 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3127 Block = nullptr;
3128
3129 return SEHExceptBlock;
3130 }
3131
VisitSEHFinallyStmt(SEHFinallyStmt * FS)3132 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3133 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
3134 }
3135
VisitSEHLeaveStmt(SEHLeaveStmt * LS)3136 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3137 // "__leave" is a control-flow statement. Thus we stop processing the current
3138 // block.
3139 if (badCFG)
3140 return nullptr;
3141
3142 // Now create a new block that ends with the __leave statement.
3143 Block = createBlock(false);
3144 Block->setTerminator(LS);
3145
3146 // If there is no target for the __leave, then we are looking at an incomplete
3147 // AST. This means that the CFG cannot be constructed.
3148 if (SEHLeaveJumpTarget.block) {
3149 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3150 addSuccessor(Block, SEHLeaveJumpTarget.block);
3151 } else
3152 badCFG = true;
3153
3154 return Block;
3155 }
3156
VisitSEHTryStmt(SEHTryStmt * Terminator)3157 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3158 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3159 // processing the current block.
3160 CFGBlock *SEHTrySuccessor = nullptr;
3161
3162 if (Block) {
3163 if (badCFG)
3164 return nullptr;
3165 SEHTrySuccessor = Block;
3166 } else SEHTrySuccessor = Succ;
3167
3168 // FIXME: Implement __finally support.
3169 if (Terminator->getFinallyHandler())
3170 return NYS();
3171
3172 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3173
3174 // Create a new block that will contain the __try statement.
3175 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3176
3177 // Add the terminator in the __try block.
3178 NewTryTerminatedBlock->setTerminator(Terminator);
3179
3180 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3181 // The code after the try is the implicit successor if there's an __except.
3182 Succ = SEHTrySuccessor;
3183 Block = nullptr;
3184 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3185 if (!ExceptBlock)
3186 return nullptr;
3187 // Add this block to the list of successors for the block with the try
3188 // statement.
3189 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3190 }
3191 if (PrevSEHTryTerminatedBlock)
3192 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3193 else
3194 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3195
3196 // The code after the try is the implicit successor.
3197 Succ = SEHTrySuccessor;
3198
3199 // Save the current "__try" context.
3200 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
3201 NewTryTerminatedBlock);
3202 cfg->addTryDispatchBlock(TryTerminatedBlock);
3203
3204 // Save the current value for the __leave target.
3205 // All __leaves should go to the code following the __try
3206 // (FIXME: or if the __try has a __finally, to the __finally.)
3207 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
3208 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3209
3210 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3211 Block = nullptr;
3212 return addStmt(Terminator->getTryBlock());
3213 }
3214
VisitLabelStmt(LabelStmt * L)3215 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3216 // Get the block of the labeled statement. Add it to our map.
3217 addStmt(L->getSubStmt());
3218 CFGBlock *LabelBlock = Block;
3219
3220 if (!LabelBlock) // This can happen when the body is empty, i.e.
3221 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3222
3223 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
3224 "label already in map");
3225 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3226
3227 // Labels partition blocks, so this is the end of the basic block we were
3228 // processing (L is the block's label). Because this is label (and we have
3229 // already processed the substatement) there is no extra control-flow to worry
3230 // about.
3231 LabelBlock->setLabel(L);
3232 if (badCFG)
3233 return nullptr;
3234
3235 // We set Block to NULL to allow lazy creation of a new block (if necessary);
3236 Block = nullptr;
3237
3238 // This block is now the implicit successor of other blocks.
3239 Succ = LabelBlock;
3240
3241 return LabelBlock;
3242 }
3243
VisitBlockExpr(BlockExpr * E,AddStmtChoice asc)3244 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3245 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3246 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3247 if (Expr *CopyExpr = CI.getCopyExpr()) {
3248 CFGBlock *Tmp = Visit(CopyExpr);
3249 if (Tmp)
3250 LastBlock = Tmp;
3251 }
3252 }
3253 return LastBlock;
3254 }
3255
VisitLambdaExpr(LambdaExpr * E,AddStmtChoice asc)3256 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3257 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3258 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3259 et = E->capture_init_end(); it != et; ++it) {
3260 if (Expr *Init = *it) {
3261 CFGBlock *Tmp = Visit(Init);
3262 if (Tmp)
3263 LastBlock = Tmp;
3264 }
3265 }
3266 return LastBlock;
3267 }
3268
VisitGotoStmt(GotoStmt * G)3269 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3270 // Goto is a control-flow statement. Thus we stop processing the current
3271 // block and create a new one.
3272
3273 Block = createBlock(false);
3274 Block->setTerminator(G);
3275
3276 // If we already know the mapping to the label block add the successor now.
3277 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
3278
3279 if (I == LabelMap.end())
3280 // We will need to backpatch this block later.
3281 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3282 else {
3283 JumpTarget JT = I->second;
3284 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
3285 addSuccessor(Block, JT.block);
3286 }
3287
3288 return Block;
3289 }
3290
VisitGCCAsmStmt(GCCAsmStmt * G,AddStmtChoice asc)3291 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3292 // Goto is a control-flow statement. Thus we stop processing the current
3293 // block and create a new one.
3294
3295 if (!G->isAsmGoto())
3296 return VisitStmt(G, asc);
3297
3298 if (Block) {
3299 Succ = Block;
3300 if (badCFG)
3301 return nullptr;
3302 }
3303 Block = createBlock();
3304 Block->setTerminator(G);
3305 // We will backpatch this block later for all the labels.
3306 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3307 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3308 // used to avoid adding "Succ" again.
3309 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3310 return Block;
3311 }
3312
VisitForStmt(ForStmt * F)3313 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3314 CFGBlock *LoopSuccessor = nullptr;
3315
3316 // Save local scope position because in case of condition variable ScopePos
3317 // won't be restored when traversing AST.
3318 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3319
3320 // Create local scope for init statement and possible condition variable.
3321 // Add destructor for init statement and condition variable.
3322 // Store scope position for continue statement.
3323 if (Stmt *Init = F->getInit())
3324 addLocalScopeForStmt(Init);
3325 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3326
3327 if (VarDecl *VD = F->getConditionVariable())
3328 addLocalScopeForVarDecl(VD);
3329 LocalScope::const_iterator ContinueScopePos = ScopePos;
3330
3331 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
3332
3333 addLoopExit(F);
3334
3335 // "for" is a control-flow statement. Thus we stop processing the current
3336 // block.
3337 if (Block) {
3338 if (badCFG)
3339 return nullptr;
3340 LoopSuccessor = Block;
3341 } else
3342 LoopSuccessor = Succ;
3343
3344 // Save the current value for the break targets.
3345 // All breaks should go to the code following the loop.
3346 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3347 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3348
3349 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3350
3351 // Now create the loop body.
3352 {
3353 assert(F->getBody());
3354
3355 // Save the current values for Block, Succ, continue and break targets.
3356 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3357 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3358
3359 // Create an empty block to represent the transition block for looping back
3360 // to the head of the loop. If we have increment code, it will
3361 // go in this block as well.
3362 Block = Succ = TransitionBlock = createBlock(false);
3363 TransitionBlock->setLoopTarget(F);
3364
3365 if (Stmt *I = F->getInc()) {
3366 // Generate increment code in its own basic block. This is the target of
3367 // continue statements.
3368 Succ = addStmt(I);
3369 }
3370
3371 // Finish up the increment (or empty) block if it hasn't been already.
3372 if (Block) {
3373 assert(Block == Succ);
3374 if (badCFG)
3375 return nullptr;
3376 Block = nullptr;
3377 }
3378
3379 // The starting block for the loop increment is the block that should
3380 // represent the 'loop target' for looping back to the start of the loop.
3381 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3382 ContinueJumpTarget.block->setLoopTarget(F);
3383
3384 // Loop body should end with destructor of Condition variable (if any).
3385 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
3386
3387 // If body is not a compound statement create implicit scope
3388 // and add destructors.
3389 if (!isa<CompoundStmt>(F->getBody()))
3390 addLocalScopeAndDtors(F->getBody());
3391
3392 // Now populate the body block, and in the process create new blocks as we
3393 // walk the body of the loop.
3394 BodyBlock = addStmt(F->getBody());
3395
3396 if (!BodyBlock) {
3397 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3398 // Use the continue jump target as the proxy for the body.
3399 BodyBlock = ContinueJumpTarget.block;
3400 }
3401 else if (badCFG)
3402 return nullptr;
3403 }
3404
3405 // Because of short-circuit evaluation, the condition of the loop can span
3406 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3407 // evaluate the condition.
3408 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3409
3410 do {
3411 Expr *C = F->getCond();
3412 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3413
3414 // Specially handle logical operators, which have a slightly
3415 // more optimal CFG representation.
3416 if (BinaryOperator *Cond =
3417 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
3418 if (Cond->isLogicalOp()) {
3419 std::tie(EntryConditionBlock, ExitConditionBlock) =
3420 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3421 break;
3422 }
3423
3424 // The default case when not handling logical operators.
3425 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3426 ExitConditionBlock->setTerminator(F);
3427
3428 // See if this is a known constant.
3429 TryResult KnownVal(true);
3430
3431 if (C) {
3432 // Now add the actual condition to the condition block.
3433 // Because the condition itself may contain control-flow, new blocks may
3434 // be created. Thus we update "Succ" after adding the condition.
3435 Block = ExitConditionBlock;
3436 EntryConditionBlock = addStmt(C);
3437
3438 // If this block contains a condition variable, add both the condition
3439 // variable and initializer to the CFG.
3440 if (VarDecl *VD = F->getConditionVariable()) {
3441 if (Expr *Init = VD->getInit()) {
3442 autoCreateBlock();
3443 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3444 assert(DS->isSingleDecl());
3445 findConstructionContexts(
3446 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3447 Init);
3448 appendStmt(Block, DS);
3449 EntryConditionBlock = addStmt(Init);
3450 assert(Block == EntryConditionBlock);
3451 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3452 }
3453 }
3454
3455 if (Block && badCFG)
3456 return nullptr;
3457
3458 KnownVal = tryEvaluateBool(C);
3459 }
3460
3461 // Add the loop body entry as a successor to the condition.
3462 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3463 // Link up the condition block with the code that follows the loop. (the
3464 // false branch).
3465 addSuccessor(ExitConditionBlock,
3466 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3467 } while (false);
3468
3469 // Link up the loop-back block to the entry condition block.
3470 addSuccessor(TransitionBlock, EntryConditionBlock);
3471
3472 // The condition block is the implicit successor for any code above the loop.
3473 Succ = EntryConditionBlock;
3474
3475 // If the loop contains initialization, create a new block for those
3476 // statements. This block can also contain statements that precede the loop.
3477 if (Stmt *I = F->getInit()) {
3478 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3479 ScopePos = LoopBeginScopePos;
3480 Block = createBlock();
3481 return addStmt(I);
3482 }
3483
3484 // There is no loop initialization. We are thus basically a while loop.
3485 // NULL out Block to force lazy block construction.
3486 Block = nullptr;
3487 Succ = EntryConditionBlock;
3488 return EntryConditionBlock;
3489 }
3490
3491 CFGBlock *
VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr * MTE,AddStmtChoice asc)3492 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3493 AddStmtChoice asc) {
3494 findConstructionContexts(
3495 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
3496 MTE->getSubExpr());
3497
3498 return VisitStmt(MTE, asc);
3499 }
3500
VisitMemberExpr(MemberExpr * M,AddStmtChoice asc)3501 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3502 if (asc.alwaysAdd(*this, M)) {
3503 autoCreateBlock();
3504 appendStmt(Block, M);
3505 }
3506 return Visit(M->getBase());
3507 }
3508
VisitObjCForCollectionStmt(ObjCForCollectionStmt * S)3509 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3510 // Objective-C fast enumeration 'for' statements:
3511 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3512 //
3513 // for ( Type newVariable in collection_expression ) { statements }
3514 //
3515 // becomes:
3516 //
3517 // prologue:
3518 // 1. collection_expression
3519 // T. jump to loop_entry
3520 // loop_entry:
3521 // 1. side-effects of element expression
3522 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3523 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3524 // TB:
3525 // statements
3526 // T. jump to loop_entry
3527 // FB:
3528 // what comes after
3529 //
3530 // and
3531 //
3532 // Type existingItem;
3533 // for ( existingItem in expression ) { statements }
3534 //
3535 // becomes:
3536 //
3537 // the same with newVariable replaced with existingItem; the binding works
3538 // the same except that for one ObjCForCollectionStmt::getElement() returns
3539 // a DeclStmt and the other returns a DeclRefExpr.
3540
3541 CFGBlock *LoopSuccessor = nullptr;
3542
3543 if (Block) {
3544 if (badCFG)
3545 return nullptr;
3546 LoopSuccessor = Block;
3547 Block = nullptr;
3548 } else
3549 LoopSuccessor = Succ;
3550
3551 // Build the condition blocks.
3552 CFGBlock *ExitConditionBlock = createBlock(false);
3553
3554 // Set the terminator for the "exit" condition block.
3555 ExitConditionBlock->setTerminator(S);
3556
3557 // The last statement in the block should be the ObjCForCollectionStmt, which
3558 // performs the actual binding to 'element' and determines if there are any
3559 // more items in the collection.
3560 appendStmt(ExitConditionBlock, S);
3561 Block = ExitConditionBlock;
3562
3563 // Walk the 'element' expression to see if there are any side-effects. We
3564 // generate new blocks as necessary. We DON'T add the statement by default to
3565 // the CFG unless it contains control-flow.
3566 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3567 AddStmtChoice::NotAlwaysAdd);
3568 if (Block) {
3569 if (badCFG)
3570 return nullptr;
3571 Block = nullptr;
3572 }
3573
3574 // The condition block is the implicit successor for the loop body as well as
3575 // any code above the loop.
3576 Succ = EntryConditionBlock;
3577
3578 // Now create the true branch.
3579 {
3580 // Save the current values for Succ, continue and break targets.
3581 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3582 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3583 save_break(BreakJumpTarget);
3584
3585 // Add an intermediate block between the BodyBlock and the
3586 // EntryConditionBlock to represent the "loop back" transition, for looping
3587 // back to the head of the loop.
3588 CFGBlock *LoopBackBlock = nullptr;
3589 Succ = LoopBackBlock = createBlock();
3590 LoopBackBlock->setLoopTarget(S);
3591
3592 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3593 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3594
3595 CFGBlock *BodyBlock = addStmt(S->getBody());
3596
3597 if (!BodyBlock)
3598 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3599 else if (Block) {
3600 if (badCFG)
3601 return nullptr;
3602 }
3603
3604 // This new body block is a successor to our "exit" condition block.
3605 addSuccessor(ExitConditionBlock, BodyBlock);
3606 }
3607
3608 // Link up the condition block with the code that follows the loop.
3609 // (the false branch).
3610 addSuccessor(ExitConditionBlock, LoopSuccessor);
3611
3612 // Now create a prologue block to contain the collection expression.
3613 Block = createBlock();
3614 return addStmt(S->getCollection());
3615 }
3616
VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt * S)3617 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3618 // Inline the body.
3619 return addStmt(S->getSubStmt());
3620 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3621 }
3622
VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt * S)3623 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3624 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3625
3626 // Inline the body.
3627 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3628
3629 // The sync body starts its own basic block. This makes it a little easier
3630 // for diagnostic clients.
3631 if (SyncBlock) {
3632 if (badCFG)
3633 return nullptr;
3634
3635 Block = nullptr;
3636 Succ = SyncBlock;
3637 }
3638
3639 // Add the @synchronized to the CFG.
3640 autoCreateBlock();
3641 appendStmt(Block, S);
3642
3643 // Inline the sync expression.
3644 return addStmt(S->getSynchExpr());
3645 }
3646
VisitObjCAtTryStmt(ObjCAtTryStmt * S)3647 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
3648 // FIXME
3649 return NYS();
3650 }
3651
VisitPseudoObjectExpr(PseudoObjectExpr * E)3652 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3653 autoCreateBlock();
3654
3655 // Add the PseudoObject as the last thing.
3656 appendStmt(Block, E);
3657
3658 CFGBlock *lastBlock = Block;
3659
3660 // Before that, evaluate all of the semantics in order. In
3661 // CFG-land, that means appending them in reverse order.
3662 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3663 Expr *Semantic = E->getSemanticExpr(--i);
3664
3665 // If the semantic is an opaque value, we're being asked to bind
3666 // it to its source expression.
3667 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3668 Semantic = OVE->getSourceExpr();
3669
3670 if (CFGBlock *B = Visit(Semantic))
3671 lastBlock = B;
3672 }
3673
3674 return lastBlock;
3675 }
3676
VisitWhileStmt(WhileStmt * W)3677 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3678 CFGBlock *LoopSuccessor = nullptr;
3679
3680 // Save local scope position because in case of condition variable ScopePos
3681 // won't be restored when traversing AST.
3682 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3683
3684 // Create local scope for possible condition variable.
3685 // Store scope position for continue statement.
3686 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3687 if (VarDecl *VD = W->getConditionVariable()) {
3688 addLocalScopeForVarDecl(VD);
3689 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3690 }
3691 addLoopExit(W);
3692
3693 // "while" is a control-flow statement. Thus we stop processing the current
3694 // block.
3695 if (Block) {
3696 if (badCFG)
3697 return nullptr;
3698 LoopSuccessor = Block;
3699 Block = nullptr;
3700 } else {
3701 LoopSuccessor = Succ;
3702 }
3703
3704 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3705
3706 // Process the loop body.
3707 {
3708 assert(W->getBody());
3709
3710 // Save the current values for Block, Succ, continue and break targets.
3711 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3712 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3713 save_break(BreakJumpTarget);
3714
3715 // Create an empty block to represent the transition block for looping back
3716 // to the head of the loop.
3717 Succ = TransitionBlock = createBlock(false);
3718 TransitionBlock->setLoopTarget(W);
3719 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
3720
3721 // All breaks should go to the code following the loop.
3722 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3723
3724 // Loop body should end with destructor of Condition variable (if any).
3725 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3726
3727 // If body is not a compound statement create implicit scope
3728 // and add destructors.
3729 if (!isa<CompoundStmt>(W->getBody()))
3730 addLocalScopeAndDtors(W->getBody());
3731
3732 // Create the body. The returned block is the entry to the loop body.
3733 BodyBlock = addStmt(W->getBody());
3734
3735 if (!BodyBlock)
3736 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
3737 else if (Block && badCFG)
3738 return nullptr;
3739 }
3740
3741 // Because of short-circuit evaluation, the condition of the loop can span
3742 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3743 // evaluate the condition.
3744 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3745
3746 do {
3747 Expr *C = W->getCond();
3748
3749 // Specially handle logical operators, which have a slightly
3750 // more optimal CFG representation.
3751 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
3752 if (Cond->isLogicalOp()) {
3753 std::tie(EntryConditionBlock, ExitConditionBlock) =
3754 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
3755 break;
3756 }
3757
3758 // The default case when not handling logical operators.
3759 ExitConditionBlock = createBlock(false);
3760 ExitConditionBlock->setTerminator(W);
3761
3762 // Now add the actual condition to the condition block.
3763 // Because the condition itself may contain control-flow, new blocks may
3764 // be created. Thus we update "Succ" after adding the condition.
3765 Block = ExitConditionBlock;
3766 Block = EntryConditionBlock = addStmt(C);
3767
3768 // If this block contains a condition variable, add both the condition
3769 // variable and initializer to the CFG.
3770 if (VarDecl *VD = W->getConditionVariable()) {
3771 if (Expr *Init = VD->getInit()) {
3772 autoCreateBlock();
3773 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3774 assert(DS->isSingleDecl());
3775 findConstructionContexts(
3776 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3777 const_cast<DeclStmt *>(DS)),
3778 Init);
3779 appendStmt(Block, DS);
3780 EntryConditionBlock = addStmt(Init);
3781 assert(Block == EntryConditionBlock);
3782 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3783 }
3784 }
3785
3786 if (Block && badCFG)
3787 return nullptr;
3788
3789 // See if this is a known constant.
3790 const TryResult& KnownVal = tryEvaluateBool(C);
3791
3792 // Add the loop body entry as a successor to the condition.
3793 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3794 // Link up the condition block with the code that follows the loop. (the
3795 // false branch).
3796 addSuccessor(ExitConditionBlock,
3797 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3798 } while(false);
3799
3800 // Link up the loop-back block to the entry condition block.
3801 addSuccessor(TransitionBlock, EntryConditionBlock);
3802
3803 // There can be no more statements in the condition block since we loop back
3804 // to this block. NULL out Block to force lazy creation of another block.
3805 Block = nullptr;
3806
3807 // Return the condition block, which is the dominating block for the loop.
3808 Succ = EntryConditionBlock;
3809 return EntryConditionBlock;
3810 }
3811
VisitObjCAtCatchStmt(ObjCAtCatchStmt * S)3812 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
3813 // FIXME: For now we pretend that @catch and the code it contains does not
3814 // exit.
3815 return Block;
3816 }
3817
VisitObjCAtThrowStmt(ObjCAtThrowStmt * S)3818 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
3819 // FIXME: This isn't complete. We basically treat @throw like a return
3820 // statement.
3821
3822 // If we were in the middle of a block we stop processing that block.
3823 if (badCFG)
3824 return nullptr;
3825
3826 // Create the new block.
3827 Block = createBlock(false);
3828
3829 // The Exit block is the only successor.
3830 addSuccessor(Block, &cfg->getExit());
3831
3832 // Add the statement to the block. This may create new blocks if S contains
3833 // control-flow (short-circuit operations).
3834 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
3835 }
3836
VisitObjCMessageExpr(ObjCMessageExpr * ME,AddStmtChoice asc)3837 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
3838 AddStmtChoice asc) {
3839 findConstructionContextsForArguments(ME);
3840
3841 autoCreateBlock();
3842 appendObjCMessage(Block, ME);
3843
3844 return VisitChildren(ME);
3845 }
3846
VisitCXXThrowExpr(CXXThrowExpr * T)3847 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
3848 // If we were in the middle of a block we stop processing that block.
3849 if (badCFG)
3850 return nullptr;
3851
3852 // Create the new block.
3853 Block = createBlock(false);
3854
3855 if (TryTerminatedBlock)
3856 // The current try statement is the only successor.
3857 addSuccessor(Block, TryTerminatedBlock);
3858 else
3859 // otherwise the Exit block is the only successor.
3860 addSuccessor(Block, &cfg->getExit());
3861
3862 // Add the statement to the block. This may create new blocks if S contains
3863 // control-flow (short-circuit operations).
3864 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
3865 }
3866
VisitDoStmt(DoStmt * D)3867 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
3868 CFGBlock *LoopSuccessor = nullptr;
3869
3870 addLoopExit(D);
3871
3872 // "do...while" is a control-flow statement. Thus we stop processing the
3873 // current block.
3874 if (Block) {
3875 if (badCFG)
3876 return nullptr;
3877 LoopSuccessor = Block;
3878 } else
3879 LoopSuccessor = Succ;
3880
3881 // Because of short-circuit evaluation, the condition of the loop can span
3882 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3883 // evaluate the condition.
3884 CFGBlock *ExitConditionBlock = createBlock(false);
3885 CFGBlock *EntryConditionBlock = ExitConditionBlock;
3886
3887 // Set the terminator for the "exit" condition block.
3888 ExitConditionBlock->setTerminator(D);
3889
3890 // Now add the actual condition to the condition block. Because the condition
3891 // itself may contain control-flow, new blocks may be created.
3892 if (Stmt *C = D->getCond()) {
3893 Block = ExitConditionBlock;
3894 EntryConditionBlock = addStmt(C);
3895 if (Block) {
3896 if (badCFG)
3897 return nullptr;
3898 }
3899 }
3900
3901 // The condition block is the implicit successor for the loop body.
3902 Succ = EntryConditionBlock;
3903
3904 // See if this is a known constant.
3905 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
3906
3907 // Process the loop body.
3908 CFGBlock *BodyBlock = nullptr;
3909 {
3910 assert(D->getBody());
3911
3912 // Save the current values for Block, Succ, and continue and break targets
3913 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3914 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3915 save_break(BreakJumpTarget);
3916
3917 // All continues within this loop should go to the condition block
3918 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
3919
3920 // All breaks should go to the code following the loop.
3921 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3922
3923 // NULL out Block to force lazy instantiation of blocks for the body.
3924 Block = nullptr;
3925
3926 // If body is not a compound statement create implicit scope
3927 // and add destructors.
3928 if (!isa<CompoundStmt>(D->getBody()))
3929 addLocalScopeAndDtors(D->getBody());
3930
3931 // Create the body. The returned block is the entry to the loop body.
3932 BodyBlock = addStmt(D->getBody());
3933
3934 if (!BodyBlock)
3935 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
3936 else if (Block) {
3937 if (badCFG)
3938 return nullptr;
3939 }
3940
3941 // Add an intermediate block between the BodyBlock and the
3942 // ExitConditionBlock to represent the "loop back" transition. Create an
3943 // empty block to represent the transition block for looping back to the
3944 // head of the loop.
3945 // FIXME: Can we do this more efficiently without adding another block?
3946 Block = nullptr;
3947 Succ = BodyBlock;
3948 CFGBlock *LoopBackBlock = createBlock();
3949 LoopBackBlock->setLoopTarget(D);
3950
3951 if (!KnownVal.isFalse())
3952 // Add the loop body entry as a successor to the condition.
3953 addSuccessor(ExitConditionBlock, LoopBackBlock);
3954 else
3955 addSuccessor(ExitConditionBlock, nullptr);
3956 }
3957
3958 // Link up the condition block with the code that follows the loop.
3959 // (the false branch).
3960 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3961
3962 // There can be no more statements in the body block(s) since we loop back to
3963 // the body. NULL out Block to force lazy creation of another block.
3964 Block = nullptr;
3965
3966 // Return the loop body, which is the dominating block for the loop.
3967 Succ = BodyBlock;
3968 return BodyBlock;
3969 }
3970
VisitContinueStmt(ContinueStmt * C)3971 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
3972 // "continue" is a control-flow statement. Thus we stop processing the
3973 // current block.
3974 if (badCFG)
3975 return nullptr;
3976
3977 // Now create a new block that ends with the continue statement.
3978 Block = createBlock(false);
3979 Block->setTerminator(C);
3980
3981 // If there is no target for the continue, then we are looking at an
3982 // incomplete AST. This means the CFG cannot be constructed.
3983 if (ContinueJumpTarget.block) {
3984 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
3985 addSuccessor(Block, ContinueJumpTarget.block);
3986 } else
3987 badCFG = true;
3988
3989 return Block;
3990 }
3991
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E,AddStmtChoice asc)3992 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3993 AddStmtChoice asc) {
3994 if (asc.alwaysAdd(*this, E)) {
3995 autoCreateBlock();
3996 appendStmt(Block, E);
3997 }
3998
3999 // VLA types have expressions that must be evaluated.
4000 CFGBlock *lastBlock = Block;
4001
4002 if (E->isArgumentType()) {
4003 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
4004 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
4005 lastBlock = addStmt(VA->getSizeExpr());
4006 }
4007 return lastBlock;
4008 }
4009
4010 /// VisitStmtExpr - Utility method to handle (nested) statement
4011 /// expressions (a GCC extension).
VisitStmtExpr(StmtExpr * SE,AddStmtChoice asc)4012 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
4013 if (asc.alwaysAdd(*this, SE)) {
4014 autoCreateBlock();
4015 appendStmt(Block, SE);
4016 }
4017 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
4018 }
4019
VisitSwitchStmt(SwitchStmt * Terminator)4020 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
4021 // "switch" is a control-flow statement. Thus we stop processing the current
4022 // block.
4023 CFGBlock *SwitchSuccessor = nullptr;
4024
4025 // Save local scope position because in case of condition variable ScopePos
4026 // won't be restored when traversing AST.
4027 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4028
4029 // Create local scope for C++17 switch init-stmt if one exists.
4030 if (Stmt *Init = Terminator->getInit())
4031 addLocalScopeForStmt(Init);
4032
4033 // Create local scope for possible condition variable.
4034 // Store scope position. Add implicit destructor.
4035 if (VarDecl *VD = Terminator->getConditionVariable())
4036 addLocalScopeForVarDecl(VD);
4037
4038 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4039
4040 if (Block) {
4041 if (badCFG)
4042 return nullptr;
4043 SwitchSuccessor = Block;
4044 } else SwitchSuccessor = Succ;
4045
4046 // Save the current "switch" context.
4047 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
4048 save_default(DefaultCaseBlock);
4049 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4050
4051 // Set the "default" case to be the block after the switch statement. If the
4052 // switch statement contains a "default:", this value will be overwritten with
4053 // the block for that code.
4054 DefaultCaseBlock = SwitchSuccessor;
4055
4056 // Create a new block that will contain the switch statement.
4057 SwitchTerminatedBlock = createBlock(false);
4058
4059 // Now process the switch body. The code after the switch is the implicit
4060 // successor.
4061 Succ = SwitchSuccessor;
4062 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4063
4064 // When visiting the body, the case statements should automatically get linked
4065 // up to the switch. We also don't keep a pointer to the body, since all
4066 // control-flow from the switch goes to case/default statements.
4067 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4068 Block = nullptr;
4069
4070 // For pruning unreachable case statements, save the current state
4071 // for tracking the condition value.
4072 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
4073 false);
4074
4075 // Determine if the switch condition can be explicitly evaluated.
4076 assert(Terminator->getCond() && "switch condition must be non-NULL");
4077 Expr::EvalResult result;
4078 bool b = tryEvaluate(Terminator->getCond(), result);
4079 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
4080 b ? &result : nullptr);
4081
4082 // If body is not a compound statement create implicit scope
4083 // and add destructors.
4084 if (!isa<CompoundStmt>(Terminator->getBody()))
4085 addLocalScopeAndDtors(Terminator->getBody());
4086
4087 addStmt(Terminator->getBody());
4088 if (Block) {
4089 if (badCFG)
4090 return nullptr;
4091 }
4092
4093 // If we have no "default:" case, the default transition is to the code
4094 // following the switch body. Moreover, take into account if all the
4095 // cases of a switch are covered (e.g., switching on an enum value).
4096 //
4097 // Note: We add a successor to a switch that is considered covered yet has no
4098 // case statements if the enumeration has no enumerators.
4099 bool SwitchAlwaysHasSuccessor = false;
4100 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4101 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
4102 Terminator->getSwitchCaseList();
4103 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
4104 !SwitchAlwaysHasSuccessor);
4105
4106 // Add the terminator and condition in the switch block.
4107 SwitchTerminatedBlock->setTerminator(Terminator);
4108 Block = SwitchTerminatedBlock;
4109 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4110
4111 // If the SwitchStmt contains a condition variable, add both the
4112 // SwitchStmt and the condition variable initialization to the CFG.
4113 if (VarDecl *VD = Terminator->getConditionVariable()) {
4114 if (Expr *Init = VD->getInit()) {
4115 autoCreateBlock();
4116 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
4117 LastBlock = addStmt(Init);
4118 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4119 }
4120 }
4121
4122 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4123 if (Stmt *Init = Terminator->getInit()) {
4124 autoCreateBlock();
4125 LastBlock = addStmt(Init);
4126 }
4127
4128 return LastBlock;
4129 }
4130
shouldAddCase(bool & switchExclusivelyCovered,const Expr::EvalResult * switchCond,const CaseStmt * CS,ASTContext & Ctx)4131 static bool shouldAddCase(bool &switchExclusivelyCovered,
4132 const Expr::EvalResult *switchCond,
4133 const CaseStmt *CS,
4134 ASTContext &Ctx) {
4135 if (!switchCond)
4136 return true;
4137
4138 bool addCase = false;
4139
4140 if (!switchExclusivelyCovered) {
4141 if (switchCond->Val.isInt()) {
4142 // Evaluate the LHS of the case value.
4143 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4144 const llvm::APSInt &condInt = switchCond->Val.getInt();
4145
4146 if (condInt == lhsInt) {
4147 addCase = true;
4148 switchExclusivelyCovered = true;
4149 }
4150 else if (condInt > lhsInt) {
4151 if (const Expr *RHS = CS->getRHS()) {
4152 // Evaluate the RHS of the case value.
4153 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4154 if (V2 >= condInt) {
4155 addCase = true;
4156 switchExclusivelyCovered = true;
4157 }
4158 }
4159 }
4160 }
4161 else
4162 addCase = true;
4163 }
4164 return addCase;
4165 }
4166
VisitCaseStmt(CaseStmt * CS)4167 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4168 // CaseStmts are essentially labels, so they are the first statement in a
4169 // block.
4170 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4171
4172 if (Stmt *Sub = CS->getSubStmt()) {
4173 // For deeply nested chains of CaseStmts, instead of doing a recursion
4174 // (which can blow out the stack), manually unroll and create blocks
4175 // along the way.
4176 while (isa<CaseStmt>(Sub)) {
4177 CFGBlock *currentBlock = createBlock(false);
4178 currentBlock->setLabel(CS);
4179
4180 if (TopBlock)
4181 addSuccessor(LastBlock, currentBlock);
4182 else
4183 TopBlock = currentBlock;
4184
4185 addSuccessor(SwitchTerminatedBlock,
4186 shouldAddCase(switchExclusivelyCovered, switchCond,
4187 CS, *Context)
4188 ? currentBlock : nullptr);
4189
4190 LastBlock = currentBlock;
4191 CS = cast<CaseStmt>(Sub);
4192 Sub = CS->getSubStmt();
4193 }
4194
4195 addStmt(Sub);
4196 }
4197
4198 CFGBlock *CaseBlock = Block;
4199 if (!CaseBlock)
4200 CaseBlock = createBlock();
4201
4202 // Cases statements partition blocks, so this is the top of the basic block we
4203 // were processing (the "case XXX:" is the label).
4204 CaseBlock->setLabel(CS);
4205
4206 if (badCFG)
4207 return nullptr;
4208
4209 // Add this block to the list of successors for the block with the switch
4210 // statement.
4211 assert(SwitchTerminatedBlock);
4212 addSuccessor(SwitchTerminatedBlock, CaseBlock,
4213 shouldAddCase(switchExclusivelyCovered, switchCond,
4214 CS, *Context));
4215
4216 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4217 Block = nullptr;
4218
4219 if (TopBlock) {
4220 addSuccessor(LastBlock, CaseBlock);
4221 Succ = TopBlock;
4222 } else {
4223 // This block is now the implicit successor of other blocks.
4224 Succ = CaseBlock;
4225 }
4226
4227 return Succ;
4228 }
4229
VisitDefaultStmt(DefaultStmt * Terminator)4230 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4231 if (Terminator->getSubStmt())
4232 addStmt(Terminator->getSubStmt());
4233
4234 DefaultCaseBlock = Block;
4235
4236 if (!DefaultCaseBlock)
4237 DefaultCaseBlock = createBlock();
4238
4239 // Default statements partition blocks, so this is the top of the basic block
4240 // we were processing (the "default:" is the label).
4241 DefaultCaseBlock->setLabel(Terminator);
4242
4243 if (badCFG)
4244 return nullptr;
4245
4246 // Unlike case statements, we don't add the default block to the successors
4247 // for the switch statement immediately. This is done when we finish
4248 // processing the switch statement. This allows for the default case
4249 // (including a fall-through to the code after the switch statement) to always
4250 // be the last successor of a switch-terminated block.
4251
4252 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4253 Block = nullptr;
4254
4255 // This block is now the implicit successor of other blocks.
4256 Succ = DefaultCaseBlock;
4257
4258 return DefaultCaseBlock;
4259 }
4260
VisitCXXTryStmt(CXXTryStmt * Terminator)4261 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4262 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4263 // current block.
4264 CFGBlock *TrySuccessor = nullptr;
4265
4266 if (Block) {
4267 if (badCFG)
4268 return nullptr;
4269 TrySuccessor = Block;
4270 } else TrySuccessor = Succ;
4271
4272 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4273
4274 // Create a new block that will contain the try statement.
4275 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4276 // Add the terminator in the try block.
4277 NewTryTerminatedBlock->setTerminator(Terminator);
4278
4279 bool HasCatchAll = false;
4280 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
4281 // The code after the try is the implicit successor.
4282 Succ = TrySuccessor;
4283 CXXCatchStmt *CS = Terminator->getHandler(h);
4284 if (CS->getExceptionDecl() == nullptr) {
4285 HasCatchAll = true;
4286 }
4287 Block = nullptr;
4288 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
4289 if (!CatchBlock)
4290 return nullptr;
4291 // Add this block to the list of successors for the block with the try
4292 // statement.
4293 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4294 }
4295 if (!HasCatchAll) {
4296 if (PrevTryTerminatedBlock)
4297 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4298 else
4299 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4300 }
4301
4302 // The code after the try is the implicit successor.
4303 Succ = TrySuccessor;
4304
4305 // Save the current "try" context.
4306 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
4307 cfg->addTryDispatchBlock(TryTerminatedBlock);
4308
4309 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4310 Block = nullptr;
4311 return addStmt(Terminator->getTryBlock());
4312 }
4313
VisitCXXCatchStmt(CXXCatchStmt * CS)4314 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4315 // CXXCatchStmt are treated like labels, so they are the first statement in a
4316 // block.
4317
4318 // Save local scope position because in case of exception variable ScopePos
4319 // won't be restored when traversing AST.
4320 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4321
4322 // Create local scope for possible exception variable.
4323 // Store scope position. Add implicit destructor.
4324 if (VarDecl *VD = CS->getExceptionDecl()) {
4325 LocalScope::const_iterator BeginScopePos = ScopePos;
4326 addLocalScopeForVarDecl(VD);
4327 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
4328 }
4329
4330 if (CS->getHandlerBlock())
4331 addStmt(CS->getHandlerBlock());
4332
4333 CFGBlock *CatchBlock = Block;
4334 if (!CatchBlock)
4335 CatchBlock = createBlock();
4336
4337 // CXXCatchStmt is more than just a label. They have semantic meaning
4338 // as well, as they implicitly "initialize" the catch variable. Add
4339 // it to the CFG as a CFGElement so that the control-flow of these
4340 // semantics gets captured.
4341 appendStmt(CatchBlock, CS);
4342
4343 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4344 // labels.
4345 CatchBlock->setLabel(CS);
4346
4347 // Bail out if the CFG is bad.
4348 if (badCFG)
4349 return nullptr;
4350
4351 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4352 Block = nullptr;
4353
4354 return CatchBlock;
4355 }
4356
VisitCXXForRangeStmt(CXXForRangeStmt * S)4357 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4358 // C++0x for-range statements are specified as [stmt.ranged]:
4359 //
4360 // {
4361 // auto && __range = range-init;
4362 // for ( auto __begin = begin-expr,
4363 // __end = end-expr;
4364 // __begin != __end;
4365 // ++__begin ) {
4366 // for-range-declaration = *__begin;
4367 // statement
4368 // }
4369 // }
4370
4371 // Save local scope position before the addition of the implicit variables.
4372 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4373
4374 // Create local scopes and destructors for range, begin and end variables.
4375 if (Stmt *Range = S->getRangeStmt())
4376 addLocalScopeForStmt(Range);
4377 if (Stmt *Begin = S->getBeginStmt())
4378 addLocalScopeForStmt(Begin);
4379 if (Stmt *End = S->getEndStmt())
4380 addLocalScopeForStmt(End);
4381 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
4382
4383 LocalScope::const_iterator ContinueScopePos = ScopePos;
4384
4385 // "for" is a control-flow statement. Thus we stop processing the current
4386 // block.
4387 CFGBlock *LoopSuccessor = nullptr;
4388 if (Block) {
4389 if (badCFG)
4390 return nullptr;
4391 LoopSuccessor = Block;
4392 } else
4393 LoopSuccessor = Succ;
4394
4395 // Save the current value for the break targets.
4396 // All breaks should go to the code following the loop.
4397 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4398 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4399
4400 // The block for the __begin != __end expression.
4401 CFGBlock *ConditionBlock = createBlock(false);
4402 ConditionBlock->setTerminator(S);
4403
4404 // Now add the actual condition to the condition block.
4405 if (Expr *C = S->getCond()) {
4406 Block = ConditionBlock;
4407 CFGBlock *BeginConditionBlock = addStmt(C);
4408 if (badCFG)
4409 return nullptr;
4410 assert(BeginConditionBlock == ConditionBlock &&
4411 "condition block in for-range was unexpectedly complex");
4412 (void)BeginConditionBlock;
4413 }
4414
4415 // The condition block is the implicit successor for the loop body as well as
4416 // any code above the loop.
4417 Succ = ConditionBlock;
4418
4419 // See if this is a known constant.
4420 TryResult KnownVal(true);
4421
4422 if (S->getCond())
4423 KnownVal = tryEvaluateBool(S->getCond());
4424
4425 // Now create the loop body.
4426 {
4427 assert(S->getBody());
4428
4429 // Save the current values for Block, Succ, and continue targets.
4430 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
4431 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
4432
4433 // Generate increment code in its own basic block. This is the target of
4434 // continue statements.
4435 Block = nullptr;
4436 Succ = addStmt(S->getInc());
4437 if (badCFG)
4438 return nullptr;
4439 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4440
4441 // The starting block for the loop increment is the block that should
4442 // represent the 'loop target' for looping back to the start of the loop.
4443 ContinueJumpTarget.block->setLoopTarget(S);
4444
4445 // Finish up the increment block and prepare to start the loop body.
4446 assert(Block);
4447 if (badCFG)
4448 return nullptr;
4449 Block = nullptr;
4450
4451 // Add implicit scope and dtors for loop variable.
4452 addLocalScopeAndDtors(S->getLoopVarStmt());
4453
4454 // Populate a new block to contain the loop body and loop variable.
4455 addStmt(S->getBody());
4456 if (badCFG)
4457 return nullptr;
4458 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
4459 if (badCFG)
4460 return nullptr;
4461
4462 // This new body block is a successor to our condition block.
4463 addSuccessor(ConditionBlock,
4464 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4465 }
4466
4467 // Link up the condition block with the code that follows the loop (the
4468 // false branch).
4469 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4470
4471 // Add the initialization statements.
4472 Block = createBlock();
4473 addStmt(S->getBeginStmt());
4474 addStmt(S->getEndStmt());
4475 CFGBlock *Head = addStmt(S->getRangeStmt());
4476 if (S->getInit())
4477 Head = addStmt(S->getInit());
4478 return Head;
4479 }
4480
VisitExprWithCleanups(ExprWithCleanups * E,AddStmtChoice asc,bool ExternallyDestructed)4481 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4482 AddStmtChoice asc, bool ExternallyDestructed) {
4483 if (BuildOpts.AddTemporaryDtors) {
4484 // If adding implicit destructors visit the full expression for adding
4485 // destructors of temporaries.
4486 TempDtorContext Context;
4487 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
4488
4489 // Full expression has to be added as CFGStmt so it will be sequenced
4490 // before destructors of it's temporaries.
4491 asc = asc.withAlwaysAdd(true);
4492 }
4493 return Visit(E->getSubExpr(), asc);
4494 }
4495
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E,AddStmtChoice asc)4496 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4497 AddStmtChoice asc) {
4498 if (asc.alwaysAdd(*this, E)) {
4499 autoCreateBlock();
4500 appendStmt(Block, E);
4501
4502 findConstructionContexts(
4503 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
4504 E->getSubExpr());
4505
4506 // We do not want to propagate the AlwaysAdd property.
4507 asc = asc.withAlwaysAdd(false);
4508 }
4509 return Visit(E->getSubExpr(), asc);
4510 }
4511
VisitCXXConstructExpr(CXXConstructExpr * C,AddStmtChoice asc)4512 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4513 AddStmtChoice asc) {
4514 // If the constructor takes objects as arguments by value, we need to properly
4515 // construct these objects. Construction contexts we find here aren't for the
4516 // constructor C, they're for its arguments only.
4517 findConstructionContextsForArguments(C);
4518
4519 autoCreateBlock();
4520 appendConstructor(Block, C);
4521
4522 return VisitChildren(C);
4523 }
4524
VisitCXXNewExpr(CXXNewExpr * NE,AddStmtChoice asc)4525 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4526 AddStmtChoice asc) {
4527 autoCreateBlock();
4528 appendStmt(Block, NE);
4529
4530 findConstructionContexts(
4531 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
4532 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
4533
4534 if (NE->getInitializer())
4535 Block = Visit(NE->getInitializer());
4536
4537 if (BuildOpts.AddCXXNewAllocator)
4538 appendNewAllocator(Block, NE);
4539
4540 if (NE->isArray() && *NE->getArraySize())
4541 Block = Visit(*NE->getArraySize());
4542
4543 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4544 E = NE->placement_arg_end(); I != E; ++I)
4545 Block = Visit(*I);
4546
4547 return Block;
4548 }
4549
VisitCXXDeleteExpr(CXXDeleteExpr * DE,AddStmtChoice asc)4550 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4551 AddStmtChoice asc) {
4552 autoCreateBlock();
4553 appendStmt(Block, DE);
4554 QualType DTy = DE->getDestroyedType();
4555 if (!DTy.isNull()) {
4556 DTy = DTy.getNonReferenceType();
4557 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4558 if (RD) {
4559 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4560 appendDeleteDtor(Block, RD, DE);
4561 }
4562 }
4563
4564 return VisitChildren(DE);
4565 }
4566
VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr * E,AddStmtChoice asc)4567 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4568 AddStmtChoice asc) {
4569 if (asc.alwaysAdd(*this, E)) {
4570 autoCreateBlock();
4571 appendStmt(Block, E);
4572 // We do not want to propagate the AlwaysAdd property.
4573 asc = asc.withAlwaysAdd(false);
4574 }
4575 return Visit(E->getSubExpr(), asc);
4576 }
4577
VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr * C,AddStmtChoice asc)4578 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4579 AddStmtChoice asc) {
4580 // If the constructor takes objects as arguments by value, we need to properly
4581 // construct these objects. Construction contexts we find here aren't for the
4582 // constructor C, they're for its arguments only.
4583 findConstructionContextsForArguments(C);
4584
4585 autoCreateBlock();
4586 appendConstructor(Block, C);
4587 return VisitChildren(C);
4588 }
4589
VisitImplicitCastExpr(ImplicitCastExpr * E,AddStmtChoice asc)4590 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4591 AddStmtChoice asc) {
4592 if (asc.alwaysAdd(*this, E)) {
4593 autoCreateBlock();
4594 appendStmt(Block, E);
4595 }
4596
4597 if (E->getCastKind() == CK_IntegralToBoolean)
4598 tryEvaluateBool(E->getSubExpr()->IgnoreParens());
4599
4600 return Visit(E->getSubExpr(), AddStmtChoice());
4601 }
4602
VisitConstantExpr(ConstantExpr * E,AddStmtChoice asc)4603 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4604 return Visit(E->getSubExpr(), AddStmtChoice());
4605 }
4606
VisitIndirectGotoStmt(IndirectGotoStmt * I)4607 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4608 // Lazily create the indirect-goto dispatch block if there isn't one already.
4609 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
4610
4611 if (!IBlock) {
4612 IBlock = createBlock(false);
4613 cfg->setIndirectGotoBlock(IBlock);
4614 }
4615
4616 // IndirectGoto is a control-flow statement. Thus we stop processing the
4617 // current block and create a new one.
4618 if (badCFG)
4619 return nullptr;
4620
4621 Block = createBlock(false);
4622 Block->setTerminator(I);
4623 addSuccessor(Block, IBlock);
4624 return addStmt(I->getTarget());
4625 }
4626
VisitForTemporaryDtors(Stmt * E,bool ExternallyDestructed,TempDtorContext & Context)4627 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
4628 TempDtorContext &Context) {
4629 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4630
4631 tryAgain:
4632 if (!E) {
4633 badCFG = true;
4634 return nullptr;
4635 }
4636 switch (E->getStmtClass()) {
4637 default:
4638 return VisitChildrenForTemporaryDtors(E, false, Context);
4639
4640 case Stmt::InitListExprClass:
4641 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
4642
4643 case Stmt::BinaryOperatorClass:
4644 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4645 ExternallyDestructed,
4646 Context);
4647
4648 case Stmt::CXXBindTemporaryExprClass:
4649 return VisitCXXBindTemporaryExprForTemporaryDtors(
4650 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
4651
4652 case Stmt::BinaryConditionalOperatorClass:
4653 case Stmt::ConditionalOperatorClass:
4654 return VisitConditionalOperatorForTemporaryDtors(
4655 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
4656
4657 case Stmt::ImplicitCastExprClass:
4658 // For implicit cast we want ExternallyDestructed to be passed further.
4659 E = cast<CastExpr>(E)->getSubExpr();
4660 goto tryAgain;
4661
4662 case Stmt::CXXFunctionalCastExprClass:
4663 // For functional cast we want ExternallyDestructed to be passed further.
4664 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4665 goto tryAgain;
4666
4667 case Stmt::ConstantExprClass:
4668 E = cast<ConstantExpr>(E)->getSubExpr();
4669 goto tryAgain;
4670
4671 case Stmt::ParenExprClass:
4672 E = cast<ParenExpr>(E)->getSubExpr();
4673 goto tryAgain;
4674
4675 case Stmt::MaterializeTemporaryExprClass: {
4676 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4677 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
4678 SmallVector<const Expr *, 2> CommaLHSs;
4679 SmallVector<SubobjectAdjustment, 2> Adjustments;
4680 // Find the expression whose lifetime needs to be extended.
4681 E = const_cast<Expr *>(
4682 cast<MaterializeTemporaryExpr>(E)
4683 ->getSubExpr()
4684 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4685 // Visit the skipped comma operator left-hand sides for other temporaries.
4686 for (const Expr *CommaLHS : CommaLHSs) {
4687 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
4688 /*ExternallyDestructed=*/false, Context);
4689 }
4690 goto tryAgain;
4691 }
4692
4693 case Stmt::BlockExprClass:
4694 // Don't recurse into blocks; their subexpressions don't get evaluated
4695 // here.
4696 return Block;
4697
4698 case Stmt::LambdaExprClass: {
4699 // For lambda expressions, only recurse into the capture initializers,
4700 // and not the body.
4701 auto *LE = cast<LambdaExpr>(E);
4702 CFGBlock *B = Block;
4703 for (Expr *Init : LE->capture_inits()) {
4704 if (Init) {
4705 if (CFGBlock *R = VisitForTemporaryDtors(
4706 Init, /*ExternallyDestructed=*/true, Context))
4707 B = R;
4708 }
4709 }
4710 return B;
4711 }
4712
4713 case Stmt::StmtExprClass:
4714 // Don't recurse into statement expressions; any cleanups inside them
4715 // will be wrapped in their own ExprWithCleanups.
4716 return Block;
4717
4718 case Stmt::CXXDefaultArgExprClass:
4719 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4720 goto tryAgain;
4721
4722 case Stmt::CXXDefaultInitExprClass:
4723 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4724 goto tryAgain;
4725 }
4726 }
4727
VisitChildrenForTemporaryDtors(Stmt * E,bool ExternallyDestructed,TempDtorContext & Context)4728 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4729 bool ExternallyDestructed,
4730 TempDtorContext &Context) {
4731 if (isa<LambdaExpr>(E)) {
4732 // Do not visit the children of lambdas; they have their own CFGs.
4733 return Block;
4734 }
4735
4736 // When visiting children for destructors we want to visit them in reverse
4737 // order that they will appear in the CFG. Because the CFG is built
4738 // bottom-up, this means we visit them in their natural order, which
4739 // reverses them in the CFG.
4740 CFGBlock *B = Block;
4741 for (Stmt *Child : E->children())
4742 if (Child)
4743 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
4744 B = R;
4745
4746 return B;
4747 }
4748
VisitBinaryOperatorForTemporaryDtors(BinaryOperator * E,bool ExternallyDestructed,TempDtorContext & Context)4749 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4750 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
4751 if (E->isCommaOp()) {
4752 // For comma operator LHS expression is visited
4753 // before RHS expression. For destructors visit them in reverse order.
4754 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
4755 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4756 return LHSBlock ? LHSBlock : RHSBlock;
4757 }
4758
4759 if (E->isLogicalOp()) {
4760 VisitForTemporaryDtors(E->getLHS(), false, Context);
4761 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4762 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4763 RHSExecuted.negate();
4764
4765 // We do not know at CFG-construction time whether the right-hand-side was
4766 // executed, thus we add a branch node that depends on the temporary
4767 // constructor call.
4768 TempDtorContext RHSContext(
4769 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
4770 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
4771 InsertTempDtorDecisionBlock(RHSContext);
4772
4773 return Block;
4774 }
4775
4776 if (E->isAssignmentOp()) {
4777 // For assignment operator (=) LHS expression is visited
4778 // before RHS expression. For destructors visit them in reverse order.
4779 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4780 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4781 return LHSBlock ? LHSBlock : RHSBlock;
4782 }
4783
4784 // For any other binary operator RHS expression is visited before
4785 // LHS expression (order of children). For destructors visit them in reverse
4786 // order.
4787 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4788 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4789 return RHSBlock ? RHSBlock : LHSBlock;
4790 }
4791
VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr * E,bool ExternallyDestructed,TempDtorContext & Context)4792 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
4793 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
4794 // First add destructors for temporaries in subexpression.
4795 // Because VisitCXXBindTemporaryExpr calls setDestructed:
4796 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
4797 if (!ExternallyDestructed) {
4798 // If lifetime of temporary is not prolonged (by assigning to constant
4799 // reference) add destructor for it.
4800
4801 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
4802
4803 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
4804 // If the destructor is marked as a no-return destructor, we need to
4805 // create a new block for the destructor which does not have as a
4806 // successor anything built thus far. Control won't flow out of this
4807 // block.
4808 if (B) Succ = B;
4809 Block = createNoReturnBlock();
4810 } else if (Context.needsTempDtorBranch()) {
4811 // If we need to introduce a branch, we add a new block that we will hook
4812 // up to a decision block later.
4813 if (B) Succ = B;
4814 Block = createBlock();
4815 } else {
4816 autoCreateBlock();
4817 }
4818 if (Context.needsTempDtorBranch()) {
4819 Context.setDecisionPoint(Succ, E);
4820 }
4821 appendTemporaryDtor(Block, E);
4822
4823 B = Block;
4824 }
4825 return B;
4826 }
4827
InsertTempDtorDecisionBlock(const TempDtorContext & Context,CFGBlock * FalseSucc)4828 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4829 CFGBlock *FalseSucc) {
4830 if (!Context.TerminatorExpr) {
4831 // If no temporary was found, we do not need to insert a decision point.
4832 return;
4833 }
4834 assert(Context.TerminatorExpr);
4835 CFGBlock *Decision = createBlock(false);
4836 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
4837 CFGTerminator::TemporaryDtorsBranch));
4838 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
4839 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
4840 !Context.KnownExecuted.isTrue());
4841 Block = Decision;
4842 }
4843
VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator * E,bool ExternallyDestructed,TempDtorContext & Context)4844 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
4845 AbstractConditionalOperator *E, bool ExternallyDestructed,
4846 TempDtorContext &Context) {
4847 VisitForTemporaryDtors(E->getCond(), false, Context);
4848 CFGBlock *ConditionBlock = Block;
4849 CFGBlock *ConditionSucc = Succ;
4850 TryResult ConditionVal = tryEvaluateBool(E->getCond());
4851 TryResult NegatedVal = ConditionVal;
4852 if (NegatedVal.isKnown()) NegatedVal.negate();
4853
4854 TempDtorContext TrueContext(
4855 bothKnownTrue(Context.KnownExecuted, ConditionVal));
4856 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
4857 CFGBlock *TrueBlock = Block;
4858
4859 Block = ConditionBlock;
4860 Succ = ConditionSucc;
4861 TempDtorContext FalseContext(
4862 bothKnownTrue(Context.KnownExecuted, NegatedVal));
4863 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
4864
4865 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
4866 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
4867 } else if (TrueContext.TerminatorExpr) {
4868 Block = TrueBlock;
4869 InsertTempDtorDecisionBlock(TrueContext);
4870 } else {
4871 InsertTempDtorDecisionBlock(FalseContext);
4872 }
4873 return Block;
4874 }
4875
VisitOMPExecutableDirective(OMPExecutableDirective * D,AddStmtChoice asc)4876 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
4877 AddStmtChoice asc) {
4878 if (asc.alwaysAdd(*this, D)) {
4879 autoCreateBlock();
4880 appendStmt(Block, D);
4881 }
4882
4883 // Iterate over all used expression in clauses.
4884 CFGBlock *B = Block;
4885
4886 // Reverse the elements to process them in natural order. Iterators are not
4887 // bidirectional, so we need to create temp vector.
4888 SmallVector<Stmt *, 8> Used(
4889 OMPExecutableDirective::used_clauses_children(D->clauses()));
4890 for (Stmt *S : llvm::reverse(Used)) {
4891 assert(S && "Expected non-null used-in-clause child.");
4892 if (CFGBlock *R = Visit(S))
4893 B = R;
4894 }
4895 // Visit associated structured block if any.
4896 if (!D->isStandaloneDirective())
4897 if (CapturedStmt *CS = D->getInnermostCapturedStmt()) {
4898 Stmt *S = CS->getCapturedStmt();
4899 if (!isa<CompoundStmt>(S))
4900 addLocalScopeAndDtors(S);
4901 if (CFGBlock *R = addStmt(S))
4902 B = R;
4903 }
4904
4905 return B;
4906 }
4907
4908 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4909 /// no successors or predecessors. If this is the first block created in the
4910 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
createBlock()4911 CFGBlock *CFG::createBlock() {
4912 bool first_block = begin() == end();
4913
4914 // Create the block.
4915 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
4916 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
4917 Blocks.push_back(Mem, BlkBVC);
4918
4919 // If this is the first block, set it as the Entry and Exit.
4920 if (first_block)
4921 Entry = Exit = &back();
4922
4923 // Return the block.
4924 return &back();
4925 }
4926
4927 /// buildCFG - Constructs a CFG from an AST.
buildCFG(const Decl * D,Stmt * Statement,ASTContext * C,const BuildOptions & BO)4928 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4929 ASTContext *C, const BuildOptions &BO) {
4930 CFGBuilder Builder(C, BO);
4931 return Builder.buildCFG(D, Statement);
4932 }
4933
isLinear() const4934 bool CFG::isLinear() const {
4935 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
4936 // in between, then we have no room for control flow.
4937 if (size() <= 3)
4938 return true;
4939
4940 // Traverse the CFG until we find a branch.
4941 // TODO: While this should still be very fast,
4942 // maybe we should cache the answer.
4943 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
4944 const CFGBlock *B = Entry;
4945 while (B != Exit) {
4946 auto IteratorAndFlag = Visited.insert(B);
4947 if (!IteratorAndFlag.second) {
4948 // We looped back to a block that we've already visited. Not linear.
4949 return false;
4950 }
4951
4952 // Iterate over reachable successors.
4953 const CFGBlock *FirstReachableB = nullptr;
4954 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
4955 if (!AB.isReachable())
4956 continue;
4957
4958 if (FirstReachableB == nullptr) {
4959 FirstReachableB = &*AB;
4960 } else {
4961 // We've encountered a branch. It's not a linear CFG.
4962 return false;
4963 }
4964 }
4965
4966 if (!FirstReachableB) {
4967 // We reached a dead end. EXIT is unreachable. This is linear enough.
4968 return true;
4969 }
4970
4971 // There's only one way to move forward. Proceed.
4972 B = FirstReachableB;
4973 }
4974
4975 // We reached EXIT and found no branches.
4976 return true;
4977 }
4978
4979 const CXXDestructorDecl *
getDestructorDecl(ASTContext & astContext) const4980 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
4981 switch (getKind()) {
4982 case CFGElement::Initializer:
4983 case CFGElement::NewAllocator:
4984 case CFGElement::LoopExit:
4985 case CFGElement::LifetimeEnds:
4986 case CFGElement::Statement:
4987 case CFGElement::Constructor:
4988 case CFGElement::CXXRecordTypedCall:
4989 case CFGElement::ScopeBegin:
4990 case CFGElement::ScopeEnd:
4991 llvm_unreachable("getDestructorDecl should only be used with "
4992 "ImplicitDtors");
4993 case CFGElement::AutomaticObjectDtor: {
4994 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
4995 QualType ty = var->getType();
4996
4997 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4998 //
4999 // Lifetime-extending constructs are handled here. This works for a single
5000 // temporary in an initializer expression.
5001 if (ty->isReferenceType()) {
5002 if (const Expr *Init = var->getInit()) {
5003 ty = getReferenceInitTemporaryType(Init);
5004 }
5005 }
5006
5007 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5008 ty = arrayType->getElementType();
5009 }
5010
5011 // The situation when the type of the lifetime-extending reference
5012 // does not correspond to the type of the object is supposed
5013 // to be handled by now. In particular, 'ty' is now the unwrapped
5014 // record type.
5015 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5016 assert(classDecl);
5017 return classDecl->getDestructor();
5018 }
5019 case CFGElement::DeleteDtor: {
5020 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
5021 QualType DTy = DE->getDestroyedType();
5022 DTy = DTy.getNonReferenceType();
5023 const CXXRecordDecl *classDecl =
5024 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
5025 return classDecl->getDestructor();
5026 }
5027 case CFGElement::TemporaryDtor: {
5028 const CXXBindTemporaryExpr *bindExpr =
5029 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5030 const CXXTemporary *temp = bindExpr->getTemporary();
5031 return temp->getDestructor();
5032 }
5033 case CFGElement::BaseDtor:
5034 case CFGElement::MemberDtor:
5035 // Not yet supported.
5036 return nullptr;
5037 }
5038 llvm_unreachable("getKind() returned bogus value");
5039 }
5040
5041 //===----------------------------------------------------------------------===//
5042 // CFGBlock operations.
5043 //===----------------------------------------------------------------------===//
5044
AdjacentBlock(CFGBlock * B,bool IsReachable)5045 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
5046 : ReachableBlock(IsReachable ? B : nullptr),
5047 UnreachableBlock(!IsReachable ? B : nullptr,
5048 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5049
AdjacentBlock(CFGBlock * B,CFGBlock * AlternateBlock)5050 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
5051 : ReachableBlock(B),
5052 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5053 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5054
addSuccessor(AdjacentBlock Succ,BumpVectorContext & C)5055 void CFGBlock::addSuccessor(AdjacentBlock Succ,
5056 BumpVectorContext &C) {
5057 if (CFGBlock *B = Succ.getReachableBlock())
5058 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
5059
5060 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5061 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
5062
5063 Succs.push_back(Succ, C);
5064 }
5065
FilterEdge(const CFGBlock::FilterOptions & F,const CFGBlock * From,const CFGBlock * To)5066 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
5067 const CFGBlock *From, const CFGBlock *To) {
5068 if (F.IgnoreNullPredecessors && !From)
5069 return true;
5070
5071 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5072 // If the 'To' has no label or is labeled but the label isn't a
5073 // CaseStmt then filter this edge.
5074 if (const SwitchStmt *S =
5075 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
5076 if (S->isAllEnumCasesCovered()) {
5077 const Stmt *L = To->getLabel();
5078 if (!L || !isa<CaseStmt>(L))
5079 return true;
5080 }
5081 }
5082 }
5083
5084 return false;
5085 }
5086
5087 //===----------------------------------------------------------------------===//
5088 // CFG pretty printing
5089 //===----------------------------------------------------------------------===//
5090
5091 namespace {
5092
5093 class StmtPrinterHelper : public PrinterHelper {
5094 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5095 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5096
5097 StmtMapTy StmtMap;
5098 DeclMapTy DeclMap;
5099 signed currentBlock = 0;
5100 unsigned currStmt = 0;
5101 const LangOptions &LangOpts;
5102
5103 public:
StmtPrinterHelper(const CFG * cfg,const LangOptions & LO)5104 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5105 : LangOpts(LO) {
5106 if (!cfg)
5107 return;
5108 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5109 unsigned j = 1;
5110 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5111 BI != BEnd; ++BI, ++j ) {
5112 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5113 const Stmt *stmt= SE->getStmt();
5114 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5115 StmtMap[stmt] = P;
5116
5117 switch (stmt->getStmtClass()) {
5118 case Stmt::DeclStmtClass:
5119 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
5120 break;
5121 case Stmt::IfStmtClass: {
5122 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
5123 if (var)
5124 DeclMap[var] = P;
5125 break;
5126 }
5127 case Stmt::ForStmtClass: {
5128 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
5129 if (var)
5130 DeclMap[var] = P;
5131 break;
5132 }
5133 case Stmt::WhileStmtClass: {
5134 const VarDecl *var =
5135 cast<WhileStmt>(stmt)->getConditionVariable();
5136 if (var)
5137 DeclMap[var] = P;
5138 break;
5139 }
5140 case Stmt::SwitchStmtClass: {
5141 const VarDecl *var =
5142 cast<SwitchStmt>(stmt)->getConditionVariable();
5143 if (var)
5144 DeclMap[var] = P;
5145 break;
5146 }
5147 case Stmt::CXXCatchStmtClass: {
5148 const VarDecl *var =
5149 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5150 if (var)
5151 DeclMap[var] = P;
5152 break;
5153 }
5154 default:
5155 break;
5156 }
5157 }
5158 }
5159 }
5160 }
5161
5162 ~StmtPrinterHelper() override = default;
5163
getLangOpts() const5164 const LangOptions &getLangOpts() const { return LangOpts; }
setBlockID(signed i)5165 void setBlockID(signed i) { currentBlock = i; }
setStmtID(unsigned i)5166 void setStmtID(unsigned i) { currStmt = i; }
5167
handledStmt(Stmt * S,raw_ostream & OS)5168 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5169 StmtMapTy::iterator I = StmtMap.find(S);
5170
5171 if (I == StmtMap.end())
5172 return false;
5173
5174 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5175 && I->second.second == currStmt) {
5176 return false;
5177 }
5178
5179 OS << "[B" << I->second.first << "." << I->second.second << "]";
5180 return true;
5181 }
5182
handleDecl(const Decl * D,raw_ostream & OS)5183 bool handleDecl(const Decl *D, raw_ostream &OS) {
5184 DeclMapTy::iterator I = DeclMap.find(D);
5185
5186 if (I == DeclMap.end())
5187 return false;
5188
5189 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5190 && I->second.second == currStmt) {
5191 return false;
5192 }
5193
5194 OS << "[B" << I->second.first << "." << I->second.second << "]";
5195 return true;
5196 }
5197 };
5198
5199 class CFGBlockTerminatorPrint
5200 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5201 raw_ostream &OS;
5202 StmtPrinterHelper* Helper;
5203 PrintingPolicy Policy;
5204
5205 public:
CFGBlockTerminatorPrint(raw_ostream & os,StmtPrinterHelper * helper,const PrintingPolicy & Policy)5206 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5207 const PrintingPolicy &Policy)
5208 : OS(os), Helper(helper), Policy(Policy) {
5209 this->Policy.IncludeNewlines = false;
5210 }
5211
VisitIfStmt(IfStmt * I)5212 void VisitIfStmt(IfStmt *I) {
5213 OS << "if ";
5214 if (Stmt *C = I->getCond())
5215 C->printPretty(OS, Helper, Policy);
5216 }
5217
5218 // Default case.
VisitStmt(Stmt * Terminator)5219 void VisitStmt(Stmt *Terminator) {
5220 Terminator->printPretty(OS, Helper, Policy);
5221 }
5222
VisitDeclStmt(DeclStmt * DS)5223 void VisitDeclStmt(DeclStmt *DS) {
5224 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5225 OS << "static init " << VD->getName();
5226 }
5227
VisitForStmt(ForStmt * F)5228 void VisitForStmt(ForStmt *F) {
5229 OS << "for (" ;
5230 if (F->getInit())
5231 OS << "...";
5232 OS << "; ";
5233 if (Stmt *C = F->getCond())
5234 C->printPretty(OS, Helper, Policy);
5235 OS << "; ";
5236 if (F->getInc())
5237 OS << "...";
5238 OS << ")";
5239 }
5240
VisitWhileStmt(WhileStmt * W)5241 void VisitWhileStmt(WhileStmt *W) {
5242 OS << "while " ;
5243 if (Stmt *C = W->getCond())
5244 C->printPretty(OS, Helper, Policy);
5245 }
5246
VisitDoStmt(DoStmt * D)5247 void VisitDoStmt(DoStmt *D) {
5248 OS << "do ... while ";
5249 if (Stmt *C = D->getCond())
5250 C->printPretty(OS, Helper, Policy);
5251 }
5252
VisitSwitchStmt(SwitchStmt * Terminator)5253 void VisitSwitchStmt(SwitchStmt *Terminator) {
5254 OS << "switch ";
5255 Terminator->getCond()->printPretty(OS, Helper, Policy);
5256 }
5257
VisitCXXTryStmt(CXXTryStmt * CS)5258 void VisitCXXTryStmt(CXXTryStmt *CS) {
5259 OS << "try ...";
5260 }
5261
VisitSEHTryStmt(SEHTryStmt * CS)5262 void VisitSEHTryStmt(SEHTryStmt *CS) {
5263 OS << "__try ...";
5264 }
5265
VisitAbstractConditionalOperator(AbstractConditionalOperator * C)5266 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5267 if (Stmt *Cond = C->getCond())
5268 Cond->printPretty(OS, Helper, Policy);
5269 OS << " ? ... : ...";
5270 }
5271
VisitChooseExpr(ChooseExpr * C)5272 void VisitChooseExpr(ChooseExpr *C) {
5273 OS << "__builtin_choose_expr( ";
5274 if (Stmt *Cond = C->getCond())
5275 Cond->printPretty(OS, Helper, Policy);
5276 OS << " )";
5277 }
5278
VisitIndirectGotoStmt(IndirectGotoStmt * I)5279 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5280 OS << "goto *";
5281 if (Stmt *T = I->getTarget())
5282 T->printPretty(OS, Helper, Policy);
5283 }
5284
VisitBinaryOperator(BinaryOperator * B)5285 void VisitBinaryOperator(BinaryOperator* B) {
5286 if (!B->isLogicalOp()) {
5287 VisitExpr(B);
5288 return;
5289 }
5290
5291 if (B->getLHS())
5292 B->getLHS()->printPretty(OS, Helper, Policy);
5293
5294 switch (B->getOpcode()) {
5295 case BO_LOr:
5296 OS << " || ...";
5297 return;
5298 case BO_LAnd:
5299 OS << " && ...";
5300 return;
5301 default:
5302 llvm_unreachable("Invalid logical operator.");
5303 }
5304 }
5305
VisitExpr(Expr * E)5306 void VisitExpr(Expr *E) {
5307 E->printPretty(OS, Helper, Policy);
5308 }
5309
5310 public:
print(CFGTerminator T)5311 void print(CFGTerminator T) {
5312 switch (T.getKind()) {
5313 case CFGTerminator::StmtBranch:
5314 Visit(T.getStmt());
5315 break;
5316 case CFGTerminator::TemporaryDtorsBranch:
5317 OS << "(Temp Dtor) ";
5318 Visit(T.getStmt());
5319 break;
5320 case CFGTerminator::VirtualBaseBranch:
5321 OS << "(See if most derived ctor has already initialized vbases)";
5322 break;
5323 }
5324 }
5325 };
5326
5327 } // namespace
5328
print_initializer(raw_ostream & OS,StmtPrinterHelper & Helper,const CXXCtorInitializer * I)5329 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5330 const CXXCtorInitializer *I) {
5331 if (I->isBaseInitializer())
5332 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5333 else if (I->isDelegatingInitializer())
5334 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5335 else
5336 OS << I->getAnyMember()->getName();
5337 OS << "(";
5338 if (Expr *IE = I->getInit())
5339 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5340 OS << ")";
5341
5342 if (I->isBaseInitializer())
5343 OS << " (Base initializer)";
5344 else if (I->isDelegatingInitializer())
5345 OS << " (Delegating initializer)";
5346 else
5347 OS << " (Member initializer)";
5348 }
5349
print_construction_context(raw_ostream & OS,StmtPrinterHelper & Helper,const ConstructionContext * CC)5350 static void print_construction_context(raw_ostream &OS,
5351 StmtPrinterHelper &Helper,
5352 const ConstructionContext *CC) {
5353 SmallVector<const Stmt *, 3> Stmts;
5354 switch (CC->getKind()) {
5355 case ConstructionContext::SimpleConstructorInitializerKind: {
5356 OS << ", ";
5357 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5358 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5359 return;
5360 }
5361 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5362 OS << ", ";
5363 const auto *CICC =
5364 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5365 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
5366 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5367 break;
5368 }
5369 case ConstructionContext::SimpleVariableKind: {
5370 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
5371 Stmts.push_back(SDSCC->getDeclStmt());
5372 break;
5373 }
5374 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5375 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
5376 Stmts.push_back(CDSCC->getDeclStmt());
5377 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5378 break;
5379 }
5380 case ConstructionContext::NewAllocatedObjectKind: {
5381 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
5382 Stmts.push_back(NECC->getCXXNewExpr());
5383 break;
5384 }
5385 case ConstructionContext::SimpleReturnedValueKind: {
5386 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
5387 Stmts.push_back(RSCC->getReturnStmt());
5388 break;
5389 }
5390 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5391 const auto *RSCC =
5392 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
5393 Stmts.push_back(RSCC->getReturnStmt());
5394 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5395 break;
5396 }
5397 case ConstructionContext::SimpleTemporaryObjectKind: {
5398 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5399 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5400 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5401 break;
5402 }
5403 case ConstructionContext::ElidedTemporaryObjectKind: {
5404 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5405 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5406 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5407 Stmts.push_back(TOCC->getConstructorAfterElision());
5408 break;
5409 }
5410 case ConstructionContext::ArgumentKind: {
5411 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5412 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5413 OS << ", ";
5414 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5415 }
5416 OS << ", ";
5417 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5418 OS << "+" << ACC->getIndex();
5419 return;
5420 }
5421 }
5422 for (auto I: Stmts)
5423 if (I) {
5424 OS << ", ";
5425 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5426 }
5427 }
5428
5429 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5430 const CFGElement &E);
5431
dumpToStream(llvm::raw_ostream & OS) const5432 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
5433 StmtPrinterHelper Helper(nullptr, {});
5434 print_elem(OS, Helper, *this);
5435 }
5436
print_elem(raw_ostream & OS,StmtPrinterHelper & Helper,const CFGElement & E)5437 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5438 const CFGElement &E) {
5439 switch (E.getKind()) {
5440 case CFGElement::Kind::Statement:
5441 case CFGElement::Kind::CXXRecordTypedCall:
5442 case CFGElement::Kind::Constructor: {
5443 CFGStmt CS = E.castAs<CFGStmt>();
5444 const Stmt *S = CS.getStmt();
5445 assert(S != nullptr && "Expecting non-null Stmt");
5446
5447 // special printing for statement-expressions.
5448 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5449 const CompoundStmt *Sub = SE->getSubStmt();
5450
5451 auto Children = Sub->children();
5452 if (Children.begin() != Children.end()) {
5453 OS << "({ ... ; ";
5454 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5455 OS << " })\n";
5456 return;
5457 }
5458 }
5459 // special printing for comma expressions.
5460 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5461 if (B->getOpcode() == BO_Comma) {
5462 OS << "... , ";
5463 Helper.handledStmt(B->getRHS(),OS);
5464 OS << '\n';
5465 return;
5466 }
5467 }
5468 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5469
5470 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5471 if (isa<CXXOperatorCallExpr>(S))
5472 OS << " (OperatorCall)";
5473 OS << " (CXXRecordTypedCall";
5474 print_construction_context(OS, Helper, VTC->getConstructionContext());
5475 OS << ")";
5476 } else if (isa<CXXOperatorCallExpr>(S)) {
5477 OS << " (OperatorCall)";
5478 } else if (isa<CXXBindTemporaryExpr>(S)) {
5479 OS << " (BindTemporary)";
5480 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
5481 OS << " (CXXConstructExpr";
5482 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
5483 print_construction_context(OS, Helper, CE->getConstructionContext());
5484 }
5485 OS << ", " << CCE->getType().getAsString() << ")";
5486 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
5487 OS << " (" << CE->getStmtClassName() << ", "
5488 << CE->getCastKindName()
5489 << ", " << CE->getType().getAsString()
5490 << ")";
5491 }
5492
5493 // Expressions need a newline.
5494 if (isa<Expr>(S))
5495 OS << '\n';
5496
5497 break;
5498 }
5499
5500 case CFGElement::Kind::Initializer:
5501 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
5502 OS << '\n';
5503 break;
5504
5505 case CFGElement::Kind::AutomaticObjectDtor: {
5506 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
5507 const VarDecl *VD = DE.getVarDecl();
5508 Helper.handleDecl(VD, OS);
5509
5510 QualType T = VD->getType();
5511 if (T->isReferenceType())
5512 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5513
5514 OS << ".~";
5515 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5516 OS << "() (Implicit destructor)\n";
5517 break;
5518 }
5519
5520 case CFGElement::Kind::LifetimeEnds:
5521 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
5522 OS << " (Lifetime ends)\n";
5523 break;
5524
5525 case CFGElement::Kind::LoopExit:
5526 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
5527 break;
5528
5529 case CFGElement::Kind::ScopeBegin:
5530 OS << "CFGScopeBegin(";
5531 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
5532 OS << VD->getQualifiedNameAsString();
5533 OS << ")\n";
5534 break;
5535
5536 case CFGElement::Kind::ScopeEnd:
5537 OS << "CFGScopeEnd(";
5538 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
5539 OS << VD->getQualifiedNameAsString();
5540 OS << ")\n";
5541 break;
5542
5543 case CFGElement::Kind::NewAllocator:
5544 OS << "CFGNewAllocator(";
5545 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
5546 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5547 OS << ")\n";
5548 break;
5549
5550 case CFGElement::Kind::DeleteDtor: {
5551 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
5552 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
5553 if (!RD)
5554 return;
5555 CXXDeleteExpr *DelExpr =
5556 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
5557 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
5558 OS << "->~" << RD->getName().str() << "()";
5559 OS << " (Implicit destructor)\n";
5560 break;
5561 }
5562
5563 case CFGElement::Kind::BaseDtor: {
5564 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
5565 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
5566 OS << " (Base object destructor)\n";
5567 break;
5568 }
5569
5570 case CFGElement::Kind::MemberDtor: {
5571 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
5572 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
5573 OS << "this->" << FD->getName();
5574 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
5575 OS << " (Member object destructor)\n";
5576 break;
5577 }
5578
5579 case CFGElement::Kind::TemporaryDtor: {
5580 const CXXBindTemporaryExpr *BT = E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5581 OS << "~";
5582 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5583 OS << "() (Temporary object destructor)\n";
5584 break;
5585 }
5586 }
5587 }
5588
print_block(raw_ostream & OS,const CFG * cfg,const CFGBlock & B,StmtPrinterHelper & Helper,bool print_edges,bool ShowColors)5589 static void print_block(raw_ostream &OS, const CFG* cfg,
5590 const CFGBlock &B,
5591 StmtPrinterHelper &Helper, bool print_edges,
5592 bool ShowColors) {
5593 Helper.setBlockID(B.getBlockID());
5594
5595 // Print the header.
5596 if (ShowColors)
5597 OS.changeColor(raw_ostream::YELLOW, true);
5598
5599 OS << "\n [B" << B.getBlockID();
5600
5601 if (&B == &cfg->getEntry())
5602 OS << " (ENTRY)]\n";
5603 else if (&B == &cfg->getExit())
5604 OS << " (EXIT)]\n";
5605 else if (&B == cfg->getIndirectGotoBlock())
5606 OS << " (INDIRECT GOTO DISPATCH)]\n";
5607 else if (B.hasNoReturnElement())
5608 OS << " (NORETURN)]\n";
5609 else
5610 OS << "]\n";
5611
5612 if (ShowColors)
5613 OS.resetColor();
5614
5615 // Print the label of this block.
5616 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
5617 if (print_edges)
5618 OS << " ";
5619
5620 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
5621 OS << L->getName();
5622 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
5623 OS << "case ";
5624 if (C->getLHS())
5625 C->getLHS()->printPretty(OS, &Helper,
5626 PrintingPolicy(Helper.getLangOpts()));
5627 if (C->getRHS()) {
5628 OS << " ... ";
5629 C->getRHS()->printPretty(OS, &Helper,
5630 PrintingPolicy(Helper.getLangOpts()));
5631 }
5632 } else if (isa<DefaultStmt>(Label))
5633 OS << "default";
5634 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
5635 OS << "catch (";
5636 if (CS->getExceptionDecl())
5637 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
5638 0);
5639 else
5640 OS << "...";
5641 OS << ")";
5642 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5643 OS << "__except (";
5644 ES->getFilterExpr()->printPretty(OS, &Helper,
5645 PrintingPolicy(Helper.getLangOpts()), 0);
5646 OS << ")";
5647 } else
5648 llvm_unreachable("Invalid label statement in CFGBlock.");
5649
5650 OS << ":\n";
5651 }
5652
5653 // Iterate through the statements in the block and print them.
5654 unsigned j = 1;
5655
5656 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5657 I != E ; ++I, ++j ) {
5658 // Print the statement # in the basic block and the statement itself.
5659 if (print_edges)
5660 OS << " ";
5661
5662 OS << llvm::format("%3d", j) << ": ";
5663
5664 Helper.setStmtID(j);
5665
5666 print_elem(OS, Helper, *I);
5667 }
5668
5669 // Print the terminator of this block.
5670 if (B.getTerminator().isValid()) {
5671 if (ShowColors)
5672 OS.changeColor(raw_ostream::GREEN);
5673
5674 OS << " T: ";
5675
5676 Helper.setBlockID(-1);
5677
5678 PrintingPolicy PP(Helper.getLangOpts());
5679 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
5680 TPrinter.print(B.getTerminator());
5681 OS << '\n';
5682
5683 if (ShowColors)
5684 OS.resetColor();
5685 }
5686
5687 if (print_edges) {
5688 // Print the predecessors of this block.
5689 if (!B.pred_empty()) {
5690 const raw_ostream::Colors Color = raw_ostream::BLUE;
5691 if (ShowColors)
5692 OS.changeColor(Color);
5693 OS << " Preds " ;
5694 if (ShowColors)
5695 OS.resetColor();
5696 OS << '(' << B.pred_size() << "):";
5697 unsigned i = 0;
5698
5699 if (ShowColors)
5700 OS.changeColor(Color);
5701
5702 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
5703 I != E; ++I, ++i) {
5704 if (i % 10 == 8)
5705 OS << "\n ";
5706
5707 CFGBlock *B = *I;
5708 bool Reachable = true;
5709 if (!B) {
5710 Reachable = false;
5711 B = I->getPossiblyUnreachableBlock();
5712 }
5713
5714 OS << " B" << B->getBlockID();
5715 if (!Reachable)
5716 OS << "(Unreachable)";
5717 }
5718
5719 if (ShowColors)
5720 OS.resetColor();
5721
5722 OS << '\n';
5723 }
5724
5725 // Print the successors of this block.
5726 if (!B.succ_empty()) {
5727 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
5728 if (ShowColors)
5729 OS.changeColor(Color);
5730 OS << " Succs ";
5731 if (ShowColors)
5732 OS.resetColor();
5733 OS << '(' << B.succ_size() << "):";
5734 unsigned i = 0;
5735
5736 if (ShowColors)
5737 OS.changeColor(Color);
5738
5739 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
5740 I != E; ++I, ++i) {
5741 if (i % 10 == 8)
5742 OS << "\n ";
5743
5744 CFGBlock *B = *I;
5745
5746 bool Reachable = true;
5747 if (!B) {
5748 Reachable = false;
5749 B = I->getPossiblyUnreachableBlock();
5750 }
5751
5752 if (B) {
5753 OS << " B" << B->getBlockID();
5754 if (!Reachable)
5755 OS << "(Unreachable)";
5756 }
5757 else {
5758 OS << " NULL";
5759 }
5760 }
5761
5762 if (ShowColors)
5763 OS.resetColor();
5764 OS << '\n';
5765 }
5766 }
5767 }
5768
5769 /// dump - A simple pretty printer of a CFG that outputs to stderr.
dump(const LangOptions & LO,bool ShowColors) const5770 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
5771 print(llvm::errs(), LO, ShowColors);
5772 }
5773
5774 /// print - A simple pretty printer of a CFG that outputs to an ostream.
print(raw_ostream & OS,const LangOptions & LO,bool ShowColors) const5775 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
5776 StmtPrinterHelper Helper(this, LO);
5777
5778 // Print the entry block.
5779 print_block(OS, this, getEntry(), Helper, true, ShowColors);
5780
5781 // Iterate through the CFGBlocks and print them one by one.
5782 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5783 // Skip the entry block, because we already printed it.
5784 if (&(**I) == &getEntry() || &(**I) == &getExit())
5785 continue;
5786
5787 print_block(OS, this, **I, Helper, true, ShowColors);
5788 }
5789
5790 // Print the exit block.
5791 print_block(OS, this, getExit(), Helper, true, ShowColors);
5792 OS << '\n';
5793 OS.flush();
5794 }
5795
getIndexInCFG() const5796 size_t CFGBlock::getIndexInCFG() const {
5797 return llvm::find(*getParent(), this) - getParent()->begin();
5798 }
5799
5800 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
dump(const CFG * cfg,const LangOptions & LO,bool ShowColors) const5801 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5802 bool ShowColors) const {
5803 print(llvm::errs(), cfg, LO, ShowColors);
5804 }
5805
dump() const5806 LLVM_DUMP_METHOD void CFGBlock::dump() const {
5807 dump(getParent(), LangOptions(), false);
5808 }
5809
5810 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5811 /// Generally this will only be called from CFG::print.
print(raw_ostream & OS,const CFG * cfg,const LangOptions & LO,bool ShowColors) const5812 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
5813 const LangOptions &LO, bool ShowColors) const {
5814 StmtPrinterHelper Helper(cfg, LO);
5815 print_block(OS, cfg, *this, Helper, true, ShowColors);
5816 OS << '\n';
5817 }
5818
5819 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
printTerminator(raw_ostream & OS,const LangOptions & LO) const5820 void CFGBlock::printTerminator(raw_ostream &OS,
5821 const LangOptions &LO) const {
5822 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
5823 TPrinter.print(getTerminator());
5824 }
5825
5826 /// printTerminatorJson - Pretty-prints the terminator in JSON format.
printTerminatorJson(raw_ostream & Out,const LangOptions & LO,bool AddQuotes) const5827 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
5828 bool AddQuotes) const {
5829 std::string Buf;
5830 llvm::raw_string_ostream TempOut(Buf);
5831
5832 printTerminator(TempOut, LO);
5833
5834 Out << JsonFormat(TempOut.str(), AddQuotes);
5835 }
5836
5837 // Returns true if by simply looking at the block, we can be sure that it
5838 // results in a sink during analysis. This is useful to know when the analysis
5839 // was interrupted, and we try to figure out if it would sink eventually.
5840 // There may be many more reasons why a sink would appear during analysis
5841 // (eg. checkers may generate sinks arbitrarily), but here we only consider
5842 // sinks that would be obvious by looking at the CFG.
isImmediateSinkBlock(const CFGBlock * Blk)5843 static bool isImmediateSinkBlock(const CFGBlock *Blk) {
5844 if (Blk->hasNoReturnElement())
5845 return true;
5846
5847 // FIXME: Throw-expressions are currently generating sinks during analysis:
5848 // they're not supported yet, and also often used for actually terminating
5849 // the program. So we should treat them as sinks in this analysis as well,
5850 // at least for now, but once we have better support for exceptions,
5851 // we'd need to carefully handle the case when the throw is being
5852 // immediately caught.
5853 if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
5854 if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
5855 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
5856 return true;
5857 return false;
5858 }))
5859 return true;
5860
5861 return false;
5862 }
5863
isInevitablySinking() const5864 bool CFGBlock::isInevitablySinking() const {
5865 const CFG &Cfg = *getParent();
5866
5867 const CFGBlock *StartBlk = this;
5868 if (isImmediateSinkBlock(StartBlk))
5869 return true;
5870
5871 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
5872 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
5873
5874 DFSWorkList.push_back(StartBlk);
5875 while (!DFSWorkList.empty()) {
5876 const CFGBlock *Blk = DFSWorkList.back();
5877 DFSWorkList.pop_back();
5878 Visited.insert(Blk);
5879
5880 // If at least one path reaches the CFG exit, it means that control is
5881 // returned to the caller. For now, say that we are not sure what
5882 // happens next. If necessary, this can be improved to analyze
5883 // the parent StackFrameContext's call site in a similar manner.
5884 if (Blk == &Cfg.getExit())
5885 return false;
5886
5887 for (const auto &Succ : Blk->succs()) {
5888 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
5889 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
5890 // If the block has reachable child blocks that aren't no-return,
5891 // add them to the worklist.
5892 DFSWorkList.push_back(SuccBlk);
5893 }
5894 }
5895 }
5896 }
5897
5898 // Nothing reached the exit. It can only mean one thing: there's no return.
5899 return true;
5900 }
5901
getLastCondition() const5902 const Expr *CFGBlock::getLastCondition() const {
5903 // If the terminator is a temporary dtor or a virtual base, etc, we can't
5904 // retrieve a meaningful condition, bail out.
5905 if (Terminator.getKind() != CFGTerminator::StmtBranch)
5906 return nullptr;
5907
5908 // Also, if this method was called on a block that doesn't have 2 successors,
5909 // this block doesn't have retrievable condition.
5910 if (succ_size() < 2)
5911 return nullptr;
5912
5913 // FIXME: Is there a better condition expression we can return in this case?
5914 if (size() == 0)
5915 return nullptr;
5916
5917 auto StmtElem = rbegin()->getAs<CFGStmt>();
5918 if (!StmtElem)
5919 return nullptr;
5920
5921 const Stmt *Cond = StmtElem->getStmt();
5922 if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond))
5923 return nullptr;
5924
5925 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
5926 // the cast<>.
5927 return cast<Expr>(Cond)->IgnoreParens();
5928 }
5929
getTerminatorCondition(bool StripParens)5930 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
5931 Stmt *Terminator = getTerminatorStmt();
5932 if (!Terminator)
5933 return nullptr;
5934
5935 Expr *E = nullptr;
5936
5937 switch (Terminator->getStmtClass()) {
5938 default:
5939 break;
5940
5941 case Stmt::CXXForRangeStmtClass:
5942 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5943 break;
5944
5945 case Stmt::ForStmtClass:
5946 E = cast<ForStmt>(Terminator)->getCond();
5947 break;
5948
5949 case Stmt::WhileStmtClass:
5950 E = cast<WhileStmt>(Terminator)->getCond();
5951 break;
5952
5953 case Stmt::DoStmtClass:
5954 E = cast<DoStmt>(Terminator)->getCond();
5955 break;
5956
5957 case Stmt::IfStmtClass:
5958 E = cast<IfStmt>(Terminator)->getCond();
5959 break;
5960
5961 case Stmt::ChooseExprClass:
5962 E = cast<ChooseExpr>(Terminator)->getCond();
5963 break;
5964
5965 case Stmt::IndirectGotoStmtClass:
5966 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5967 break;
5968
5969 case Stmt::SwitchStmtClass:
5970 E = cast<SwitchStmt>(Terminator)->getCond();
5971 break;
5972
5973 case Stmt::BinaryConditionalOperatorClass:
5974 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5975 break;
5976
5977 case Stmt::ConditionalOperatorClass:
5978 E = cast<ConditionalOperator>(Terminator)->getCond();
5979 break;
5980
5981 case Stmt::BinaryOperatorClass: // '&&' and '||'
5982 E = cast<BinaryOperator>(Terminator)->getLHS();
5983 break;
5984
5985 case Stmt::ObjCForCollectionStmtClass:
5986 return Terminator;
5987 }
5988
5989 if (!StripParens)
5990 return E;
5991
5992 return E ? E->IgnoreParens() : nullptr;
5993 }
5994
5995 //===----------------------------------------------------------------------===//
5996 // CFG Graphviz Visualization
5997 //===----------------------------------------------------------------------===//
5998
5999 #ifndef NDEBUG
6000 static StmtPrinterHelper* GraphHelper;
6001 #endif
6002
viewCFG(const LangOptions & LO) const6003 void CFG::viewCFG(const LangOptions &LO) const {
6004 #ifndef NDEBUG
6005 StmtPrinterHelper H(this, LO);
6006 GraphHelper = &H;
6007 llvm::ViewGraph(this,"CFG");
6008 GraphHelper = nullptr;
6009 #endif
6010 }
6011
6012 namespace llvm {
6013
6014 template<>
6015 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits6016 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6017
getNodeLabelllvm::DOTGraphTraits6018 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
6019 #ifndef NDEBUG
6020 std::string OutSStr;
6021 llvm::raw_string_ostream Out(OutSStr);
6022 print_block(Out,Graph, *Node, *GraphHelper, false, false);
6023 std::string& OutStr = Out.str();
6024
6025 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6026
6027 // Process string output to make it nicer...
6028 for (unsigned i = 0; i != OutStr.length(); ++i)
6029 if (OutStr[i] == '\n') { // Left justify
6030 OutStr[i] = '\\';
6031 OutStr.insert(OutStr.begin()+i+1, 'l');
6032 }
6033
6034 return OutStr;
6035 #else
6036 return {};
6037 #endif
6038 }
6039 };
6040
6041 } // namespace llvm
6042