clang API Documentation

CFG.cpp
Go to the documentation of this file.
00001   //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the CFG and CFGBuilder classes for representing and
00011 //  building Control-Flow Graphs (CFGs) from ASTs.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Analysis/CFG.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/CharUnits.h"
00019 #include "clang/AST/DeclCXX.h"
00020 #include "clang/AST/PrettyPrinter.h"
00021 #include "clang/AST/StmtVisitor.h"
00022 #include "clang/Basic/Builtins.h"
00023 #include "llvm/ADT/DenseMap.h"
00024 #include <memory>
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/Support/Allocator.h"
00027 #include "llvm/Support/Format.h"
00028 #include "llvm/Support/GraphWriter.h"
00029 #include "llvm/Support/SaveAndRestore.h"
00030 
00031 using namespace clang;
00032 
00033 namespace {
00034 
00035 static SourceLocation GetEndLoc(Decl *D) {
00036   if (VarDecl *VD = dyn_cast<VarDecl>(D))
00037     if (Expr *Ex = VD->getInit())
00038       return Ex->getSourceRange().getEnd();
00039   return D->getLocation();
00040 }
00041 
00042 class CFGBuilder;
00043   
00044 /// The CFG builder uses a recursive algorithm to build the CFG.  When
00045 ///  we process an expression, sometimes we know that we must add the
00046 ///  subexpressions as block-level expressions.  For example:
00047 ///
00048 ///    exp1 || exp2
00049 ///
00050 ///  When processing the '||' expression, we know that exp1 and exp2
00051 ///  need to be added as block-level expressions, even though they
00052 ///  might not normally need to be.  AddStmtChoice records this
00053 ///  contextual information.  If AddStmtChoice is 'NotAlwaysAdd', then
00054 ///  the builder has an option not to add a subexpression as a
00055 ///  block-level expression.
00056 ///
00057 class AddStmtChoice {
00058 public:
00059   enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
00060 
00061   AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
00062 
00063   bool alwaysAdd(CFGBuilder &builder,
00064                  const Stmt *stmt) const;
00065 
00066   /// Return a copy of this object, except with the 'always-add' bit
00067   ///  set as specified.
00068   AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
00069     return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
00070   }
00071 
00072 private:
00073   Kind kind;
00074 };
00075 
00076 /// LocalScope - Node in tree of local scopes created for C++ implicit
00077 /// destructor calls generation. It contains list of automatic variables
00078 /// declared in the scope and link to position in previous scope this scope
00079 /// began in.
00080 ///
00081 /// The process of creating local scopes is as follows:
00082 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
00083 /// - Before processing statements in scope (e.g. CompoundStmt) create
00084 ///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
00085 ///   and set CFGBuilder::ScopePos to the end of new scope,
00086 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
00087 ///   at this VarDecl,
00088 /// - For every normal (without jump) end of scope add to CFGBlock destructors
00089 ///   for objects in the current scope,
00090 /// - For every jump add to CFGBlock destructors for objects
00091 ///   between CFGBuilder::ScopePos and local scope position saved for jump
00092 ///   target. Thanks to C++ restrictions on goto jumps we can be sure that
00093 ///   jump target position will be on the path to root from CFGBuilder::ScopePos
00094 ///   (adding any variable that doesn't need constructor to be called to
00095 ///   LocalScope can break this assumption),
00096 ///
00097 class LocalScope {
00098 public:
00099   typedef BumpVector<VarDecl*> AutomaticVarsTy;
00100 
00101   /// const_iterator - Iterates local scope backwards and jumps to previous
00102   /// scope on reaching the beginning of currently iterated scope.
00103   class const_iterator {
00104     const LocalScope* Scope;
00105 
00106     /// VarIter is guaranteed to be greater then 0 for every valid iterator.
00107     /// Invalid iterator (with null Scope) has VarIter equal to 0.
00108     unsigned VarIter;
00109 
00110   public:
00111     /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
00112     /// Incrementing invalid iterator is allowed and will result in invalid
00113     /// iterator.
00114     const_iterator()
00115         : Scope(nullptr), VarIter(0) {}
00116 
00117     /// Create valid iterator. In case when S.Prev is an invalid iterator and
00118     /// I is equal to 0, this will create invalid iterator.
00119     const_iterator(const LocalScope& S, unsigned I)
00120         : Scope(&S), VarIter(I) {
00121       // Iterator to "end" of scope is not allowed. Handle it by going up
00122       // in scopes tree possibly up to invalid iterator in the root.
00123       if (VarIter == 0 && Scope)
00124         *this = Scope->Prev;
00125     }
00126 
00127     VarDecl *const* operator->() const {
00128       assert (Scope && "Dereferencing invalid iterator is not allowed");
00129       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
00130       return &Scope->Vars[VarIter - 1];
00131     }
00132     VarDecl *operator*() const {
00133       return *this->operator->();
00134     }
00135 
00136     const_iterator &operator++() {
00137       if (!Scope)
00138         return *this;
00139 
00140       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
00141       --VarIter;
00142       if (VarIter == 0)
00143         *this = Scope->Prev;
00144       return *this;
00145     }
00146     const_iterator operator++(int) {
00147       const_iterator P = *this;
00148       ++*this;
00149       return P;
00150     }
00151 
00152     bool operator==(const const_iterator &rhs) const {
00153       return Scope == rhs.Scope && VarIter == rhs.VarIter;
00154     }
00155     bool operator!=(const const_iterator &rhs) const {
00156       return !(*this == rhs);
00157     }
00158 
00159     LLVM_EXPLICIT operator bool() const {
00160       return *this != const_iterator();
00161     }
00162 
00163     int distance(const_iterator L);
00164   };
00165 
00166   friend class const_iterator;
00167 
00168 private:
00169   BumpVectorContext ctx;
00170   
00171   /// Automatic variables in order of declaration.
00172   AutomaticVarsTy Vars;
00173   /// Iterator to variable in previous scope that was declared just before
00174   /// begin of this scope.
00175   const_iterator Prev;
00176 
00177 public:
00178   /// Constructs empty scope linked to previous scope in specified place.
00179   LocalScope(BumpVectorContext &ctx, const_iterator P)
00180       : ctx(ctx), Vars(ctx, 4), Prev(P) {}
00181 
00182   /// Begin of scope in direction of CFG building (backwards).
00183   const_iterator begin() const { return const_iterator(*this, Vars.size()); }
00184 
00185   void addVar(VarDecl *VD) {
00186     Vars.push_back(VD, ctx);
00187   }
00188 };
00189 
00190 /// distance - Calculates distance from this to L. L must be reachable from this
00191 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
00192 /// number of scopes between this and L.
00193 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
00194   int D = 0;
00195   const_iterator F = *this;
00196   while (F.Scope != L.Scope) {
00197     assert (F != const_iterator()
00198         && "L iterator is not reachable from F iterator.");
00199     D += F.VarIter;
00200     F = F.Scope->Prev;
00201   }
00202   D += F.VarIter - L.VarIter;
00203   return D;
00204 }
00205 
00206 /// BlockScopePosPair - Structure for specifying position in CFG during its
00207 /// build process. It consists of CFGBlock that specifies position in CFG graph
00208 /// and  LocalScope::const_iterator that specifies position in LocalScope graph.
00209 struct BlockScopePosPair {
00210   BlockScopePosPair() : block(nullptr) {}
00211   BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
00212       : block(b), scopePosition(scopePos) {}
00213 
00214   CFGBlock *block;
00215   LocalScope::const_iterator scopePosition;
00216 };
00217 
00218 /// TryResult - a class representing a variant over the values
00219 ///  'true', 'false', or 'unknown'.  This is returned by tryEvaluateBool,
00220 ///  and is used by the CFGBuilder to decide if a branch condition
00221 ///  can be decided up front during CFG construction.
00222 class TryResult {
00223   int X;
00224 public:
00225   TryResult(bool b) : X(b ? 1 : 0) {}
00226   TryResult() : X(-1) {}
00227   
00228   bool isTrue() const { return X == 1; }
00229   bool isFalse() const { return X == 0; }
00230   bool isKnown() const { return X >= 0; }
00231   void negate() {
00232     assert(isKnown());
00233     X ^= 0x1;
00234   }
00235 };
00236 
00237 TryResult bothKnownTrue(TryResult R1, TryResult R2) {
00238   if (!R1.isKnown() || !R2.isKnown())
00239     return TryResult();
00240   return TryResult(R1.isTrue() && R2.isTrue());
00241 }
00242 
00243 class reverse_children {
00244   llvm::SmallVector<Stmt *, 12> childrenBuf;
00245   ArrayRef<Stmt*> children;
00246 public:
00247   reverse_children(Stmt *S);
00248 
00249   typedef ArrayRef<Stmt*>::reverse_iterator iterator;
00250   iterator begin() const { return children.rbegin(); }
00251   iterator end() const { return children.rend(); }
00252 };
00253 
00254 
00255 reverse_children::reverse_children(Stmt *S) {
00256   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
00257     children = CE->getRawSubExprs();
00258     return;
00259   }
00260   switch (S->getStmtClass()) {
00261     // Note: Fill in this switch with more cases we want to optimize.
00262     case Stmt::InitListExprClass: {
00263       InitListExpr *IE = cast<InitListExpr>(S);
00264       children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
00265                                     IE->getNumInits());
00266       return;
00267     }
00268     default:
00269       break;
00270   }
00271 
00272   // Default case for all other statements.
00273   for (Stmt::child_range I = S->children(); I; ++I) {
00274     childrenBuf.push_back(*I);
00275   }
00276 
00277   // This needs to be done *after* childrenBuf has been populated.
00278   children = childrenBuf;
00279 }
00280 
00281 /// CFGBuilder - This class implements CFG construction from an AST.
00282 ///   The builder is stateful: an instance of the builder should be used to only
00283 ///   construct a single CFG.
00284 ///
00285 ///   Example usage:
00286 ///
00287 ///     CFGBuilder builder;
00288 ///     CFG* cfg = builder.BuildAST(stmt1);
00289 ///
00290 ///  CFG construction is done via a recursive walk of an AST.  We actually parse
00291 ///  the AST in reverse order so that the successor of a basic block is
00292 ///  constructed prior to its predecessor.  This allows us to nicely capture
00293 ///  implicit fall-throughs without extra basic blocks.
00294 ///
00295 class CFGBuilder {
00296   typedef BlockScopePosPair JumpTarget;
00297   typedef BlockScopePosPair JumpSource;
00298 
00299   ASTContext *Context;
00300   std::unique_ptr<CFG> cfg;
00301 
00302   CFGBlock *Block;
00303   CFGBlock *Succ;
00304   JumpTarget ContinueJumpTarget;
00305   JumpTarget BreakJumpTarget;
00306   CFGBlock *SwitchTerminatedBlock;
00307   CFGBlock *DefaultCaseBlock;
00308   CFGBlock *TryTerminatedBlock;
00309 
00310   // Current position in local scope.
00311   LocalScope::const_iterator ScopePos;
00312 
00313   // LabelMap records the mapping from Label expressions to their jump targets.
00314   typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
00315   LabelMapTy LabelMap;
00316 
00317   // A list of blocks that end with a "goto" that must be backpatched to their
00318   // resolved targets upon completion of CFG construction.
00319   typedef std::vector<JumpSource> BackpatchBlocksTy;
00320   BackpatchBlocksTy BackpatchBlocks;
00321 
00322   // A list of labels whose address has been taken (for indirect gotos).
00323   typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
00324   LabelSetTy AddressTakenLabels;
00325 
00326   bool badCFG;
00327   const CFG::BuildOptions &BuildOpts;
00328   
00329   // State to track for building switch statements.
00330   bool switchExclusivelyCovered;
00331   Expr::EvalResult *switchCond;
00332   
00333   CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
00334   const Stmt *lastLookup;
00335 
00336   // Caches boolean evaluations of expressions to avoid multiple re-evaluations
00337   // during construction of branches for chained logical operators.
00338   typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
00339   CachedBoolEvalsTy CachedBoolEvals;
00340 
00341 public:
00342   explicit CFGBuilder(ASTContext *astContext,
00343                       const CFG::BuildOptions &buildOpts) 
00344     : Context(astContext), cfg(new CFG()), // crew a new CFG
00345       Block(nullptr), Succ(nullptr),
00346       SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
00347       TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
00348       switchExclusivelyCovered(false), switchCond(nullptr),
00349       cachedEntry(nullptr), lastLookup(nullptr) {}
00350 
00351   // buildCFG - Used by external clients to construct the CFG.
00352   std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
00353 
00354   bool alwaysAdd(const Stmt *stmt);
00355   
00356 private:
00357   // Visitors to walk an AST and construct the CFG.
00358   CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
00359   CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
00360   CFGBlock *VisitBreakStmt(BreakStmt *B);
00361   CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
00362   CFGBlock *VisitCaseStmt(CaseStmt *C);
00363   CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
00364   CFGBlock *VisitCompoundStmt(CompoundStmt *C);
00365   CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
00366                                      AddStmtChoice asc);
00367   CFGBlock *VisitContinueStmt(ContinueStmt *C);
00368   CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
00369                                       AddStmtChoice asc);
00370   CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
00371   CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
00372   CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
00373   CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
00374   CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
00375   CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
00376                                        AddStmtChoice asc);
00377   CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
00378                                         AddStmtChoice asc);
00379   CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
00380   CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
00381   CFGBlock *VisitDeclStmt(DeclStmt *DS);
00382   CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
00383   CFGBlock *VisitDefaultStmt(DefaultStmt *D);
00384   CFGBlock *VisitDoStmt(DoStmt *D);
00385   CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
00386   CFGBlock *VisitForStmt(ForStmt *F);
00387   CFGBlock *VisitGotoStmt(GotoStmt *G);
00388   CFGBlock *VisitIfStmt(IfStmt *I);
00389   CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
00390   CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
00391   CFGBlock *VisitLabelStmt(LabelStmt *L);
00392   CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
00393   CFGBlock *VisitLogicalOperator(BinaryOperator *B);
00394   std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
00395                                                          Stmt *Term,
00396                                                          CFGBlock *TrueBlock,
00397                                                          CFGBlock *FalseBlock);
00398   CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
00399   CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
00400   CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
00401   CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
00402   CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
00403   CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
00404   CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
00405   CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
00406   CFGBlock *VisitReturnStmt(ReturnStmt *R);
00407   CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
00408   CFGBlock *VisitSwitchStmt(SwitchStmt *S);
00409   CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
00410                                           AddStmtChoice asc);
00411   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
00412   CFGBlock *VisitWhileStmt(WhileStmt *W);
00413 
00414   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
00415   CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
00416   CFGBlock *VisitChildren(Stmt *S);
00417   CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
00418 
00419   /// When creating the CFG for temporary destructors, we want to mirror the
00420   /// branch structure of the corresponding constructor calls.
00421   /// Thus, while visiting a statement for temporary destructors, we keep a
00422   /// context to keep track of the following information:
00423   /// - whether a subexpression is executed unconditionally
00424   /// - if a subexpression is executed conditionally, the first
00425   ///   CXXBindTemporaryExpr we encounter in that subexpression (which
00426   ///   corresponds to the last temporary destructor we have to call for this
00427   ///   subexpression) and the CFG block at that point (which will become the
00428   ///   successor block when inserting the decision point).
00429   ///
00430   /// That way, we can build the branch structure for temporary destructors as
00431   /// follows:
00432   /// 1. If a subexpression is executed unconditionally, we add the temporary
00433   ///    destructor calls to the current block.
00434   /// 2. If a subexpression is executed conditionally, when we encounter a
00435   ///    CXXBindTemporaryExpr:
00436   ///    a) If it is the first temporary destructor call in the subexpression,
00437   ///       we remember the CXXBindTemporaryExpr and the current block in the
00438   ///       TempDtorContext; we start a new block, and insert the temporary
00439   ///       destructor call.
00440   ///    b) Otherwise, add the temporary destructor call to the current block.
00441   ///  3. When we finished visiting a conditionally executed subexpression,
00442   ///     and we found at least one temporary constructor during the visitation
00443   ///     (2.a has executed), we insert a decision block that uses the
00444   ///     CXXBindTemporaryExpr as terminator, and branches to the current block
00445   ///     if the CXXBindTemporaryExpr was marked executed, and otherwise
00446   ///     branches to the stored successor.
00447   struct TempDtorContext {
00448     TempDtorContext()
00449         : IsConditional(false), KnownExecuted(true), Succ(nullptr),
00450           TerminatorExpr(nullptr) {}
00451 
00452     TempDtorContext(TryResult KnownExecuted)
00453         : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
00454           TerminatorExpr(nullptr) {}
00455 
00456     /// Returns whether we need to start a new branch for a temporary destructor
00457     /// call. This is the case when the the temporary destructor is
00458     /// conditionally executed, and it is the first one we encounter while
00459     /// visiting a subexpression - other temporary destructors at the same level
00460     /// will be added to the same block and are executed under the same
00461     /// condition.
00462     bool needsTempDtorBranch() const {
00463       return IsConditional && !TerminatorExpr;
00464     }
00465 
00466     /// Remember the successor S of a temporary destructor decision branch for
00467     /// the corresponding CXXBindTemporaryExpr E.
00468     void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
00469       Succ = S;
00470       TerminatorExpr = E;
00471     }
00472 
00473     const bool IsConditional;
00474     const TryResult KnownExecuted;
00475     CFGBlock *Succ;
00476     CXXBindTemporaryExpr *TerminatorExpr;
00477   };
00478 
00479   // Visitors to walk an AST and generate destructors of temporaries in
00480   // full expression.
00481   CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
00482                                    TempDtorContext &Context);
00483   CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
00484   CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
00485                                                  TempDtorContext &Context);
00486   CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
00487       CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
00488   CFGBlock *VisitConditionalOperatorForTemporaryDtors(
00489       AbstractConditionalOperator *E, bool BindToTemporary,
00490       TempDtorContext &Context);
00491   void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
00492                                    CFGBlock *FalseSucc = nullptr);
00493 
00494   // NYS == Not Yet Supported
00495   CFGBlock *NYS() {
00496     badCFG = true;
00497     return Block;
00498   }
00499 
00500   void autoCreateBlock() { if (!Block) Block = createBlock(); }
00501   CFGBlock *createBlock(bool add_successor = true);
00502   CFGBlock *createNoReturnBlock();
00503 
00504   CFGBlock *addStmt(Stmt *S) {
00505     return Visit(S, AddStmtChoice::AlwaysAdd);
00506   }
00507   CFGBlock *addInitializer(CXXCtorInitializer *I);
00508   void addAutomaticObjDtors(LocalScope::const_iterator B,
00509                             LocalScope::const_iterator E, Stmt *S);
00510   void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
00511 
00512   // Local scopes creation.
00513   LocalScope* createOrReuseLocalScope(LocalScope* Scope);
00514 
00515   void addLocalScopeForStmt(Stmt *S);
00516   LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
00517                                        LocalScope* Scope = nullptr);
00518   LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
00519 
00520   void addLocalScopeAndDtors(Stmt *S);
00521 
00522   // Interface to CFGBlock - adding CFGElements.
00523   void appendStmt(CFGBlock *B, const Stmt *S) {
00524     if (alwaysAdd(S) && cachedEntry)
00525       cachedEntry->second = B;
00526 
00527     // All block-level expressions should have already been IgnoreParens()ed.
00528     assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
00529     B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
00530   }
00531   void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
00532     B->appendInitializer(I, cfg->getBumpVectorContext());
00533   }
00534   void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
00535     B->appendNewAllocator(NE, cfg->getBumpVectorContext());
00536   }
00537   void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
00538     B->appendBaseDtor(BS, cfg->getBumpVectorContext());
00539   }
00540   void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
00541     B->appendMemberDtor(FD, cfg->getBumpVectorContext());
00542   }
00543   void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
00544     B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
00545   }
00546   void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
00547     B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
00548   }
00549 
00550   void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
00551     B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
00552   }
00553 
00554   void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
00555       LocalScope::const_iterator B, LocalScope::const_iterator E);
00556 
00557   void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
00558     B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
00559                     cfg->getBumpVectorContext());
00560   }
00561 
00562   /// Add a reachable successor to a block, with the alternate variant that is
00563   /// unreachable.
00564   void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
00565     B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
00566                     cfg->getBumpVectorContext());
00567   }
00568 
00569   /// \brief Find a relational comparison with an expression evaluating to a
00570   /// boolean and a constant other than 0 and 1.
00571   /// e.g. if ((x < y) == 10)
00572   TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
00573     const Expr *LHSExpr = B->getLHS()->IgnoreParens();
00574     const Expr *RHSExpr = B->getRHS()->IgnoreParens();
00575 
00576     const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
00577     const Expr *BoolExpr = RHSExpr;
00578     bool IntFirst = true;
00579     if (!IntLiteral) {
00580       IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
00581       BoolExpr = LHSExpr;
00582       IntFirst = false;
00583     }
00584 
00585     if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
00586       return TryResult();
00587 
00588     llvm::APInt IntValue = IntLiteral->getValue();
00589     if ((IntValue == 1) || (IntValue == 0))
00590       return TryResult();
00591 
00592     bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
00593                      !IntValue.isNegative();
00594 
00595     BinaryOperatorKind Bok = B->getOpcode();
00596     if (Bok == BO_GT || Bok == BO_GE) {
00597       // Always true for 10 > bool and bool > -1
00598       // Always false for -1 > bool and bool > 10
00599       return TryResult(IntFirst == IntLarger);
00600     } else {
00601       // Always true for -1 < bool and bool < 10
00602       // Always false for 10 < bool and bool < -1
00603       return TryResult(IntFirst != IntLarger);
00604     }
00605   }
00606 
00607   /// Find an incorrect equality comparison. Either with an expression
00608   /// evaluating to a boolean and a constant other than 0 and 1.
00609   /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
00610   /// true/false e.q. (x & 8) == 4.
00611   TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
00612     const Expr *LHSExpr = B->getLHS()->IgnoreParens();
00613     const Expr *RHSExpr = B->getRHS()->IgnoreParens();
00614 
00615     const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
00616     const Expr *BoolExpr = RHSExpr;
00617 
00618     if (!IntLiteral) {
00619       IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
00620       BoolExpr = LHSExpr;
00621     }
00622 
00623     if (!IntLiteral)
00624       return TryResult();
00625 
00626     const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
00627     if (BitOp && (BitOp->getOpcode() == BO_And ||
00628                   BitOp->getOpcode() == BO_Or)) {
00629       const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
00630       const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
00631 
00632       const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
00633 
00634       if (!IntLiteral2)
00635         IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
00636 
00637       if (!IntLiteral2)
00638         return TryResult();
00639 
00640       llvm::APInt L1 = IntLiteral->getValue();
00641       llvm::APInt L2 = IntLiteral2->getValue();
00642       if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
00643           (BitOp->getOpcode() == BO_Or  && (L2 | L1) != L1)) {
00644         if (BuildOpts.Observer)
00645           BuildOpts.Observer->compareBitwiseEquality(B,
00646                                                      B->getOpcode() != BO_EQ);
00647         TryResult(B->getOpcode() != BO_EQ);
00648       }
00649     } else if (BoolExpr->isKnownToHaveBooleanValue()) {
00650       llvm::APInt IntValue = IntLiteral->getValue();
00651       if ((IntValue == 1) || (IntValue == 0)) {
00652         return TryResult();
00653       }
00654       return TryResult(B->getOpcode() != BO_EQ);
00655     }
00656 
00657     return TryResult();
00658   }
00659 
00660   TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
00661                                           const llvm::APSInt &Value1,
00662                                           const llvm::APSInt &Value2) {
00663     assert(Value1.isSigned() == Value2.isSigned());
00664     switch (Relation) {
00665       default:
00666         return TryResult();
00667       case BO_EQ:
00668         return TryResult(Value1 == Value2);
00669       case BO_NE:
00670         return TryResult(Value1 != Value2);
00671       case BO_LT:
00672         return TryResult(Value1 <  Value2);
00673       case BO_LE:
00674         return TryResult(Value1 <= Value2);
00675       case BO_GT:
00676         return TryResult(Value1 >  Value2);
00677       case BO_GE:
00678         return TryResult(Value1 >= Value2);
00679     }
00680   }
00681 
00682   /// \brief Find a pair of comparison expressions with or without parentheses
00683   /// with a shared variable and constants and a logical operator between them
00684   /// that always evaluates to either true or false.
00685   /// e.g. if (x != 3 || x != 4)
00686   TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
00687     assert(B->isLogicalOp());
00688     const BinaryOperator *LHS =
00689         dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
00690     const BinaryOperator *RHS =
00691         dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
00692     if (!LHS || !RHS)
00693       return TryResult();
00694 
00695     if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
00696       return TryResult();
00697 
00698     BinaryOperatorKind BO1 = LHS->getOpcode();
00699     const DeclRefExpr *Decl1 =
00700         dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
00701     const IntegerLiteral *Literal1 =
00702         dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
00703     if (!Decl1 && !Literal1) {
00704       if (BO1 == BO_GT)
00705         BO1 = BO_LT;
00706       else if (BO1 == BO_GE)
00707         BO1 = BO_LE;
00708       else if (BO1 == BO_LT)
00709         BO1 = BO_GT;
00710       else if (BO1 == BO_LE)
00711         BO1 = BO_GE;
00712       Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
00713       Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
00714     }
00715 
00716     if (!Decl1 || !Literal1)
00717       return TryResult();
00718 
00719     BinaryOperatorKind BO2 = RHS->getOpcode();
00720     const DeclRefExpr *Decl2 =
00721         dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
00722     const IntegerLiteral *Literal2 =
00723         dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
00724     if (!Decl2 && !Literal2) {
00725       if (BO2 == BO_GT)
00726         BO2 = BO_LT;
00727       else if (BO2 == BO_GE)
00728         BO2 = BO_LE;
00729       else if (BO2 == BO_LT)
00730         BO2 = BO_GT;
00731       else if (BO2 == BO_LE)
00732         BO2 = BO_GE;
00733       Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
00734       Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
00735     }
00736 
00737     if (!Decl2 || !Literal2)
00738       return TryResult();
00739 
00740     // Check that it is the same variable on both sides.
00741     if (Decl1->getDecl() != Decl2->getDecl())
00742       return TryResult();
00743 
00744     llvm::APSInt L1, L2;
00745 
00746     if (!Literal1->EvaluateAsInt(L1, *Context) ||
00747         !Literal2->EvaluateAsInt(L2, *Context))
00748       return TryResult();
00749 
00750     // Can't compare signed with unsigned or with different bit width.
00751     if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
00752       return TryResult();
00753 
00754     // Values that will be used to determine if result of logical
00755     // operator is always true/false
00756     const llvm::APSInt Values[] = {
00757       // Value less than both Value1 and Value2
00758       llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
00759       // L1
00760       L1,
00761       // Value between Value1 and Value2
00762       ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
00763                               L1.isUnsigned()),
00764       // L2
00765       L2,
00766       // Value greater than both Value1 and Value2
00767       llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
00768     };
00769 
00770     // Check whether expression is always true/false by evaluating the following
00771     // * variable x is less than the smallest literal.
00772     // * variable x is equal to the smallest literal.
00773     // * Variable x is between smallest and largest literal.
00774     // * Variable x is equal to the largest literal.
00775     // * Variable x is greater than largest literal.
00776     bool AlwaysTrue = true, AlwaysFalse = true;
00777     for (unsigned int ValueIndex = 0;
00778          ValueIndex < sizeof(Values) / sizeof(Values[0]);
00779          ++ValueIndex) {
00780       llvm::APSInt Value = Values[ValueIndex];
00781       TryResult Res1, Res2;
00782       Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
00783       Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
00784 
00785       if (!Res1.isKnown() || !Res2.isKnown())
00786         return TryResult();
00787 
00788       if (B->getOpcode() == BO_LAnd) {
00789         AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
00790         AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
00791       } else {
00792         AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
00793         AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
00794       }
00795     }
00796 
00797     if (AlwaysTrue || AlwaysFalse) {
00798       if (BuildOpts.Observer)
00799         BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
00800       return TryResult(AlwaysTrue);
00801     }
00802     return TryResult();
00803   }
00804 
00805   /// Try and evaluate an expression to an integer constant.
00806   bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
00807     if (!BuildOpts.PruneTriviallyFalseEdges)
00808       return false;
00809     return !S->isTypeDependent() && 
00810            !S->isValueDependent() &&
00811            S->EvaluateAsRValue(outResult, *Context);
00812   }
00813 
00814   /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
00815   /// if we can evaluate to a known value, otherwise return -1.
00816   TryResult tryEvaluateBool(Expr *S) {
00817     if (!BuildOpts.PruneTriviallyFalseEdges ||
00818         S->isTypeDependent() || S->isValueDependent())
00819       return TryResult();
00820 
00821     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
00822       if (Bop->isLogicalOp()) {
00823         // Check the cache first.
00824         CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
00825         if (I != CachedBoolEvals.end())
00826           return I->second; // already in map;
00827 
00828         // Retrieve result at first, or the map might be updated.
00829         TryResult Result = evaluateAsBooleanConditionNoCache(S);
00830         CachedBoolEvals[S] = Result; // update or insert
00831         return Result;
00832       }
00833       else {
00834         switch (Bop->getOpcode()) {
00835           default: break;
00836           // For 'x & 0' and 'x * 0', we can determine that
00837           // the value is always false.
00838           case BO_Mul:
00839           case BO_And: {
00840             // If either operand is zero, we know the value
00841             // must be false.
00842             llvm::APSInt IntVal;
00843             if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
00844               if (IntVal.getBoolValue() == false) {
00845                 return TryResult(false);
00846               }
00847             }
00848             if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
00849               if (IntVal.getBoolValue() == false) {
00850                 return TryResult(false);
00851               }
00852             }
00853           }
00854           break;
00855         }
00856       }
00857     }
00858 
00859     return evaluateAsBooleanConditionNoCache(S);
00860   }
00861 
00862   /// \brief Evaluate as boolean \param E without using the cache.
00863   TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
00864     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
00865       if (Bop->isLogicalOp()) {
00866         TryResult LHS = tryEvaluateBool(Bop->getLHS());
00867         if (LHS.isKnown()) {
00868           // We were able to evaluate the LHS, see if we can get away with not
00869           // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
00870           if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
00871             return LHS.isTrue();
00872 
00873           TryResult RHS = tryEvaluateBool(Bop->getRHS());
00874           if (RHS.isKnown()) {
00875             if (Bop->getOpcode() == BO_LOr)
00876               return LHS.isTrue() || RHS.isTrue();
00877             else
00878               return LHS.isTrue() && RHS.isTrue();
00879           }
00880         } else {
00881           TryResult RHS = tryEvaluateBool(Bop->getRHS());
00882           if (RHS.isKnown()) {
00883             // We can't evaluate the LHS; however, sometimes the result
00884             // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
00885             if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
00886               return RHS.isTrue();
00887           } else {
00888             TryResult BopRes = checkIncorrectLogicOperator(Bop);
00889             if (BopRes.isKnown())
00890               return BopRes.isTrue();
00891           }
00892         }
00893 
00894         return TryResult();
00895       } else if (Bop->isEqualityOp()) {
00896           TryResult BopRes = checkIncorrectEqualityOperator(Bop);
00897           if (BopRes.isKnown())
00898             return BopRes.isTrue();
00899       } else if (Bop->isRelationalOp()) {
00900         TryResult BopRes = checkIncorrectRelationalOperator(Bop);
00901         if (BopRes.isKnown())
00902           return BopRes.isTrue();
00903       }
00904     }
00905 
00906     bool Result;
00907     if (E->EvaluateAsBooleanCondition(Result, *Context))
00908       return Result;
00909 
00910     return TryResult();
00911   }
00912   
00913 };
00914 
00915 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
00916                                      const Stmt *stmt) const {
00917   return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
00918 }
00919 
00920 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
00921   bool shouldAdd = BuildOpts.alwaysAdd(stmt);
00922   
00923   if (!BuildOpts.forcedBlkExprs)
00924     return shouldAdd;
00925 
00926   if (lastLookup == stmt) {  
00927     if (cachedEntry) {
00928       assert(cachedEntry->first == stmt);
00929       return true;
00930     }
00931     return shouldAdd;
00932   }
00933   
00934   lastLookup = stmt;
00935 
00936   // Perform the lookup!
00937   CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
00938 
00939   if (!fb) {
00940     // No need to update 'cachedEntry', since it will always be null.
00941     assert(!cachedEntry);
00942     return shouldAdd;
00943   }
00944 
00945   CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
00946   if (itr == fb->end()) {
00947     cachedEntry = nullptr;
00948     return shouldAdd;
00949   }
00950 
00951   cachedEntry = &*itr;
00952   return true;
00953 }
00954   
00955 // FIXME: Add support for dependent-sized array types in C++?
00956 // Does it even make sense to build a CFG for an uninstantiated template?
00957 static const VariableArrayType *FindVA(const Type *t) {
00958   while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
00959     if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
00960       if (vat->getSizeExpr())
00961         return vat;
00962 
00963     t = vt->getElementType().getTypePtr();
00964   }
00965 
00966   return nullptr;
00967 }
00968 
00969 /// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
00970 ///  arbitrary statement.  Examples include a single expression or a function
00971 ///  body (compound statement).  The ownership of the returned CFG is
00972 ///  transferred to the caller.  If CFG construction fails, this method returns
00973 ///  NULL.
00974 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
00975   assert(cfg.get());
00976   if (!Statement)
00977     return nullptr;
00978 
00979   // Create an empty block that will serve as the exit block for the CFG.  Since
00980   // this is the first block added to the CFG, it will be implicitly registered
00981   // as the exit block.
00982   Succ = createBlock();
00983   assert(Succ == &cfg->getExit());
00984   Block = nullptr;  // the EXIT block is empty.  Create all other blocks lazily.
00985 
00986   if (BuildOpts.AddImplicitDtors)
00987     if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
00988       addImplicitDtorsForDestructor(DD);
00989 
00990   // Visit the statements and create the CFG.
00991   CFGBlock *B = addStmt(Statement);
00992 
00993   if (badCFG)
00994     return nullptr;
00995 
00996   // For C++ constructor add initializers to CFG.
00997   if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
00998     for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
00999         E = CD->init_rend(); I != E; ++I) {
01000       B = addInitializer(*I);
01001       if (badCFG)
01002         return nullptr;
01003     }
01004   }
01005 
01006   if (B)
01007     Succ = B;
01008 
01009   // Backpatch the gotos whose label -> block mappings we didn't know when we
01010   // encountered them.
01011   for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
01012                                    E = BackpatchBlocks.end(); I != E; ++I ) {
01013 
01014     CFGBlock *B = I->block;
01015     const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
01016     LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
01017 
01018     // If there is no target for the goto, then we are looking at an
01019     // incomplete AST.  Handle this by not registering a successor.
01020     if (LI == LabelMap.end()) continue;
01021 
01022     JumpTarget JT = LI->second;
01023     prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
01024                                            JT.scopePosition);
01025     addSuccessor(B, JT.block);
01026   }
01027 
01028   // Add successors to the Indirect Goto Dispatch block (if we have one).
01029   if (CFGBlock *B = cfg->getIndirectGotoBlock())
01030     for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
01031                               E = AddressTakenLabels.end(); I != E; ++I ) {
01032       
01033       // Lookup the target block.
01034       LabelMapTy::iterator LI = LabelMap.find(*I);
01035 
01036       // If there is no target block that contains label, then we are looking
01037       // at an incomplete AST.  Handle this by not registering a successor.
01038       if (LI == LabelMap.end()) continue;
01039       
01040       addSuccessor(B, LI->second.block);
01041     }
01042 
01043   // Create an empty entry block that has no predecessors.
01044   cfg->setEntry(createBlock());
01045 
01046   return std::move(cfg);
01047 }
01048 
01049 /// createBlock - Used to lazily create blocks that are connected
01050 ///  to the current (global) succcessor.
01051 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
01052   CFGBlock *B = cfg->createBlock();
01053   if (add_successor && Succ)
01054     addSuccessor(B, Succ);
01055   return B;
01056 }
01057 
01058 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
01059 /// CFG. It is *not* connected to the current (global) successor, and instead
01060 /// directly tied to the exit block in order to be reachable.
01061 CFGBlock *CFGBuilder::createNoReturnBlock() {
01062   CFGBlock *B = createBlock(false);
01063   B->setHasNoReturnElement();
01064   addSuccessor(B, &cfg->getExit(), Succ);
01065   return B;
01066 }
01067 
01068 /// addInitializer - Add C++ base or member initializer element to CFG.
01069 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
01070   if (!BuildOpts.AddInitializers)
01071     return Block;
01072 
01073   bool HasTemporaries = false;
01074 
01075   // Destructors of temporaries in initialization expression should be called
01076   // after initialization finishes.
01077   Expr *Init = I->getInit();
01078   if (Init) {
01079     HasTemporaries = isa<ExprWithCleanups>(Init);
01080 
01081     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
01082       // Generate destructors for temporaries in initialization expression.
01083       TempDtorContext Context;
01084       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
01085                              /*BindToTemporary=*/false, Context);
01086     }
01087   }
01088 
01089   autoCreateBlock();
01090   appendInitializer(Block, I);
01091 
01092   if (Init) {
01093     if (HasTemporaries) {
01094       // For expression with temporaries go directly to subexpression to omit
01095       // generating destructors for the second time.
01096       return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
01097     }
01098     return Visit(Init);
01099   }
01100 
01101   return Block;
01102 }
01103 
01104 /// \brief Retrieve the type of the temporary object whose lifetime was 
01105 /// extended by a local reference with the given initializer.
01106 static QualType getReferenceInitTemporaryType(ASTContext &Context,
01107                                               const Expr *Init) {
01108   while (true) {
01109     // Skip parentheses.
01110     Init = Init->IgnoreParens();
01111     
01112     // Skip through cleanups.
01113     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
01114       Init = EWC->getSubExpr();
01115       continue;
01116     }
01117     
01118     // Skip through the temporary-materialization expression.
01119     if (const MaterializeTemporaryExpr *MTE
01120           = dyn_cast<MaterializeTemporaryExpr>(Init)) {
01121       Init = MTE->GetTemporaryExpr();
01122       continue;
01123     }
01124     
01125     // Skip derived-to-base and no-op casts.
01126     if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
01127       if ((CE->getCastKind() == CK_DerivedToBase ||
01128            CE->getCastKind() == CK_UncheckedDerivedToBase ||
01129            CE->getCastKind() == CK_NoOp) &&
01130           Init->getType()->isRecordType()) {
01131         Init = CE->getSubExpr();
01132         continue;
01133       }
01134     }
01135     
01136     // Skip member accesses into rvalues.
01137     if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
01138       if (!ME->isArrow() && ME->getBase()->isRValue()) {
01139         Init = ME->getBase();
01140         continue;
01141       }
01142     }
01143     
01144     break;
01145   }
01146 
01147   return Init->getType();
01148 }
01149   
01150 /// addAutomaticObjDtors - Add to current block automatic objects destructors
01151 /// for objects in range of local scope positions. Use S as trigger statement
01152 /// for destructors.
01153 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
01154                                       LocalScope::const_iterator E, Stmt *S) {
01155   if (!BuildOpts.AddImplicitDtors)
01156     return;
01157 
01158   if (B == E)
01159     return;
01160 
01161   // We need to append the destructors in reverse order, but any one of them
01162   // may be a no-return destructor which changes the CFG. As a result, buffer
01163   // this sequence up and replay them in reverse order when appending onto the
01164   // CFGBlock(s).
01165   SmallVector<VarDecl*, 10> Decls;
01166   Decls.reserve(B.distance(E));
01167   for (LocalScope::const_iterator I = B; I != E; ++I)
01168     Decls.push_back(*I);
01169 
01170   for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
01171                                                    E = Decls.rend();
01172        I != E; ++I) {
01173     // If this destructor is marked as a no-return destructor, we need to
01174     // create a new block for the destructor which does not have as a successor
01175     // anything built thus far: control won't flow out of this block.
01176     QualType Ty = (*I)->getType();
01177     if (Ty->isReferenceType()) {
01178       Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
01179     }
01180     Ty = Context->getBaseElementType(Ty);
01181 
01182     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
01183     if (Dtor->isNoReturn())
01184       Block = createNoReturnBlock();
01185     else
01186       autoCreateBlock();
01187 
01188     appendAutomaticObjDtor(Block, *I, S);
01189   }
01190 }
01191 
01192 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
01193 /// base and member objects in destructor.
01194 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
01195   assert (BuildOpts.AddImplicitDtors
01196       && "Can be called only when dtors should be added");
01197   const CXXRecordDecl *RD = DD->getParent();
01198 
01199   // At the end destroy virtual base objects.
01200   for (const auto &VI : RD->vbases()) {
01201     const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
01202     if (!CD->hasTrivialDestructor()) {
01203       autoCreateBlock();
01204       appendBaseDtor(Block, &VI);
01205     }
01206   }
01207 
01208   // Before virtual bases destroy direct base objects.
01209   for (const auto &BI : RD->bases()) {
01210     if (!BI.isVirtual()) {
01211       const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
01212       if (!CD->hasTrivialDestructor()) {
01213         autoCreateBlock();
01214         appendBaseDtor(Block, &BI);
01215       }
01216     }
01217   }
01218 
01219   // First destroy member objects.
01220   for (auto *FI : RD->fields()) {
01221     // Check for constant size array. Set type to array element type.
01222     QualType QT = FI->getType();
01223     if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
01224       if (AT->getSize() == 0)
01225         continue;
01226       QT = AT->getElementType();
01227     }
01228 
01229     if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
01230       if (!CD->hasTrivialDestructor()) {
01231         autoCreateBlock();
01232         appendMemberDtor(Block, FI);
01233       }
01234   }
01235 }
01236 
01237 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
01238 /// way return valid LocalScope object.
01239 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
01240   if (!Scope) {
01241     llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
01242     Scope = alloc.Allocate<LocalScope>();
01243     BumpVectorContext ctx(alloc);
01244     new (Scope) LocalScope(ctx, ScopePos);
01245   }
01246   return Scope;
01247 }
01248 
01249 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
01250 /// that should create implicit scope (e.g. if/else substatements). 
01251 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
01252   if (!BuildOpts.AddImplicitDtors)
01253     return;
01254 
01255   LocalScope *Scope = nullptr;
01256 
01257   // For compound statement we will be creating explicit scope.
01258   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
01259     for (auto *BI : CS->body()) {
01260       Stmt *SI = BI->stripLabelLikeStatements();
01261       if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
01262         Scope = addLocalScopeForDeclStmt(DS, Scope);
01263     }
01264     return;
01265   }
01266 
01267   // For any other statement scope will be implicit and as such will be
01268   // interesting only for DeclStmt.
01269   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
01270     addLocalScopeForDeclStmt(DS);
01271 }
01272 
01273 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
01274 /// reuse Scope if not NULL.
01275 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
01276                                                  LocalScope* Scope) {
01277   if (!BuildOpts.AddImplicitDtors)
01278     return Scope;
01279 
01280   for (auto *DI : DS->decls())
01281     if (VarDecl *VD = dyn_cast<VarDecl>(DI))
01282       Scope = addLocalScopeForVarDecl(VD, Scope);
01283   return Scope;
01284 }
01285 
01286 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
01287 /// create add scope for automatic objects and temporary objects bound to
01288 /// const reference. Will reuse Scope if not NULL.
01289 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
01290                                                 LocalScope* Scope) {
01291   if (!BuildOpts.AddImplicitDtors)
01292     return Scope;
01293 
01294   // Check if variable is local.
01295   switch (VD->getStorageClass()) {
01296   case SC_None:
01297   case SC_Auto:
01298   case SC_Register:
01299     break;
01300   default: return Scope;
01301   }
01302 
01303   // Check for const references bound to temporary. Set type to pointee.
01304   QualType QT = VD->getType();
01305   if (QT.getTypePtr()->isReferenceType()) {
01306     // Attempt to determine whether this declaration lifetime-extends a
01307     // temporary.
01308     //
01309     // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
01310     // temporaries, and a single declaration can extend multiple temporaries.
01311     // We should look at the storage duration on each nested
01312     // MaterializeTemporaryExpr instead.
01313     const Expr *Init = VD->getInit();
01314     if (!Init)
01315       return Scope;
01316     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
01317       Init = EWC->getSubExpr();
01318     if (!isa<MaterializeTemporaryExpr>(Init))
01319       return Scope;
01320 
01321     // Lifetime-extending a temporary.
01322     QT = getReferenceInitTemporaryType(*Context, Init);
01323   }
01324 
01325   // Check for constant size array. Set type to array element type.
01326   while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
01327     if (AT->getSize() == 0)
01328       return Scope;
01329     QT = AT->getElementType();
01330   }
01331 
01332   // Check if type is a C++ class with non-trivial destructor.
01333   if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
01334     if (!CD->hasTrivialDestructor()) {
01335       // Add the variable to scope
01336       Scope = createOrReuseLocalScope(Scope);
01337       Scope->addVar(VD);
01338       ScopePos = Scope->begin();
01339     }
01340   return Scope;
01341 }
01342 
01343 /// addLocalScopeAndDtors - For given statement add local scope for it and
01344 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
01345 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
01346   if (!BuildOpts.AddImplicitDtors)
01347     return;
01348 
01349   LocalScope::const_iterator scopeBeginPos = ScopePos;
01350   addLocalScopeForStmt(S);
01351   addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
01352 }
01353 
01354 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
01355 /// variables with automatic storage duration to CFGBlock's elements vector.
01356 /// Elements will be prepended to physical beginning of the vector which
01357 /// happens to be logical end. Use blocks terminator as statement that specifies
01358 /// destructors call site.
01359 /// FIXME: This mechanism for adding automatic destructors doesn't handle
01360 /// no-return destructors properly.
01361 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
01362     LocalScope::const_iterator B, LocalScope::const_iterator E) {
01363   BumpVectorContext &C = cfg->getBumpVectorContext();
01364   CFGBlock::iterator InsertPos
01365     = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
01366   for (LocalScope::const_iterator I = B; I != E; ++I)
01367     InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
01368                                             Blk->getTerminator());
01369 }
01370 
01371 /// Visit - Walk the subtree of a statement and add extra
01372 ///   blocks for ternary operators, &&, and ||.  We also process "," and
01373 ///   DeclStmts (which may contain nested control-flow).
01374 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
01375   if (!S) {
01376     badCFG = true;
01377     return nullptr;
01378   }
01379 
01380   if (Expr *E = dyn_cast<Expr>(S))
01381     S = E->IgnoreParens();
01382 
01383   switch (S->getStmtClass()) {
01384     default:
01385       return VisitStmt(S, asc);
01386 
01387     case Stmt::AddrLabelExprClass:
01388       return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
01389 
01390     case Stmt::BinaryConditionalOperatorClass:
01391       return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
01392 
01393     case Stmt::BinaryOperatorClass:
01394       return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
01395 
01396     case Stmt::BlockExprClass:
01397       return VisitNoRecurse(cast<Expr>(S), asc);
01398 
01399     case Stmt::BreakStmtClass:
01400       return VisitBreakStmt(cast<BreakStmt>(S));
01401 
01402     case Stmt::CallExprClass:
01403     case Stmt::CXXOperatorCallExprClass:
01404     case Stmt::CXXMemberCallExprClass:
01405     case Stmt::UserDefinedLiteralClass:
01406       return VisitCallExpr(cast<CallExpr>(S), asc);
01407 
01408     case Stmt::CaseStmtClass:
01409       return VisitCaseStmt(cast<CaseStmt>(S));
01410 
01411     case Stmt::ChooseExprClass:
01412       return VisitChooseExpr(cast<ChooseExpr>(S), asc);
01413 
01414     case Stmt::CompoundStmtClass:
01415       return VisitCompoundStmt(cast<CompoundStmt>(S));
01416 
01417     case Stmt::ConditionalOperatorClass:
01418       return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
01419 
01420     case Stmt::ContinueStmtClass:
01421       return VisitContinueStmt(cast<ContinueStmt>(S));
01422 
01423     case Stmt::CXXCatchStmtClass:
01424       return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
01425 
01426     case Stmt::ExprWithCleanupsClass:
01427       return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
01428 
01429     case Stmt::CXXDefaultArgExprClass:
01430     case Stmt::CXXDefaultInitExprClass:
01431       // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
01432       // called function's declaration, not by the caller. If we simply add
01433       // this expression to the CFG, we could end up with the same Expr
01434       // appearing multiple times.
01435       // PR13385 / <rdar://problem/12156507>
01436       //
01437       // It's likewise possible for multiple CXXDefaultInitExprs for the same
01438       // expression to be used in the same function (through aggregate
01439       // initialization).
01440       return VisitStmt(S, asc);
01441 
01442     case Stmt::CXXBindTemporaryExprClass:
01443       return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
01444 
01445     case Stmt::CXXConstructExprClass:
01446       return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
01447 
01448     case Stmt::CXXNewExprClass:
01449       return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
01450 
01451     case Stmt::CXXDeleteExprClass:
01452       return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
01453 
01454     case Stmt::CXXFunctionalCastExprClass:
01455       return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
01456 
01457     case Stmt::CXXTemporaryObjectExprClass:
01458       return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
01459 
01460     case Stmt::CXXThrowExprClass:
01461       return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
01462 
01463     case Stmt::CXXTryStmtClass:
01464       return VisitCXXTryStmt(cast<CXXTryStmt>(S));
01465 
01466     case Stmt::CXXForRangeStmtClass:
01467       return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
01468 
01469     case Stmt::DeclStmtClass:
01470       return VisitDeclStmt(cast<DeclStmt>(S));
01471 
01472     case Stmt::DefaultStmtClass:
01473       return VisitDefaultStmt(cast<DefaultStmt>(S));
01474 
01475     case Stmt::DoStmtClass:
01476       return VisitDoStmt(cast<DoStmt>(S));
01477 
01478     case Stmt::ForStmtClass:
01479       return VisitForStmt(cast<ForStmt>(S));
01480 
01481     case Stmt::GotoStmtClass:
01482       return VisitGotoStmt(cast<GotoStmt>(S));
01483 
01484     case Stmt::IfStmtClass:
01485       return VisitIfStmt(cast<IfStmt>(S));
01486 
01487     case Stmt::ImplicitCastExprClass:
01488       return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
01489 
01490     case Stmt::IndirectGotoStmtClass:
01491       return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
01492 
01493     case Stmt::LabelStmtClass:
01494       return VisitLabelStmt(cast<LabelStmt>(S));
01495 
01496     case Stmt::LambdaExprClass:
01497       return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
01498 
01499     case Stmt::MemberExprClass:
01500       return VisitMemberExpr(cast<MemberExpr>(S), asc);
01501 
01502     case Stmt::NullStmtClass:
01503       return Block;
01504 
01505     case Stmt::ObjCAtCatchStmtClass:
01506       return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
01507 
01508     case Stmt::ObjCAutoreleasePoolStmtClass:
01509     return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
01510 
01511     case Stmt::ObjCAtSynchronizedStmtClass:
01512       return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
01513 
01514     case Stmt::ObjCAtThrowStmtClass:
01515       return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
01516 
01517     case Stmt::ObjCAtTryStmtClass:
01518       return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
01519 
01520     case Stmt::ObjCForCollectionStmtClass:
01521       return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
01522 
01523     case Stmt::OpaqueValueExprClass:
01524       return Block;
01525 
01526     case Stmt::PseudoObjectExprClass:
01527       return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
01528 
01529     case Stmt::ReturnStmtClass:
01530       return VisitReturnStmt(cast<ReturnStmt>(S));
01531 
01532     case Stmt::UnaryExprOrTypeTraitExprClass:
01533       return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
01534                                            asc);
01535 
01536     case Stmt::StmtExprClass:
01537       return VisitStmtExpr(cast<StmtExpr>(S), asc);
01538 
01539     case Stmt::SwitchStmtClass:
01540       return VisitSwitchStmt(cast<SwitchStmt>(S));
01541 
01542     case Stmt::UnaryOperatorClass:
01543       return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
01544 
01545     case Stmt::WhileStmtClass:
01546       return VisitWhileStmt(cast<WhileStmt>(S));
01547   }
01548 }
01549 
01550 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
01551   if (asc.alwaysAdd(*this, S)) {
01552     autoCreateBlock();
01553     appendStmt(Block, S);
01554   }
01555 
01556   return VisitChildren(S);
01557 }
01558 
01559 /// VisitChildren - Visit the children of a Stmt.
01560 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
01561   CFGBlock *B = Block;
01562 
01563   // Visit the children in their reverse order so that they appear in
01564   // left-to-right (natural) order in the CFG.
01565   reverse_children RChildren(S);
01566   for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
01567        I != E; ++I) {
01568     if (Stmt *Child = *I)
01569       if (CFGBlock *R = Visit(Child))
01570         B = R;
01571   }
01572   return B;
01573 }
01574 
01575 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
01576                                          AddStmtChoice asc) {
01577   AddressTakenLabels.insert(A->getLabel());
01578 
01579   if (asc.alwaysAdd(*this, A)) {
01580     autoCreateBlock();
01581     appendStmt(Block, A);
01582   }
01583 
01584   return Block;
01585 }
01586 
01587 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
01588            AddStmtChoice asc) {
01589   if (asc.alwaysAdd(*this, U)) {
01590     autoCreateBlock();
01591     appendStmt(Block, U);
01592   }
01593 
01594   return Visit(U->getSubExpr(), AddStmtChoice());
01595 }
01596 
01597 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
01598   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
01599   appendStmt(ConfluenceBlock, B);
01600 
01601   if (badCFG)
01602     return nullptr;
01603 
01604   return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
01605                               ConfluenceBlock).first;
01606 }
01607 
01608 std::pair<CFGBlock*, CFGBlock*>
01609 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
01610                                  Stmt *Term,
01611                                  CFGBlock *TrueBlock,
01612                                  CFGBlock *FalseBlock) {
01613 
01614   // Introspect the RHS.  If it is a nested logical operation, we recursively
01615   // build the CFG using this function.  Otherwise, resort to default
01616   // CFG construction behavior.
01617   Expr *RHS = B->getRHS()->IgnoreParens();
01618   CFGBlock *RHSBlock, *ExitBlock;
01619 
01620   do {
01621     if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
01622       if (B_RHS->isLogicalOp()) {
01623         std::tie(RHSBlock, ExitBlock) =
01624           VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
01625         break;
01626       }
01627 
01628     // The RHS is not a nested logical operation.  Don't push the terminator
01629     // down further, but instead visit RHS and construct the respective
01630     // pieces of the CFG, and link up the RHSBlock with the terminator
01631     // we have been provided.
01632     ExitBlock = RHSBlock = createBlock(false);
01633 
01634     if (!Term) {
01635       assert(TrueBlock == FalseBlock);
01636       addSuccessor(RHSBlock, TrueBlock);
01637     }
01638     else {
01639       RHSBlock->setTerminator(Term);
01640       TryResult KnownVal = tryEvaluateBool(RHS);
01641       if (!KnownVal.isKnown())
01642         KnownVal = tryEvaluateBool(B);
01643       addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
01644       addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
01645     }
01646 
01647     Block = RHSBlock;
01648     RHSBlock = addStmt(RHS);
01649   }
01650   while (false);
01651 
01652   if (badCFG)
01653     return std::make_pair(nullptr, nullptr);
01654 
01655   // Generate the blocks for evaluating the LHS.
01656   Expr *LHS = B->getLHS()->IgnoreParens();
01657 
01658   if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
01659     if (B_LHS->isLogicalOp()) {
01660       if (B->getOpcode() == BO_LOr)
01661         FalseBlock = RHSBlock;
01662       else
01663         TrueBlock = RHSBlock;
01664 
01665       // For the LHS, treat 'B' as the terminator that we want to sink
01666       // into the nested branch.  The RHS always gets the top-most
01667       // terminator.
01668       return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
01669     }
01670 
01671   // Create the block evaluating the LHS.
01672   // This contains the '&&' or '||' as the terminator.
01673   CFGBlock *LHSBlock = createBlock(false);
01674   LHSBlock->setTerminator(B);
01675 
01676   Block = LHSBlock;
01677   CFGBlock *EntryLHSBlock = addStmt(LHS);
01678 
01679   if (badCFG)
01680     return std::make_pair(nullptr, nullptr);
01681 
01682   // See if this is a known constant.
01683   TryResult KnownVal = tryEvaluateBool(LHS);
01684 
01685   // Now link the LHSBlock with RHSBlock.
01686   if (B->getOpcode() == BO_LOr) {
01687     addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
01688     addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
01689   } else {
01690     assert(B->getOpcode() == BO_LAnd);
01691     addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
01692     addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
01693   }
01694 
01695   return std::make_pair(EntryLHSBlock, ExitBlock);
01696 }
01697 
01698 
01699 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
01700                                           AddStmtChoice asc) {
01701    // && or ||
01702   if (B->isLogicalOp())
01703     return VisitLogicalOperator(B);
01704 
01705   if (B->getOpcode() == BO_Comma) { // ,
01706     autoCreateBlock();
01707     appendStmt(Block, B);
01708     addStmt(B->getRHS());
01709     return addStmt(B->getLHS());
01710   }
01711 
01712   if (B->isAssignmentOp()) {
01713     if (asc.alwaysAdd(*this, B)) {
01714       autoCreateBlock();
01715       appendStmt(Block, B);
01716     }
01717     Visit(B->getLHS());
01718     return Visit(B->getRHS());
01719   }
01720 
01721   if (asc.alwaysAdd(*this, B)) {
01722     autoCreateBlock();
01723     appendStmt(Block, B);
01724   }
01725 
01726   CFGBlock *RBlock = Visit(B->getRHS());
01727   CFGBlock *LBlock = Visit(B->getLHS());
01728   // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
01729   // containing a DoStmt, and the LHS doesn't create a new block, then we should
01730   // return RBlock.  Otherwise we'll incorrectly return NULL.
01731   return (LBlock ? LBlock : RBlock);
01732 }
01733 
01734 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
01735   if (asc.alwaysAdd(*this, E)) {
01736     autoCreateBlock();
01737     appendStmt(Block, E);
01738   }
01739   return Block;
01740 }
01741 
01742 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
01743   // "break" is a control-flow statement.  Thus we stop processing the current
01744   // block.
01745   if (badCFG)
01746     return nullptr;
01747 
01748   // Now create a new block that ends with the break statement.
01749   Block = createBlock(false);
01750   Block->setTerminator(B);
01751 
01752   // If there is no target for the break, then we are looking at an incomplete
01753   // AST.  This means that the CFG cannot be constructed.
01754   if (BreakJumpTarget.block) {
01755     addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
01756     addSuccessor(Block, BreakJumpTarget.block);
01757   } else
01758     badCFG = true;
01759 
01760 
01761   return Block;
01762 }
01763 
01764 static bool CanThrow(Expr *E, ASTContext &Ctx) {
01765   QualType Ty = E->getType();
01766   if (Ty->isFunctionPointerType())
01767     Ty = Ty->getAs<PointerType>()->getPointeeType();
01768   else if (Ty->isBlockPointerType())
01769     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
01770 
01771   const FunctionType *FT = Ty->getAs<FunctionType>();
01772   if (FT) {
01773     if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
01774       if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
01775           Proto->isNothrow(Ctx))
01776         return false;
01777   }
01778   return true;
01779 }
01780 
01781 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
01782   // Compute the callee type.
01783   QualType calleeType = C->getCallee()->getType();
01784   if (calleeType == Context->BoundMemberTy) {
01785     QualType boundType = Expr::findBoundMemberType(C->getCallee());
01786 
01787     // We should only get a null bound type if processing a dependent
01788     // CFG.  Recover by assuming nothing.
01789     if (!boundType.isNull()) calleeType = boundType;
01790   }
01791 
01792   // If this is a call to a no-return function, this stops the block here.
01793   bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
01794 
01795   bool AddEHEdge = false;
01796 
01797   // Languages without exceptions are assumed to not throw.
01798   if (Context->getLangOpts().Exceptions) {
01799     if (BuildOpts.AddEHEdges)
01800       AddEHEdge = true;
01801   }
01802 
01803   // If this is a call to a builtin function, it might not actually evaluate
01804   // its arguments. Don't add them to the CFG if this is the case.
01805   bool OmitArguments = false;
01806 
01807   if (FunctionDecl *FD = C->getDirectCallee()) {
01808     if (FD->isNoReturn())
01809       NoReturn = true;
01810     if (FD->hasAttr<NoThrowAttr>())
01811       AddEHEdge = false;
01812     if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
01813       OmitArguments = true;
01814   }
01815 
01816   if (!CanThrow(C->getCallee(), *Context))
01817     AddEHEdge = false;
01818 
01819   if (OmitArguments) {
01820     assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
01821     assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
01822     autoCreateBlock();
01823     appendStmt(Block, C);
01824     return Visit(C->getCallee());
01825   }
01826 
01827   if (!NoReturn && !AddEHEdge) {
01828     return VisitStmt(C, asc.withAlwaysAdd(true));
01829   }
01830 
01831   if (Block) {
01832     Succ = Block;
01833     if (badCFG)
01834       return nullptr;
01835   }
01836 
01837   if (NoReturn)
01838     Block = createNoReturnBlock();
01839   else
01840     Block = createBlock();
01841 
01842   appendStmt(Block, C);
01843 
01844   if (AddEHEdge) {
01845     // Add exceptional edges.
01846     if (TryTerminatedBlock)
01847       addSuccessor(Block, TryTerminatedBlock);
01848     else
01849       addSuccessor(Block, &cfg->getExit());
01850   }
01851 
01852   return VisitChildren(C);
01853 }
01854 
01855 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
01856                                       AddStmtChoice asc) {
01857   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
01858   appendStmt(ConfluenceBlock, C);
01859   if (badCFG)
01860     return nullptr;
01861 
01862   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
01863   Succ = ConfluenceBlock;
01864   Block = nullptr;
01865   CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
01866   if (badCFG)
01867     return nullptr;
01868 
01869   Succ = ConfluenceBlock;
01870   Block = nullptr;
01871   CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
01872   if (badCFG)
01873     return nullptr;
01874 
01875   Block = createBlock(false);
01876   // See if this is a known constant.
01877   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
01878   addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
01879   addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
01880   Block->setTerminator(C);
01881   return addStmt(C->getCond());
01882 }
01883 
01884 
01885 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
01886   addLocalScopeAndDtors(C);
01887   CFGBlock *LastBlock = Block;
01888 
01889   for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
01890        I != E; ++I ) {
01891     // If we hit a segment of code just containing ';' (NullStmts), we can
01892     // get a null block back.  In such cases, just use the LastBlock
01893     if (CFGBlock *newBlock = addStmt(*I))
01894       LastBlock = newBlock;
01895 
01896     if (badCFG)
01897       return nullptr;
01898   }
01899 
01900   return LastBlock;
01901 }
01902 
01903 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
01904                                                AddStmtChoice asc) {
01905   const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
01906   const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
01907 
01908   // Create the confluence block that will "merge" the results of the ternary
01909   // expression.
01910   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
01911   appendStmt(ConfluenceBlock, C);
01912   if (badCFG)
01913     return nullptr;
01914 
01915   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
01916 
01917   // Create a block for the LHS expression if there is an LHS expression.  A
01918   // GCC extension allows LHS to be NULL, causing the condition to be the
01919   // value that is returned instead.
01920   //  e.g: x ?: y is shorthand for: x ? x : y;
01921   Succ = ConfluenceBlock;
01922   Block = nullptr;
01923   CFGBlock *LHSBlock = nullptr;
01924   const Expr *trueExpr = C->getTrueExpr();
01925   if (trueExpr != opaqueValue) {
01926     LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
01927     if (badCFG)
01928       return nullptr;
01929     Block = nullptr;
01930   }
01931   else
01932     LHSBlock = ConfluenceBlock;
01933 
01934   // Create the block for the RHS expression.
01935   Succ = ConfluenceBlock;
01936   CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
01937   if (badCFG)
01938     return nullptr;
01939 
01940   // If the condition is a logical '&&' or '||', build a more accurate CFG.
01941   if (BinaryOperator *Cond =
01942         dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
01943     if (Cond->isLogicalOp())
01944       return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
01945 
01946   // Create the block that will contain the condition.
01947   Block = createBlock(false);
01948 
01949   // See if this is a known constant.
01950   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
01951   addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
01952   addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
01953   Block->setTerminator(C);
01954   Expr *condExpr = C->getCond();
01955 
01956   if (opaqueValue) {
01957     // Run the condition expression if it's not trivially expressed in
01958     // terms of the opaque value (or if there is no opaque value).
01959     if (condExpr != opaqueValue)
01960       addStmt(condExpr);
01961 
01962     // Before that, run the common subexpression if there was one.
01963     // At least one of this or the above will be run.
01964     return addStmt(BCO->getCommon());
01965   }
01966   
01967   return addStmt(condExpr);
01968 }
01969 
01970 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
01971   // Check if the Decl is for an __label__.  If so, elide it from the
01972   // CFG entirely.
01973   if (isa<LabelDecl>(*DS->decl_begin()))
01974     return Block;
01975   
01976   // This case also handles static_asserts.
01977   if (DS->isSingleDecl())
01978     return VisitDeclSubExpr(DS);
01979 
01980   CFGBlock *B = nullptr;
01981 
01982   // Build an individual DeclStmt for each decl.
01983   for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
01984                                        E = DS->decl_rend();
01985        I != E; ++I) {
01986     // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
01987     unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
01988                ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
01989 
01990     // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
01991     // automatically freed with the CFG.
01992     DeclGroupRef DG(*I);
01993     Decl *D = *I;
01994     void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
01995     DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
01996     cfg->addSyntheticDeclStmt(DSNew, DS);
01997 
01998     // Append the fake DeclStmt to block.
01999     B = VisitDeclSubExpr(DSNew);
02000   }
02001 
02002   return B;
02003 }
02004 
02005 /// VisitDeclSubExpr - Utility method to add block-level expressions for
02006 /// DeclStmts and initializers in them.
02007 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
02008   assert(DS->isSingleDecl() && "Can handle single declarations only.");
02009   VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
02010 
02011   if (!VD) {
02012     // Of everything that can be declared in a DeclStmt, only VarDecls impact
02013     // runtime semantics.
02014     return Block;
02015   }
02016 
02017   bool HasTemporaries = false;
02018 
02019   // Guard static initializers under a branch.
02020   CFGBlock *blockAfterStaticInit = nullptr;
02021 
02022   if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
02023     // For static variables, we need to create a branch to track
02024     // whether or not they are initialized.
02025     if (Block) {
02026       Succ = Block;
02027       Block = nullptr;
02028       if (badCFG)
02029         return nullptr;
02030     }
02031     blockAfterStaticInit = Succ;
02032   }
02033 
02034   // Destructors of temporaries in initialization expression should be called
02035   // after initialization finishes.
02036   Expr *Init = VD->getInit();
02037   if (Init) {
02038     HasTemporaries = isa<ExprWithCleanups>(Init);
02039 
02040     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
02041       // Generate destructors for temporaries in initialization expression.
02042       TempDtorContext Context;
02043       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
02044                              /*BindToTemporary=*/false, Context);
02045     }
02046   }
02047 
02048   autoCreateBlock();
02049   appendStmt(Block, DS);
02050   
02051   // Keep track of the last non-null block, as 'Block' can be nulled out
02052   // if the initializer expression is something like a 'while' in a
02053   // statement-expression.
02054   CFGBlock *LastBlock = Block;
02055 
02056   if (Init) {
02057     if (HasTemporaries) {
02058       // For expression with temporaries go directly to subexpression to omit
02059       // generating destructors for the second time.
02060       ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
02061       if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
02062         LastBlock = newBlock;
02063     }
02064     else {
02065       if (CFGBlock *newBlock = Visit(Init))
02066         LastBlock = newBlock;
02067     }
02068   }
02069 
02070   // If the type of VD is a VLA, then we must process its size expressions.
02071   for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
02072        VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
02073     if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
02074       LastBlock = newBlock;
02075   }
02076 
02077   // Remove variable from local scope.
02078   if (ScopePos && VD == *ScopePos)
02079     ++ScopePos;
02080 
02081   CFGBlock *B = LastBlock;
02082   if (blockAfterStaticInit) {
02083     Succ = B;
02084     Block = createBlock(false);
02085     Block->setTerminator(DS);
02086     addSuccessor(Block, blockAfterStaticInit);
02087     addSuccessor(Block, B);
02088     B = Block;
02089   }
02090 
02091   return B;
02092 }
02093 
02094 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
02095   // We may see an if statement in the middle of a basic block, or it may be the
02096   // first statement we are processing.  In either case, we create a new basic
02097   // block.  First, we create the blocks for the then...else statements, and
02098   // then we create the block containing the if statement.  If we were in the
02099   // middle of a block, we stop processing that block.  That block is then the
02100   // implicit successor for the "then" and "else" clauses.
02101 
02102   // Save local scope position because in case of condition variable ScopePos
02103   // won't be restored when traversing AST.
02104   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
02105 
02106   // Create local scope for possible condition variable.
02107   // Store scope position. Add implicit destructor.
02108   if (VarDecl *VD = I->getConditionVariable()) {
02109     LocalScope::const_iterator BeginScopePos = ScopePos;
02110     addLocalScopeForVarDecl(VD);
02111     addAutomaticObjDtors(ScopePos, BeginScopePos, I);
02112   }
02113 
02114   // The block we were processing is now finished.  Make it the successor
02115   // block.
02116   if (Block) {
02117     Succ = Block;
02118     if (badCFG)
02119       return nullptr;
02120   }
02121 
02122   // Process the false branch.
02123   CFGBlock *ElseBlock = Succ;
02124 
02125   if (Stmt *Else = I->getElse()) {
02126     SaveAndRestore<CFGBlock*> sv(Succ);
02127 
02128     // NULL out Block so that the recursive call to Visit will
02129     // create a new basic block.
02130     Block = nullptr;
02131 
02132     // If branch is not a compound statement create implicit scope
02133     // and add destructors.
02134     if (!isa<CompoundStmt>(Else))
02135       addLocalScopeAndDtors(Else);
02136 
02137     ElseBlock = addStmt(Else);
02138 
02139     if (!ElseBlock) // Can occur when the Else body has all NullStmts.
02140       ElseBlock = sv.get();
02141     else if (Block) {
02142       if (badCFG)
02143         return nullptr;
02144     }
02145   }
02146 
02147   // Process the true branch.
02148   CFGBlock *ThenBlock;
02149   {
02150     Stmt *Then = I->getThen();
02151     assert(Then);
02152     SaveAndRestore<CFGBlock*> sv(Succ);
02153     Block = nullptr;
02154 
02155     // If branch is not a compound statement create implicit scope
02156     // and add destructors.
02157     if (!isa<CompoundStmt>(Then))
02158       addLocalScopeAndDtors(Then);
02159 
02160     ThenBlock = addStmt(Then);
02161 
02162     if (!ThenBlock) {
02163       // We can reach here if the "then" body has all NullStmts.
02164       // Create an empty block so we can distinguish between true and false
02165       // branches in path-sensitive analyses.
02166       ThenBlock = createBlock(false);
02167       addSuccessor(ThenBlock, sv.get());
02168     } else if (Block) {
02169       if (badCFG)
02170         return nullptr;
02171     }
02172   }
02173 
02174   // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
02175   // having these handle the actual control-flow jump.  Note that
02176   // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
02177   // we resort to the old control-flow behavior.  This special handling
02178   // removes infeasible paths from the control-flow graph by having the
02179   // control-flow transfer of '&&' or '||' go directly into the then/else
02180   // blocks directly.
02181   if (!I->getConditionVariable())
02182     if (BinaryOperator *Cond =
02183             dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
02184       if (Cond->isLogicalOp())
02185         return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
02186 
02187   // Now create a new block containing the if statement.
02188   Block = createBlock(false);
02189 
02190   // Set the terminator of the new block to the If statement.
02191   Block->setTerminator(I);
02192 
02193   // See if this is a known constant.
02194   const TryResult &KnownVal = tryEvaluateBool(I->getCond());
02195 
02196   // Add the successors.  If we know that specific branches are
02197   // unreachable, inform addSuccessor() of that knowledge.
02198   addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
02199   addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
02200 
02201   // Add the condition as the last statement in the new block.  This may create
02202   // new blocks as the condition may contain control-flow.  Any newly created
02203   // blocks will be pointed to be "Block".
02204   CFGBlock *LastBlock = addStmt(I->getCond());
02205 
02206   // Finally, if the IfStmt contains a condition variable, add it and its
02207   // initializer to the CFG.
02208   if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
02209     autoCreateBlock();
02210     LastBlock = addStmt(const_cast<DeclStmt *>(DS));
02211   }
02212 
02213   return LastBlock;
02214 }
02215 
02216 
02217 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
02218   // If we were in the middle of a block we stop processing that block.
02219   //
02220   // NOTE: If a "return" appears in the middle of a block, this means that the
02221   //       code afterwards is DEAD (unreachable).  We still keep a basic block
02222   //       for that code; a simple "mark-and-sweep" from the entry block will be
02223   //       able to report such dead blocks.
02224 
02225   // Create the new block.
02226   Block = createBlock(false);
02227 
02228   addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
02229 
02230   // If the one of the destructors does not return, we already have the Exit
02231   // block as a successor.
02232   if (!Block->hasNoReturnElement())
02233     addSuccessor(Block, &cfg->getExit());
02234 
02235   // Add the return statement to the block.  This may create new blocks if R
02236   // contains control-flow (short-circuit operations).
02237   return VisitStmt(R, AddStmtChoice::AlwaysAdd);
02238 }
02239 
02240 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
02241   // Get the block of the labeled statement.  Add it to our map.
02242   addStmt(L->getSubStmt());
02243   CFGBlock *LabelBlock = Block;
02244 
02245   if (!LabelBlock)              // This can happen when the body is empty, i.e.
02246     LabelBlock = createBlock(); // scopes that only contains NullStmts.
02247 
02248   assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
02249          "label already in map");
02250   LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
02251 
02252   // Labels partition blocks, so this is the end of the basic block we were
02253   // processing (L is the block's label).  Because this is label (and we have
02254   // already processed the substatement) there is no extra control-flow to worry
02255   // about.
02256   LabelBlock->setLabel(L);
02257   if (badCFG)
02258     return nullptr;
02259 
02260   // We set Block to NULL to allow lazy creation of a new block (if necessary);
02261   Block = nullptr;
02262 
02263   // This block is now the implicit successor of other blocks.
02264   Succ = LabelBlock;
02265 
02266   return LabelBlock;
02267 }
02268 
02269 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
02270   CFGBlock *LastBlock = VisitNoRecurse(E, asc);
02271   for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
02272        et = E->capture_init_end(); it != et; ++it) {
02273     if (Expr *Init = *it) {
02274       CFGBlock *Tmp = Visit(Init);
02275       if (Tmp)
02276         LastBlock = Tmp;
02277     }
02278   }
02279   return LastBlock;
02280 }
02281   
02282 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
02283   // Goto is a control-flow statement.  Thus we stop processing the current
02284   // block and create a new one.
02285 
02286   Block = createBlock(false);
02287   Block->setTerminator(G);
02288 
02289   // If we already know the mapping to the label block add the successor now.
02290   LabelMapTy::iterator I = LabelMap.find(G->getLabel());
02291 
02292   if (I == LabelMap.end())
02293     // We will need to backpatch this block later.
02294     BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
02295   else {
02296     JumpTarget JT = I->second;
02297     addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
02298     addSuccessor(Block, JT.block);
02299   }
02300 
02301   return Block;
02302 }
02303 
02304 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
02305   CFGBlock *LoopSuccessor = nullptr;
02306 
02307   // Save local scope position because in case of condition variable ScopePos
02308   // won't be restored when traversing AST.
02309   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
02310 
02311   // Create local scope for init statement and possible condition variable.
02312   // Add destructor for init statement and condition variable.
02313   // Store scope position for continue statement.
02314   if (Stmt *Init = F->getInit())
02315     addLocalScopeForStmt(Init);
02316   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
02317 
02318   if (VarDecl *VD = F->getConditionVariable())
02319     addLocalScopeForVarDecl(VD);
02320   LocalScope::const_iterator ContinueScopePos = ScopePos;
02321 
02322   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
02323 
02324   // "for" is a control-flow statement.  Thus we stop processing the current
02325   // block.
02326   if (Block) {
02327     if (badCFG)
02328       return nullptr;
02329     LoopSuccessor = Block;
02330   } else
02331     LoopSuccessor = Succ;
02332 
02333   // Save the current value for the break targets.
02334   // All breaks should go to the code following the loop.
02335   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
02336   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
02337 
02338   CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
02339 
02340   // Now create the loop body.
02341   {
02342     assert(F->getBody());
02343 
02344     // Save the current values for Block, Succ, continue and break targets.
02345     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
02346     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
02347 
02348     // Create an empty block to represent the transition block for looping back
02349     // to the head of the loop.  If we have increment code, it will
02350     // go in this block as well.
02351     Block = Succ = TransitionBlock = createBlock(false);
02352     TransitionBlock->setLoopTarget(F);
02353 
02354     if (Stmt *I = F->getInc()) {
02355       // Generate increment code in its own basic block.  This is the target of
02356       // continue statements.
02357       Succ = addStmt(I);
02358     }
02359 
02360     // Finish up the increment (or empty) block if it hasn't been already.
02361     if (Block) {
02362       assert(Block == Succ);
02363       if (badCFG)
02364         return nullptr;
02365       Block = nullptr;
02366     }
02367 
02368    // The starting block for the loop increment is the block that should
02369    // represent the 'loop target' for looping back to the start of the loop.
02370    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
02371    ContinueJumpTarget.block->setLoopTarget(F);
02372 
02373     // Loop body should end with destructor of Condition variable (if any).
02374     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
02375 
02376     // If body is not a compound statement create implicit scope
02377     // and add destructors.
02378     if (!isa<CompoundStmt>(F->getBody()))
02379       addLocalScopeAndDtors(F->getBody());
02380 
02381     // Now populate the body block, and in the process create new blocks as we
02382     // walk the body of the loop.
02383     BodyBlock = addStmt(F->getBody());
02384 
02385     if (!BodyBlock) {
02386       // In the case of "for (...;...;...);" we can have a null BodyBlock.
02387       // Use the continue jump target as the proxy for the body.
02388       BodyBlock = ContinueJumpTarget.block;
02389     }
02390     else if (badCFG)
02391       return nullptr;
02392   }
02393   
02394   // Because of short-circuit evaluation, the condition of the loop can span
02395   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
02396   // evaluate the condition.
02397   CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
02398 
02399   do {
02400     Expr *C = F->getCond();
02401 
02402     // Specially handle logical operators, which have a slightly
02403     // more optimal CFG representation.
02404     if (BinaryOperator *Cond =
02405             dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
02406       if (Cond->isLogicalOp()) {
02407         std::tie(EntryConditionBlock, ExitConditionBlock) =
02408           VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
02409         break;
02410       }
02411 
02412     // The default case when not handling logical operators.
02413     EntryConditionBlock = ExitConditionBlock = createBlock(false);
02414     ExitConditionBlock->setTerminator(F);
02415 
02416     // See if this is a known constant.
02417     TryResult KnownVal(true);
02418 
02419     if (C) {
02420       // Now add the actual condition to the condition block.
02421       // Because the condition itself may contain control-flow, new blocks may
02422       // be created.  Thus we update "Succ" after adding the condition.
02423       Block = ExitConditionBlock;
02424       EntryConditionBlock = addStmt(C);
02425 
02426       // If this block contains a condition variable, add both the condition
02427       // variable and initializer to the CFG.
02428       if (VarDecl *VD = F->getConditionVariable()) {
02429         if (Expr *Init = VD->getInit()) {
02430           autoCreateBlock();
02431           appendStmt(Block, F->getConditionVariableDeclStmt());
02432           EntryConditionBlock = addStmt(Init);
02433           assert(Block == EntryConditionBlock);
02434         }
02435       }
02436 
02437       if (Block && badCFG)
02438         return nullptr;
02439 
02440       KnownVal = tryEvaluateBool(C);
02441     }
02442 
02443     // Add the loop body entry as a successor to the condition.
02444     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
02445     // Link up the condition block with the code that follows the loop.  (the
02446     // false branch).
02447     addSuccessor(ExitConditionBlock,
02448                  KnownVal.isTrue() ? nullptr : LoopSuccessor);
02449 
02450   } while (false);
02451 
02452   // Link up the loop-back block to the entry condition block.
02453   addSuccessor(TransitionBlock, EntryConditionBlock);
02454   
02455   // The condition block is the implicit successor for any code above the loop.
02456   Succ = EntryConditionBlock;
02457 
02458   // If the loop contains initialization, create a new block for those
02459   // statements.  This block can also contain statements that precede the loop.
02460   if (Stmt *I = F->getInit()) {
02461     Block = createBlock();
02462     return addStmt(I);
02463   }
02464 
02465   // There is no loop initialization.  We are thus basically a while loop.
02466   // NULL out Block to force lazy block construction.
02467   Block = nullptr;
02468   Succ = EntryConditionBlock;
02469   return EntryConditionBlock;
02470 }
02471 
02472 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
02473   if (asc.alwaysAdd(*this, M)) {
02474     autoCreateBlock();
02475     appendStmt(Block, M);
02476   }
02477   return Visit(M->getBase());
02478 }
02479 
02480 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
02481   // Objective-C fast enumeration 'for' statements:
02482   //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
02483   //
02484   //  for ( Type newVariable in collection_expression ) { statements }
02485   //
02486   //  becomes:
02487   //
02488   //   prologue:
02489   //     1. collection_expression
02490   //     T. jump to loop_entry
02491   //   loop_entry:
02492   //     1. side-effects of element expression
02493   //     1. ObjCForCollectionStmt [performs binding to newVariable]
02494   //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
02495   //   TB:
02496   //     statements
02497   //     T. jump to loop_entry
02498   //   FB:
02499   //     what comes after
02500   //
02501   //  and
02502   //
02503   //  Type existingItem;
02504   //  for ( existingItem in expression ) { statements }
02505   //
02506   //  becomes:
02507   //
02508   //   the same with newVariable replaced with existingItem; the binding works
02509   //   the same except that for one ObjCForCollectionStmt::getElement() returns
02510   //   a DeclStmt and the other returns a DeclRefExpr.
02511   //
02512 
02513   CFGBlock *LoopSuccessor = nullptr;
02514 
02515   if (Block) {
02516     if (badCFG)
02517       return nullptr;
02518     LoopSuccessor = Block;
02519     Block = nullptr;
02520   } else
02521     LoopSuccessor = Succ;
02522 
02523   // Build the condition blocks.
02524   CFGBlock *ExitConditionBlock = createBlock(false);
02525 
02526   // Set the terminator for the "exit" condition block.
02527   ExitConditionBlock->setTerminator(S);
02528 
02529   // The last statement in the block should be the ObjCForCollectionStmt, which
02530   // performs the actual binding to 'element' and determines if there are any
02531   // more items in the collection.
02532   appendStmt(ExitConditionBlock, S);
02533   Block = ExitConditionBlock;
02534 
02535   // Walk the 'element' expression to see if there are any side-effects.  We
02536   // generate new blocks as necessary.  We DON'T add the statement by default to
02537   // the CFG unless it contains control-flow.
02538   CFGBlock *EntryConditionBlock = Visit(S->getElement(),
02539                                         AddStmtChoice::NotAlwaysAdd);
02540   if (Block) {
02541     if (badCFG)
02542       return nullptr;
02543     Block = nullptr;
02544   }
02545 
02546   // The condition block is the implicit successor for the loop body as well as
02547   // any code above the loop.
02548   Succ = EntryConditionBlock;
02549 
02550   // Now create the true branch.
02551   {
02552     // Save the current values for Succ, continue and break targets.
02553     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
02554     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
02555                                save_break(BreakJumpTarget);
02556 
02557     // Add an intermediate block between the BodyBlock and the
02558     // EntryConditionBlock to represent the "loop back" transition, for looping
02559     // back to the head of the loop.
02560     CFGBlock *LoopBackBlock = nullptr;
02561     Succ = LoopBackBlock = createBlock();
02562     LoopBackBlock->setLoopTarget(S);
02563     
02564     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
02565     ContinueJumpTarget = JumpTarget(Succ, ScopePos);
02566 
02567     CFGBlock *BodyBlock = addStmt(S->getBody());
02568 
02569     if (!BodyBlock)
02570       BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
02571     else if (Block) {
02572       if (badCFG)
02573         return nullptr;
02574     }
02575 
02576     // This new body block is a successor to our "exit" condition block.
02577     addSuccessor(ExitConditionBlock, BodyBlock);
02578   }
02579 
02580   // Link up the condition block with the code that follows the loop.
02581   // (the false branch).
02582   addSuccessor(ExitConditionBlock, LoopSuccessor);
02583 
02584   // Now create a prologue block to contain the collection expression.
02585   Block = createBlock();
02586   return addStmt(S->getCollection());
02587 }
02588 
02589 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
02590   // Inline the body.
02591   return addStmt(S->getSubStmt());
02592   // TODO: consider adding cleanups for the end of @autoreleasepool scope.
02593 }
02594 
02595 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
02596   // FIXME: Add locking 'primitives' to CFG for @synchronized.
02597 
02598   // Inline the body.
02599   CFGBlock *SyncBlock = addStmt(S->getSynchBody());
02600 
02601   // The sync body starts its own basic block.  This makes it a little easier
02602   // for diagnostic clients.
02603   if (SyncBlock) {
02604     if (badCFG)
02605       return nullptr;
02606 
02607     Block = nullptr;
02608     Succ = SyncBlock;
02609   }
02610 
02611   // Add the @synchronized to the CFG.
02612   autoCreateBlock();
02613   appendStmt(Block, S);
02614 
02615   // Inline the sync expression.
02616   return addStmt(S->getSynchExpr());
02617 }
02618 
02619 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
02620   // FIXME
02621   return NYS();
02622 }
02623 
02624 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
02625   autoCreateBlock();
02626 
02627   // Add the PseudoObject as the last thing.
02628   appendStmt(Block, E);
02629 
02630   CFGBlock *lastBlock = Block;  
02631 
02632   // Before that, evaluate all of the semantics in order.  In
02633   // CFG-land, that means appending them in reverse order.
02634   for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
02635     Expr *Semantic = E->getSemanticExpr(--i);
02636 
02637     // If the semantic is an opaque value, we're being asked to bind
02638     // it to its source expression.
02639     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
02640       Semantic = OVE->getSourceExpr();
02641 
02642     if (CFGBlock *B = Visit(Semantic))
02643       lastBlock = B;
02644   }
02645 
02646   return lastBlock;
02647 }
02648 
02649 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
02650   CFGBlock *LoopSuccessor = nullptr;
02651 
02652   // Save local scope position because in case of condition variable ScopePos
02653   // won't be restored when traversing AST.
02654   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
02655 
02656   // Create local scope for possible condition variable.
02657   // Store scope position for continue statement.
02658   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
02659   if (VarDecl *VD = W->getConditionVariable()) {
02660     addLocalScopeForVarDecl(VD);
02661     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
02662   }
02663 
02664   // "while" is a control-flow statement.  Thus we stop processing the current
02665   // block.
02666   if (Block) {
02667     if (badCFG)
02668       return nullptr;
02669     LoopSuccessor = Block;
02670     Block = nullptr;
02671   } else {
02672     LoopSuccessor = Succ;
02673   }
02674 
02675   CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
02676 
02677   // Process the loop body.
02678   {
02679     assert(W->getBody());
02680 
02681     // Save the current values for Block, Succ, continue and break targets.
02682     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
02683     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
02684                                save_break(BreakJumpTarget);
02685 
02686     // Create an empty block to represent the transition block for looping back
02687     // to the head of the loop.
02688     Succ = TransitionBlock = createBlock(false);
02689     TransitionBlock->setLoopTarget(W);
02690     ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
02691 
02692     // All breaks should go to the code following the loop.
02693     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
02694 
02695     // Loop body should end with destructor of Condition variable (if any).
02696     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
02697 
02698     // If body is not a compound statement create implicit scope
02699     // and add destructors.
02700     if (!isa<CompoundStmt>(W->getBody()))
02701       addLocalScopeAndDtors(W->getBody());
02702 
02703     // Create the body.  The returned block is the entry to the loop body.
02704     BodyBlock = addStmt(W->getBody());
02705 
02706     if (!BodyBlock)
02707       BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
02708     else if (Block && badCFG)
02709       return nullptr;
02710   }
02711 
02712   // Because of short-circuit evaluation, the condition of the loop can span
02713   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
02714   // evaluate the condition.
02715   CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
02716 
02717   do {
02718     Expr *C = W->getCond();
02719 
02720     // Specially handle logical operators, which have a slightly
02721     // more optimal CFG representation.
02722     if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
02723       if (Cond->isLogicalOp()) {
02724         std::tie(EntryConditionBlock, ExitConditionBlock) =
02725             VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
02726         break;
02727       }
02728 
02729     // The default case when not handling logical operators.
02730     ExitConditionBlock = createBlock(false);
02731     ExitConditionBlock->setTerminator(W);
02732 
02733     // Now add the actual condition to the condition block.
02734     // Because the condition itself may contain control-flow, new blocks may
02735     // be created.  Thus we update "Succ" after adding the condition.
02736     Block = ExitConditionBlock;
02737     Block = EntryConditionBlock = addStmt(C);
02738 
02739     // If this block contains a condition variable, add both the condition
02740     // variable and initializer to the CFG.
02741     if (VarDecl *VD = W->getConditionVariable()) {
02742       if (Expr *Init = VD->getInit()) {
02743         autoCreateBlock();
02744         appendStmt(Block, W->getConditionVariableDeclStmt());
02745         EntryConditionBlock = addStmt(Init);
02746         assert(Block == EntryConditionBlock);
02747       }
02748     }
02749 
02750     if (Block && badCFG)
02751       return nullptr;
02752 
02753     // See if this is a known constant.
02754     const TryResult& KnownVal = tryEvaluateBool(C);
02755 
02756     // Add the loop body entry as a successor to the condition.
02757     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
02758     // Link up the condition block with the code that follows the loop.  (the
02759     // false branch).
02760     addSuccessor(ExitConditionBlock,
02761                  KnownVal.isTrue() ? nullptr : LoopSuccessor);
02762 
02763   } while(false);
02764 
02765   // Link up the loop-back block to the entry condition block.
02766   addSuccessor(TransitionBlock, EntryConditionBlock);
02767 
02768   // There can be no more statements in the condition block since we loop back
02769   // to this block.  NULL out Block to force lazy creation of another block.
02770   Block = nullptr;
02771 
02772   // Return the condition block, which is the dominating block for the loop.
02773   Succ = EntryConditionBlock;
02774   return EntryConditionBlock;
02775 }
02776 
02777 
02778 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
02779   // FIXME: For now we pretend that @catch and the code it contains does not
02780   //  exit.
02781   return Block;
02782 }
02783 
02784 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
02785   // FIXME: This isn't complete.  We basically treat @throw like a return
02786   //  statement.
02787 
02788   // If we were in the middle of a block we stop processing that block.
02789   if (badCFG)
02790     return nullptr;
02791 
02792   // Create the new block.
02793   Block = createBlock(false);
02794 
02795   // The Exit block is the only successor.
02796   addSuccessor(Block, &cfg->getExit());
02797 
02798   // Add the statement to the block.  This may create new blocks if S contains
02799   // control-flow (short-circuit operations).
02800   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
02801 }
02802 
02803 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
02804   // If we were in the middle of a block we stop processing that block.
02805   if (badCFG)
02806     return nullptr;
02807 
02808   // Create the new block.
02809   Block = createBlock(false);
02810 
02811   if (TryTerminatedBlock)
02812     // The current try statement is the only successor.
02813     addSuccessor(Block, TryTerminatedBlock);
02814   else
02815     // otherwise the Exit block is the only successor.
02816     addSuccessor(Block, &cfg->getExit());
02817 
02818   // Add the statement to the block.  This may create new blocks if S contains
02819   // control-flow (short-circuit operations).
02820   return VisitStmt(T, AddStmtChoice::AlwaysAdd);
02821 }
02822 
02823 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
02824   CFGBlock *LoopSuccessor = nullptr;
02825 
02826   // "do...while" is a control-flow statement.  Thus we stop processing the
02827   // current block.
02828   if (Block) {
02829     if (badCFG)
02830       return nullptr;
02831     LoopSuccessor = Block;
02832   } else
02833     LoopSuccessor = Succ;
02834 
02835   // Because of short-circuit evaluation, the condition of the loop can span
02836   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
02837   // evaluate the condition.
02838   CFGBlock *ExitConditionBlock = createBlock(false);
02839   CFGBlock *EntryConditionBlock = ExitConditionBlock;
02840 
02841   // Set the terminator for the "exit" condition block.
02842   ExitConditionBlock->setTerminator(D);
02843 
02844   // Now add the actual condition to the condition block.  Because the condition
02845   // itself may contain control-flow, new blocks may be created.
02846   if (Stmt *C = D->getCond()) {
02847     Block = ExitConditionBlock;
02848     EntryConditionBlock = addStmt(C);
02849     if (Block) {
02850       if (badCFG)
02851         return nullptr;
02852     }
02853   }
02854 
02855   // The condition block is the implicit successor for the loop body.
02856   Succ = EntryConditionBlock;
02857 
02858   // See if this is a known constant.
02859   const TryResult &KnownVal = tryEvaluateBool(D->getCond());
02860 
02861   // Process the loop body.
02862   CFGBlock *BodyBlock = nullptr;
02863   {
02864     assert(D->getBody());
02865 
02866     // Save the current values for Block, Succ, and continue and break targets
02867     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
02868     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
02869         save_break(BreakJumpTarget);
02870 
02871     // All continues within this loop should go to the condition block
02872     ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
02873 
02874     // All breaks should go to the code following the loop.
02875     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
02876 
02877     // NULL out Block to force lazy instantiation of blocks for the body.
02878     Block = nullptr;
02879 
02880     // If body is not a compound statement create implicit scope
02881     // and add destructors.
02882     if (!isa<CompoundStmt>(D->getBody()))
02883       addLocalScopeAndDtors(D->getBody());
02884 
02885     // Create the body.  The returned block is the entry to the loop body.
02886     BodyBlock = addStmt(D->getBody());
02887 
02888     if (!BodyBlock)
02889       BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
02890     else if (Block) {
02891       if (badCFG)
02892         return nullptr;
02893     }
02894 
02895     if (!KnownVal.isFalse()) {
02896       // Add an intermediate block between the BodyBlock and the
02897       // ExitConditionBlock to represent the "loop back" transition.  Create an
02898       // empty block to represent the transition block for looping back to the
02899       // head of the loop.
02900       // FIXME: Can we do this more efficiently without adding another block?
02901       Block = nullptr;
02902       Succ = BodyBlock;
02903       CFGBlock *LoopBackBlock = createBlock();
02904       LoopBackBlock->setLoopTarget(D);
02905 
02906       // Add the loop body entry as a successor to the condition.
02907       addSuccessor(ExitConditionBlock, LoopBackBlock);
02908     }
02909     else
02910       addSuccessor(ExitConditionBlock, nullptr);
02911   }
02912 
02913   // Link up the condition block with the code that follows the loop.
02914   // (the false branch).
02915   addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
02916 
02917   // There can be no more statements in the body block(s) since we loop back to
02918   // the body.  NULL out Block to force lazy creation of another block.
02919   Block = nullptr;
02920 
02921   // Return the loop body, which is the dominating block for the loop.
02922   Succ = BodyBlock;
02923   return BodyBlock;
02924 }
02925 
02926 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
02927   // "continue" is a control-flow statement.  Thus we stop processing the
02928   // current block.
02929   if (badCFG)
02930     return nullptr;
02931 
02932   // Now create a new block that ends with the continue statement.
02933   Block = createBlock(false);
02934   Block->setTerminator(C);
02935 
02936   // If there is no target for the continue, then we are looking at an
02937   // incomplete AST.  This means the CFG cannot be constructed.
02938   if (ContinueJumpTarget.block) {
02939     addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
02940     addSuccessor(Block, ContinueJumpTarget.block);
02941   } else
02942     badCFG = true;
02943 
02944   return Block;
02945 }
02946 
02947 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
02948                                                     AddStmtChoice asc) {
02949 
02950   if (asc.alwaysAdd(*this, E)) {
02951     autoCreateBlock();
02952     appendStmt(Block, E);
02953   }
02954 
02955   // VLA types have expressions that must be evaluated.
02956   CFGBlock *lastBlock = Block;
02957   
02958   if (E->isArgumentType()) {
02959     for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
02960          VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
02961       lastBlock = addStmt(VA->getSizeExpr());
02962   }
02963   return lastBlock;
02964 }
02965 
02966 /// VisitStmtExpr - Utility method to handle (nested) statement
02967 ///  expressions (a GCC extension).
02968 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
02969   if (asc.alwaysAdd(*this, SE)) {
02970     autoCreateBlock();
02971     appendStmt(Block, SE);
02972   }
02973   return VisitCompoundStmt(SE->getSubStmt());
02974 }
02975 
02976 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
02977   // "switch" is a control-flow statement.  Thus we stop processing the current
02978   // block.
02979   CFGBlock *SwitchSuccessor = nullptr;
02980 
02981   // Save local scope position because in case of condition variable ScopePos
02982   // won't be restored when traversing AST.
02983   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
02984 
02985   // Create local scope for possible condition variable.
02986   // Store scope position. Add implicit destructor.
02987   if (VarDecl *VD = Terminator->getConditionVariable()) {
02988     LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
02989     addLocalScopeForVarDecl(VD);
02990     addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
02991   }
02992 
02993   if (Block) {
02994     if (badCFG)
02995       return nullptr;
02996     SwitchSuccessor = Block;
02997   } else SwitchSuccessor = Succ;
02998 
02999   // Save the current "switch" context.
03000   SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
03001                             save_default(DefaultCaseBlock);
03002   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
03003 
03004   // Set the "default" case to be the block after the switch statement.  If the
03005   // switch statement contains a "default:", this value will be overwritten with
03006   // the block for that code.
03007   DefaultCaseBlock = SwitchSuccessor;
03008 
03009   // Create a new block that will contain the switch statement.
03010   SwitchTerminatedBlock = createBlock(false);
03011 
03012   // Now process the switch body.  The code after the switch is the implicit
03013   // successor.
03014   Succ = SwitchSuccessor;
03015   BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
03016 
03017   // When visiting the body, the case statements should automatically get linked
03018   // up to the switch.  We also don't keep a pointer to the body, since all
03019   // control-flow from the switch goes to case/default statements.
03020   assert(Terminator->getBody() && "switch must contain a non-NULL body");
03021   Block = nullptr;
03022 
03023   // For pruning unreachable case statements, save the current state
03024   // for tracking the condition value.
03025   SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
03026                                                      false);
03027 
03028   // Determine if the switch condition can be explicitly evaluated.
03029   assert(Terminator->getCond() && "switch condition must be non-NULL");
03030   Expr::EvalResult result;
03031   bool b = tryEvaluate(Terminator->getCond(), result);
03032   SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
03033                                                     b ? &result : nullptr);
03034 
03035   // If body is not a compound statement create implicit scope
03036   // and add destructors.
03037   if (!isa<CompoundStmt>(Terminator->getBody()))
03038     addLocalScopeAndDtors(Terminator->getBody());
03039 
03040   addStmt(Terminator->getBody());
03041   if (Block) {
03042     if (badCFG)
03043       return nullptr;
03044   }
03045 
03046   // If we have no "default:" case, the default transition is to the code
03047   // following the switch body.  Moreover, take into account if all the
03048   // cases of a switch are covered (e.g., switching on an enum value).
03049   //
03050   // Note: We add a successor to a switch that is considered covered yet has no
03051   //       case statements if the enumeration has no enumerators.
03052   bool SwitchAlwaysHasSuccessor = false;
03053   SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
03054   SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
03055                               Terminator->getSwitchCaseList();
03056   addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
03057                !SwitchAlwaysHasSuccessor);
03058 
03059   // Add the terminator and condition in the switch block.
03060   SwitchTerminatedBlock->setTerminator(Terminator);
03061   Block = SwitchTerminatedBlock;
03062   CFGBlock *LastBlock = addStmt(Terminator->getCond());
03063 
03064   // Finally, if the SwitchStmt contains a condition variable, add both the
03065   // SwitchStmt and the condition variable initialization to the CFG.
03066   if (VarDecl *VD = Terminator->getConditionVariable()) {
03067     if (Expr *Init = VD->getInit()) {
03068       autoCreateBlock();
03069       appendStmt(Block, Terminator->getConditionVariableDeclStmt());
03070       LastBlock = addStmt(Init);
03071     }
03072   }
03073 
03074   return LastBlock;
03075 }
03076   
03077 static bool shouldAddCase(bool &switchExclusivelyCovered,
03078                           const Expr::EvalResult *switchCond,
03079                           const CaseStmt *CS,
03080                           ASTContext &Ctx) {
03081   if (!switchCond)
03082     return true;
03083 
03084   bool addCase = false;
03085 
03086   if (!switchExclusivelyCovered) {
03087     if (switchCond->Val.isInt()) {
03088       // Evaluate the LHS of the case value.
03089       const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
03090       const llvm::APSInt &condInt = switchCond->Val.getInt();
03091       
03092       if (condInt == lhsInt) {
03093         addCase = true;
03094         switchExclusivelyCovered = true;
03095       }
03096       else if (condInt < lhsInt) {
03097         if (const Expr *RHS = CS->getRHS()) {
03098           // Evaluate the RHS of the case value.
03099           const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
03100           if (V2 <= condInt) {
03101             addCase = true;
03102             switchExclusivelyCovered = true;
03103           }
03104         }
03105       }
03106     }
03107     else
03108       addCase = true;
03109   }
03110   return addCase;  
03111 }
03112 
03113 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
03114   // CaseStmts are essentially labels, so they are the first statement in a
03115   // block.
03116   CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
03117 
03118   if (Stmt *Sub = CS->getSubStmt()) {
03119     // For deeply nested chains of CaseStmts, instead of doing a recursion
03120     // (which can blow out the stack), manually unroll and create blocks
03121     // along the way.
03122     while (isa<CaseStmt>(Sub)) {
03123       CFGBlock *currentBlock = createBlock(false);
03124       currentBlock->setLabel(CS);
03125 
03126       if (TopBlock)
03127         addSuccessor(LastBlock, currentBlock);
03128       else
03129         TopBlock = currentBlock;
03130 
03131       addSuccessor(SwitchTerminatedBlock,
03132                    shouldAddCase(switchExclusivelyCovered, switchCond,
03133                                  CS, *Context)
03134                    ? currentBlock : nullptr);
03135 
03136       LastBlock = currentBlock;
03137       CS = cast<CaseStmt>(Sub);
03138       Sub = CS->getSubStmt();
03139     }
03140 
03141     addStmt(Sub);
03142   }
03143 
03144   CFGBlock *CaseBlock = Block;
03145   if (!CaseBlock)
03146     CaseBlock = createBlock();
03147 
03148   // Cases statements partition blocks, so this is the top of the basic block we
03149   // were processing (the "case XXX:" is the label).
03150   CaseBlock->setLabel(CS);
03151 
03152   if (badCFG)
03153     return nullptr;
03154 
03155   // Add this block to the list of successors for the block with the switch
03156   // statement.
03157   assert(SwitchTerminatedBlock);
03158   addSuccessor(SwitchTerminatedBlock, CaseBlock,
03159                shouldAddCase(switchExclusivelyCovered, switchCond,
03160                              CS, *Context));
03161 
03162   // We set Block to NULL to allow lazy creation of a new block (if necessary)
03163   Block = nullptr;
03164 
03165   if (TopBlock) {
03166     addSuccessor(LastBlock, CaseBlock);
03167     Succ = TopBlock;
03168   } else {
03169     // This block is now the implicit successor of other blocks.
03170     Succ = CaseBlock;
03171   }
03172 
03173   return Succ;
03174 }
03175 
03176 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
03177   if (Terminator->getSubStmt())
03178     addStmt(Terminator->getSubStmt());
03179 
03180   DefaultCaseBlock = Block;
03181 
03182   if (!DefaultCaseBlock)
03183     DefaultCaseBlock = createBlock();
03184 
03185   // Default statements partition blocks, so this is the top of the basic block
03186   // we were processing (the "default:" is the label).
03187   DefaultCaseBlock->setLabel(Terminator);
03188 
03189   if (badCFG)
03190     return nullptr;
03191 
03192   // Unlike case statements, we don't add the default block to the successors
03193   // for the switch statement immediately.  This is done when we finish
03194   // processing the switch statement.  This allows for the default case
03195   // (including a fall-through to the code after the switch statement) to always
03196   // be the last successor of a switch-terminated block.
03197 
03198   // We set Block to NULL to allow lazy creation of a new block (if necessary)
03199   Block = nullptr;
03200 
03201   // This block is now the implicit successor of other blocks.
03202   Succ = DefaultCaseBlock;
03203 
03204   return DefaultCaseBlock;
03205 }
03206 
03207 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
03208   // "try"/"catch" is a control-flow statement.  Thus we stop processing the
03209   // current block.
03210   CFGBlock *TrySuccessor = nullptr;
03211 
03212   if (Block) {
03213     if (badCFG)
03214       return nullptr;
03215     TrySuccessor = Block;
03216   } else TrySuccessor = Succ;
03217 
03218   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
03219 
03220   // Create a new block that will contain the try statement.
03221   CFGBlock *NewTryTerminatedBlock = createBlock(false);
03222   // Add the terminator in the try block.
03223   NewTryTerminatedBlock->setTerminator(Terminator);
03224 
03225   bool HasCatchAll = false;
03226   for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
03227     // The code after the try is the implicit successor.
03228     Succ = TrySuccessor;
03229     CXXCatchStmt *CS = Terminator->getHandler(h);
03230     if (CS->getExceptionDecl() == nullptr) {
03231       HasCatchAll = true;
03232     }
03233     Block = nullptr;
03234     CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
03235     if (!CatchBlock)
03236       return nullptr;
03237     // Add this block to the list of successors for the block with the try
03238     // statement.
03239     addSuccessor(NewTryTerminatedBlock, CatchBlock);
03240   }
03241   if (!HasCatchAll) {
03242     if (PrevTryTerminatedBlock)
03243       addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
03244     else
03245       addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
03246   }
03247 
03248   // The code after the try is the implicit successor.
03249   Succ = TrySuccessor;
03250 
03251   // Save the current "try" context.
03252   SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
03253   cfg->addTryDispatchBlock(TryTerminatedBlock);
03254 
03255   assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
03256   Block = nullptr;
03257   return addStmt(Terminator->getTryBlock());
03258 }
03259 
03260 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
03261   // CXXCatchStmt are treated like labels, so they are the first statement in a
03262   // block.
03263 
03264   // Save local scope position because in case of exception variable ScopePos
03265   // won't be restored when traversing AST.
03266   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
03267 
03268   // Create local scope for possible exception variable.
03269   // Store scope position. Add implicit destructor.
03270   if (VarDecl *VD = CS->getExceptionDecl()) {
03271     LocalScope::const_iterator BeginScopePos = ScopePos;
03272     addLocalScopeForVarDecl(VD);
03273     addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
03274   }
03275 
03276   if (CS->getHandlerBlock())
03277     addStmt(CS->getHandlerBlock());
03278 
03279   CFGBlock *CatchBlock = Block;
03280   if (!CatchBlock)
03281     CatchBlock = createBlock();
03282   
03283   // CXXCatchStmt is more than just a label.  They have semantic meaning
03284   // as well, as they implicitly "initialize" the catch variable.  Add
03285   // it to the CFG as a CFGElement so that the control-flow of these
03286   // semantics gets captured.
03287   appendStmt(CatchBlock, CS);
03288 
03289   // Also add the CXXCatchStmt as a label, to mirror handling of regular
03290   // labels.
03291   CatchBlock->setLabel(CS);
03292 
03293   // Bail out if the CFG is bad.
03294   if (badCFG)
03295     return nullptr;
03296 
03297   // We set Block to NULL to allow lazy creation of a new block (if necessary)
03298   Block = nullptr;
03299 
03300   return CatchBlock;
03301 }
03302 
03303 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
03304   // C++0x for-range statements are specified as [stmt.ranged]:
03305   //
03306   // {
03307   //   auto && __range = range-init;
03308   //   for ( auto __begin = begin-expr,
03309   //         __end = end-expr;
03310   //         __begin != __end;
03311   //         ++__begin ) {
03312   //     for-range-declaration = *__begin;
03313   //     statement
03314   //   }
03315   // }
03316 
03317   // Save local scope position before the addition of the implicit variables.
03318   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
03319 
03320   // Create local scopes and destructors for range, begin and end variables.
03321   if (Stmt *Range = S->getRangeStmt())
03322     addLocalScopeForStmt(Range);
03323   if (Stmt *BeginEnd = S->getBeginEndStmt())
03324     addLocalScopeForStmt(BeginEnd);
03325   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
03326 
03327   LocalScope::const_iterator ContinueScopePos = ScopePos;
03328 
03329   // "for" is a control-flow statement.  Thus we stop processing the current
03330   // block.
03331   CFGBlock *LoopSuccessor = nullptr;
03332   if (Block) {
03333     if (badCFG)
03334       return nullptr;
03335     LoopSuccessor = Block;
03336   } else
03337     LoopSuccessor = Succ;
03338 
03339   // Save the current value for the break targets.
03340   // All breaks should go to the code following the loop.
03341   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
03342   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
03343 
03344   // The block for the __begin != __end expression.
03345   CFGBlock *ConditionBlock = createBlock(false);
03346   ConditionBlock->setTerminator(S);
03347 
03348   // Now add the actual condition to the condition block.
03349   if (Expr *C = S->getCond()) {
03350     Block = ConditionBlock;
03351     CFGBlock *BeginConditionBlock = addStmt(C);
03352     if (badCFG)
03353       return nullptr;
03354     assert(BeginConditionBlock == ConditionBlock &&
03355            "condition block in for-range was unexpectedly complex");
03356     (void)BeginConditionBlock;
03357   }
03358 
03359   // The condition block is the implicit successor for the loop body as well as
03360   // any code above the loop.
03361   Succ = ConditionBlock;
03362 
03363   // See if this is a known constant.
03364   TryResult KnownVal(true);
03365 
03366   if (S->getCond())
03367     KnownVal = tryEvaluateBool(S->getCond());
03368 
03369   // Now create the loop body.
03370   {
03371     assert(S->getBody());
03372 
03373     // Save the current values for Block, Succ, and continue targets.
03374     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
03375     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
03376 
03377     // Generate increment code in its own basic block.  This is the target of
03378     // continue statements.
03379     Block = nullptr;
03380     Succ = addStmt(S->getInc());
03381     ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
03382 
03383     // The starting block for the loop increment is the block that should
03384     // represent the 'loop target' for looping back to the start of the loop.
03385     ContinueJumpTarget.block->setLoopTarget(S);
03386 
03387     // Finish up the increment block and prepare to start the loop body.
03388     assert(Block);
03389     if (badCFG)
03390       return nullptr;
03391     Block = nullptr;
03392 
03393     // Add implicit scope and dtors for loop variable.
03394     addLocalScopeAndDtors(S->getLoopVarStmt());
03395 
03396     // Populate a new block to contain the loop body and loop variable.
03397     addStmt(S->getBody());
03398     if (badCFG)
03399       return nullptr;
03400     CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
03401     if (badCFG)
03402       return nullptr;
03403 
03404     // This new body block is a successor to our condition block.
03405     addSuccessor(ConditionBlock,
03406                  KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
03407   }
03408 
03409   // Link up the condition block with the code that follows the loop (the
03410   // false branch).
03411   addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
03412 
03413   // Add the initialization statements.
03414   Block = createBlock();
03415   addStmt(S->getBeginEndStmt());
03416   return addStmt(S->getRangeStmt());
03417 }
03418 
03419 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
03420     AddStmtChoice asc) {
03421   if (BuildOpts.AddTemporaryDtors) {
03422     // If adding implicit destructors visit the full expression for adding
03423     // destructors of temporaries.
03424     TempDtorContext Context;
03425     VisitForTemporaryDtors(E->getSubExpr(), false, Context);
03426 
03427     // Full expression has to be added as CFGStmt so it will be sequenced
03428     // before destructors of it's temporaries.
03429     asc = asc.withAlwaysAdd(true);
03430   }
03431   return Visit(E->getSubExpr(), asc);
03432 }
03433 
03434 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
03435                                                 AddStmtChoice asc) {
03436   if (asc.alwaysAdd(*this, E)) {
03437     autoCreateBlock();
03438     appendStmt(Block, E);
03439 
03440     // We do not want to propagate the AlwaysAdd property.
03441     asc = asc.withAlwaysAdd(false);
03442   }
03443   return Visit(E->getSubExpr(), asc);
03444 }
03445 
03446 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
03447                                             AddStmtChoice asc) {
03448   autoCreateBlock();
03449   appendStmt(Block, C);
03450 
03451   return VisitChildren(C);
03452 }
03453 
03454 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
03455                                       AddStmtChoice asc) {
03456 
03457   autoCreateBlock();
03458   appendStmt(Block, NE);
03459 
03460   if (NE->getInitializer())
03461     Block = Visit(NE->getInitializer());
03462   if (BuildOpts.AddCXXNewAllocator)
03463     appendNewAllocator(Block, NE);
03464   if (NE->isArray())
03465     Block = Visit(NE->getArraySize());
03466   for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
03467        E = NE->placement_arg_end(); I != E; ++I)
03468     Block = Visit(*I);
03469   return Block;
03470 }
03471 
03472 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
03473                                          AddStmtChoice asc) {
03474   autoCreateBlock();
03475   appendStmt(Block, DE);
03476   QualType DTy = DE->getDestroyedType();
03477   DTy = DTy.getNonReferenceType();
03478   CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
03479   if (RD) {
03480     if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
03481       appendDeleteDtor(Block, RD, DE);
03482   }
03483 
03484   return VisitChildren(DE);
03485 }
03486 
03487 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
03488                                                  AddStmtChoice asc) {
03489   if (asc.alwaysAdd(*this, E)) {
03490     autoCreateBlock();
03491     appendStmt(Block, E);
03492     // We do not want to propagate the AlwaysAdd property.
03493     asc = asc.withAlwaysAdd(false);
03494   }
03495   return Visit(E->getSubExpr(), asc);
03496 }
03497 
03498 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
03499                                                   AddStmtChoice asc) {
03500   autoCreateBlock();
03501   appendStmt(Block, C);
03502   return VisitChildren(C);
03503 }
03504 
03505 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
03506                                             AddStmtChoice asc) {
03507   if (asc.alwaysAdd(*this, E)) {
03508     autoCreateBlock();
03509     appendStmt(Block, E);
03510   }
03511   return Visit(E->getSubExpr(), AddStmtChoice());
03512 }
03513 
03514 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
03515   // Lazily create the indirect-goto dispatch block if there isn't one already.
03516   CFGBlock *IBlock = cfg->getIndirectGotoBlock();
03517 
03518   if (!IBlock) {
03519     IBlock = createBlock(false);
03520     cfg->setIndirectGotoBlock(IBlock);
03521   }
03522 
03523   // IndirectGoto is a control-flow statement.  Thus we stop processing the
03524   // current block and create a new one.
03525   if (badCFG)
03526     return nullptr;
03527 
03528   Block = createBlock(false);
03529   Block->setTerminator(I);
03530   addSuccessor(Block, IBlock);
03531   return addStmt(I->getTarget());
03532 }
03533 
03534 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
03535                                              TempDtorContext &Context) {
03536   assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
03537 
03538 tryAgain:
03539   if (!E) {
03540     badCFG = true;
03541     return nullptr;
03542   }
03543   switch (E->getStmtClass()) {
03544     default:
03545       return VisitChildrenForTemporaryDtors(E, Context);
03546 
03547     case Stmt::BinaryOperatorClass:
03548       return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
03549                                                   Context);
03550 
03551     case Stmt::CXXBindTemporaryExprClass:
03552       return VisitCXXBindTemporaryExprForTemporaryDtors(
03553           cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
03554 
03555     case Stmt::BinaryConditionalOperatorClass:
03556     case Stmt::ConditionalOperatorClass:
03557       return VisitConditionalOperatorForTemporaryDtors(
03558           cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
03559 
03560     case Stmt::ImplicitCastExprClass:
03561       // For implicit cast we want BindToTemporary to be passed further.
03562       E = cast<CastExpr>(E)->getSubExpr();
03563       goto tryAgain;
03564 
03565     case Stmt::CXXFunctionalCastExprClass:
03566       // For functional cast we want BindToTemporary to be passed further.
03567       E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
03568       goto tryAgain;
03569 
03570     case Stmt::ParenExprClass:
03571       E = cast<ParenExpr>(E)->getSubExpr();
03572       goto tryAgain;
03573 
03574     case Stmt::MaterializeTemporaryExprClass: {
03575       const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
03576       BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
03577       SmallVector<const Expr *, 2> CommaLHSs;
03578       SmallVector<SubobjectAdjustment, 2> Adjustments;
03579       // Find the expression whose lifetime needs to be extended.
03580       E = const_cast<Expr *>(
03581           cast<MaterializeTemporaryExpr>(E)
03582               ->GetTemporaryExpr()
03583               ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
03584       // Visit the skipped comma operator left-hand sides for other temporaries.
03585       for (const Expr *CommaLHS : CommaLHSs) {
03586         VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
03587                                /*BindToTemporary=*/false, Context);
03588       }
03589       goto tryAgain;
03590     }
03591 
03592     case Stmt::BlockExprClass:
03593       // Don't recurse into blocks; their subexpressions don't get evaluated
03594       // here.
03595       return Block;
03596 
03597     case Stmt::LambdaExprClass: {
03598       // For lambda expressions, only recurse into the capture initializers,
03599       // and not the body.
03600       auto *LE = cast<LambdaExpr>(E);
03601       CFGBlock *B = Block;
03602       for (Expr *Init : LE->capture_inits()) {
03603         if (CFGBlock *R = VisitForTemporaryDtors(
03604                 Init, /*BindToTemporary=*/false, Context))
03605           B = R;
03606       }
03607       return B;
03608     }
03609 
03610     case Stmt::CXXDefaultArgExprClass:
03611       E = cast<CXXDefaultArgExpr>(E)->getExpr();
03612       goto tryAgain;
03613 
03614     case Stmt::CXXDefaultInitExprClass:
03615       E = cast<CXXDefaultInitExpr>(E)->getExpr();
03616       goto tryAgain;
03617   }
03618 }
03619 
03620 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
03621                                                      TempDtorContext &Context) {
03622   if (isa<LambdaExpr>(E)) {
03623     // Do not visit the children of lambdas; they have their own CFGs.
03624     return Block;
03625   }
03626 
03627   // When visiting children for destructors we want to visit them in reverse
03628   // order that they will appear in the CFG.  Because the CFG is built
03629   // bottom-up, this means we visit them in their natural order, which
03630   // reverses them in the CFG.
03631   CFGBlock *B = Block;
03632   for (Stmt::child_range I = E->children(); I; ++I) {
03633     if (Stmt *Child = *I)
03634       if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
03635         B = R;
03636   }
03637   return B;
03638 }
03639 
03640 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
03641     BinaryOperator *E, TempDtorContext &Context) {
03642   if (E->isLogicalOp()) {
03643     VisitForTemporaryDtors(E->getLHS(), false, Context);
03644     TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
03645     if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
03646       RHSExecuted.negate();
03647 
03648     // We do not know at CFG-construction time whether the right-hand-side was
03649     // executed, thus we add a branch node that depends on the temporary
03650     // constructor call.
03651     TempDtorContext RHSContext(
03652         bothKnownTrue(Context.KnownExecuted, RHSExecuted));
03653     VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
03654     InsertTempDtorDecisionBlock(RHSContext);
03655 
03656     return Block;
03657   }
03658 
03659   if (E->isAssignmentOp()) {
03660     // For assignment operator (=) LHS expression is visited
03661     // before RHS expression. For destructors visit them in reverse order.
03662     CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
03663     CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
03664     return LHSBlock ? LHSBlock : RHSBlock;
03665   }
03666 
03667   // For any other binary operator RHS expression is visited before
03668   // LHS expression (order of children). For destructors visit them in reverse
03669   // order.
03670   CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
03671   CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
03672   return RHSBlock ? RHSBlock : LHSBlock;
03673 }
03674 
03675 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
03676     CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
03677   // First add destructors for temporaries in subexpression.
03678   CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
03679   if (!BindToTemporary) {
03680     // If lifetime of temporary is not prolonged (by assigning to constant
03681     // reference) add destructor for it.
03682 
03683     const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
03684 
03685     if (Dtor->isNoReturn()) {
03686       // If the destructor is marked as a no-return destructor, we need to
03687       // create a new block for the destructor which does not have as a
03688       // successor anything built thus far. Control won't flow out of this
03689       // block.
03690       if (B) Succ = B;
03691       Block = createNoReturnBlock();
03692     } else if (Context.needsTempDtorBranch()) {
03693       // If we need to introduce a branch, we add a new block that we will hook
03694       // up to a decision block later.
03695       if (B) Succ = B;
03696       Block = createBlock();
03697     } else {
03698       autoCreateBlock();
03699     }
03700     if (Context.needsTempDtorBranch()) {
03701       Context.setDecisionPoint(Succ, E);
03702     }
03703     appendTemporaryDtor(Block, E);
03704 
03705     B = Block;
03706   }
03707   return B;
03708 }
03709 
03710 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
03711                                              CFGBlock *FalseSucc) {
03712   if (!Context.TerminatorExpr) {
03713     // If no temporary was found, we do not need to insert a decision point.
03714     return;
03715   }
03716   assert(Context.TerminatorExpr);
03717   CFGBlock *Decision = createBlock(false);
03718   Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
03719   addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
03720   addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
03721                !Context.KnownExecuted.isTrue());
03722   Block = Decision;
03723 }
03724 
03725 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
03726     AbstractConditionalOperator *E, bool BindToTemporary,
03727     TempDtorContext &Context) {
03728   VisitForTemporaryDtors(E->getCond(), false, Context);
03729   CFGBlock *ConditionBlock = Block;
03730   CFGBlock *ConditionSucc = Succ;
03731   TryResult ConditionVal = tryEvaluateBool(E->getCond());
03732   TryResult NegatedVal = ConditionVal;
03733   if (NegatedVal.isKnown()) NegatedVal.negate();
03734 
03735   TempDtorContext TrueContext(
03736       bothKnownTrue(Context.KnownExecuted, ConditionVal));
03737   VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
03738   CFGBlock *TrueBlock = Block;
03739 
03740   Block = ConditionBlock;
03741   Succ = ConditionSucc;
03742   TempDtorContext FalseContext(
03743       bothKnownTrue(Context.KnownExecuted, NegatedVal));
03744   VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
03745 
03746   if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
03747     InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
03748   } else if (TrueContext.TerminatorExpr) {
03749     Block = TrueBlock;
03750     InsertTempDtorDecisionBlock(TrueContext);
03751   } else {
03752     InsertTempDtorDecisionBlock(FalseContext);
03753   }
03754   return Block;
03755 }
03756 
03757 } // end anonymous namespace
03758 
03759 /// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
03760 ///  no successors or predecessors.  If this is the first block created in the
03761 ///  CFG, it is automatically set to be the Entry and Exit of the CFG.
03762 CFGBlock *CFG::createBlock() {
03763   bool first_block = begin() == end();
03764 
03765   // Create the block.
03766   CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
03767   new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
03768   Blocks.push_back(Mem, BlkBVC);
03769 
03770   // If this is the first block, set it as the Entry and Exit.
03771   if (first_block)
03772     Entry = Exit = &back();
03773 
03774   // Return the block.
03775   return &back();
03776 }
03777 
03778 /// buildCFG - Constructs a CFG from an AST.
03779 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
03780                                    ASTContext *C, const BuildOptions &BO) {
03781   CFGBuilder Builder(C, BO);
03782   return Builder.buildCFG(D, Statement);
03783 }
03784 
03785 const CXXDestructorDecl *
03786 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
03787   switch (getKind()) {
03788     case CFGElement::Statement:
03789     case CFGElement::Initializer:
03790     case CFGElement::NewAllocator:
03791       llvm_unreachable("getDestructorDecl should only be used with "
03792                        "ImplicitDtors");
03793     case CFGElement::AutomaticObjectDtor: {
03794       const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
03795       QualType ty = var->getType();
03796       ty = ty.getNonReferenceType();
03797       while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
03798         ty = arrayType->getElementType();
03799       }
03800       const RecordType *recordType = ty->getAs<RecordType>();
03801       const CXXRecordDecl *classDecl =
03802       cast<CXXRecordDecl>(recordType->getDecl());
03803       return classDecl->getDestructor();      
03804     }
03805     case CFGElement::DeleteDtor: {
03806       const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
03807       QualType DTy = DE->getDestroyedType();
03808       DTy = DTy.getNonReferenceType();
03809       const CXXRecordDecl *classDecl =
03810           astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
03811       return classDecl->getDestructor();
03812     }
03813     case CFGElement::TemporaryDtor: {
03814       const CXXBindTemporaryExpr *bindExpr =
03815         castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
03816       const CXXTemporary *temp = bindExpr->getTemporary();
03817       return temp->getDestructor();
03818     }
03819     case CFGElement::BaseDtor:
03820     case CFGElement::MemberDtor:
03821 
03822       // Not yet supported.
03823       return nullptr;
03824   }
03825   llvm_unreachable("getKind() returned bogus value");
03826 }
03827 
03828 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
03829   if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
03830     return DD->isNoReturn();
03831   return false;
03832 }
03833 
03834 //===----------------------------------------------------------------------===//
03835 // CFGBlock operations.
03836 //===----------------------------------------------------------------------===//
03837 
03838 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
03839   : ReachableBlock(IsReachable ? B : nullptr),
03840     UnreachableBlock(!IsReachable ? B : nullptr,
03841                      B && IsReachable ? AB_Normal : AB_Unreachable) {}
03842 
03843 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
03844   : ReachableBlock(B),
03845     UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
03846                      B == AlternateBlock ? AB_Alternate : AB_Normal) {}
03847 
03848 void CFGBlock::addSuccessor(AdjacentBlock Succ,
03849                             BumpVectorContext &C) {
03850   if (CFGBlock *B = Succ.getReachableBlock())
03851     B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
03852 
03853   if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
03854     UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
03855 
03856   Succs.push_back(Succ, C);
03857 }
03858 
03859 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
03860         const CFGBlock *From, const CFGBlock *To) {
03861 
03862   if (F.IgnoreNullPredecessors && !From)
03863     return true;
03864 
03865   if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
03866     // If the 'To' has no label or is labeled but the label isn't a
03867     // CaseStmt then filter this edge.
03868     if (const SwitchStmt *S =
03869         dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
03870       if (S->isAllEnumCasesCovered()) {
03871         const Stmt *L = To->getLabel();
03872         if (!L || !isa<CaseStmt>(L))
03873           return true;
03874       }
03875     }
03876   }
03877 
03878   return false;
03879 }
03880 
03881 //===----------------------------------------------------------------------===//
03882 // CFG pretty printing
03883 //===----------------------------------------------------------------------===//
03884 
03885 namespace {
03886 
03887 class StmtPrinterHelper : public PrinterHelper  {
03888   typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
03889   typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
03890   StmtMapTy StmtMap;
03891   DeclMapTy DeclMap;
03892   signed currentBlock;
03893   unsigned currStmt;
03894   const LangOptions &LangOpts;
03895 public:
03896 
03897   StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
03898     : currentBlock(0), currStmt(0), LangOpts(LO)
03899   {
03900     for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
03901       unsigned j = 1;
03902       for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
03903            BI != BEnd; ++BI, ++j ) {        
03904         if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
03905           const Stmt *stmt= SE->getStmt();
03906           std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
03907           StmtMap[stmt] = P;
03908 
03909           switch (stmt->getStmtClass()) {
03910             case Stmt::DeclStmtClass:
03911                 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
03912                 break;
03913             case Stmt::IfStmtClass: {
03914               const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
03915               if (var)
03916                 DeclMap[var] = P;
03917               break;
03918             }
03919             case Stmt::ForStmtClass: {
03920               const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
03921               if (var)
03922                 DeclMap[var] = P;
03923               break;
03924             }
03925             case Stmt::WhileStmtClass: {
03926               const VarDecl *var =
03927                 cast<WhileStmt>(stmt)->getConditionVariable();
03928               if (var)
03929                 DeclMap[var] = P;
03930               break;
03931             }
03932             case Stmt::SwitchStmtClass: {
03933               const VarDecl *var =
03934                 cast<SwitchStmt>(stmt)->getConditionVariable();
03935               if (var)
03936                 DeclMap[var] = P;
03937               break;
03938             }
03939             case Stmt::CXXCatchStmtClass: {
03940               const VarDecl *var =
03941                 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
03942               if (var)
03943                 DeclMap[var] = P;
03944               break;
03945             }
03946             default:
03947               break;
03948           }
03949         }
03950       }
03951     }
03952   }
03953   
03954 
03955   virtual ~StmtPrinterHelper() {}
03956 
03957   const LangOptions &getLangOpts() const { return LangOpts; }
03958   void setBlockID(signed i) { currentBlock = i; }
03959   void setStmtID(unsigned i) { currStmt = i; }
03960 
03961   bool handledStmt(Stmt *S, raw_ostream &OS) override {
03962     StmtMapTy::iterator I = StmtMap.find(S);
03963 
03964     if (I == StmtMap.end())
03965       return false;
03966 
03967     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
03968                           && I->second.second == currStmt) {
03969       return false;
03970     }
03971 
03972     OS << "[B" << I->second.first << "." << I->second.second << "]";
03973     return true;
03974   }
03975 
03976   bool handleDecl(const Decl *D, raw_ostream &OS) {
03977     DeclMapTy::iterator I = DeclMap.find(D);
03978 
03979     if (I == DeclMap.end())
03980       return false;
03981 
03982     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
03983                           && I->second.second == currStmt) {
03984       return false;
03985     }
03986 
03987     OS << "[B" << I->second.first << "." << I->second.second << "]";
03988     return true;
03989   }
03990 };
03991 } // end anonymous namespace
03992 
03993 
03994 namespace {
03995 class CFGBlockTerminatorPrint
03996   : public StmtVisitor<CFGBlockTerminatorPrint,void> {
03997 
03998   raw_ostream &OS;
03999   StmtPrinterHelper* Helper;
04000   PrintingPolicy Policy;
04001 public:
04002   CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
04003                           const PrintingPolicy &Policy)
04004     : OS(os), Helper(helper), Policy(Policy) {
04005     this->Policy.IncludeNewlines = false;
04006   }
04007 
04008   void VisitIfStmt(IfStmt *I) {
04009     OS << "if ";
04010     if (Stmt *C = I->getCond())
04011       C->printPretty(OS, Helper, Policy);
04012   }
04013 
04014   // Default case.
04015   void VisitStmt(Stmt *Terminator) {
04016     Terminator->printPretty(OS, Helper, Policy);
04017   }
04018 
04019   void VisitDeclStmt(DeclStmt *DS) {
04020     VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
04021     OS << "static init " << VD->getName();
04022   }
04023 
04024   void VisitForStmt(ForStmt *F) {
04025     OS << "for (" ;
04026     if (F->getInit())
04027       OS << "...";
04028     OS << "; ";
04029     if (Stmt *C = F->getCond())
04030       C->printPretty(OS, Helper, Policy);
04031     OS << "; ";
04032     if (F->getInc())
04033       OS << "...";
04034     OS << ")";
04035   }
04036 
04037   void VisitWhileStmt(WhileStmt *W) {
04038     OS << "while " ;
04039     if (Stmt *C = W->getCond())
04040       C->printPretty(OS, Helper, Policy);
04041   }
04042 
04043   void VisitDoStmt(DoStmt *D) {
04044     OS << "do ... while ";
04045     if (Stmt *C = D->getCond())
04046       C->printPretty(OS, Helper, Policy);
04047   }
04048 
04049   void VisitSwitchStmt(SwitchStmt *Terminator) {
04050     OS << "switch ";
04051     Terminator->getCond()->printPretty(OS, Helper, Policy);
04052   }
04053 
04054   void VisitCXXTryStmt(CXXTryStmt *CS) {
04055     OS << "try ...";
04056   }
04057 
04058   void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
04059     if (Stmt *Cond = C->getCond())
04060       Cond->printPretty(OS, Helper, Policy);
04061     OS << " ? ... : ...";
04062   }
04063 
04064   void VisitChooseExpr(ChooseExpr *C) {
04065     OS << "__builtin_choose_expr( ";
04066     if (Stmt *Cond = C->getCond())
04067       Cond->printPretty(OS, Helper, Policy);
04068     OS << " )";
04069   }
04070 
04071   void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
04072     OS << "goto *";
04073     if (Stmt *T = I->getTarget())
04074       T->printPretty(OS, Helper, Policy);
04075   }
04076 
04077   void VisitBinaryOperator(BinaryOperator* B) {
04078     if (!B->isLogicalOp()) {
04079       VisitExpr(B);
04080       return;
04081     }
04082 
04083     if (B->getLHS())
04084       B->getLHS()->printPretty(OS, Helper, Policy);
04085 
04086     switch (B->getOpcode()) {
04087       case BO_LOr:
04088         OS << " || ...";
04089         return;
04090       case BO_LAnd:
04091         OS << " && ...";
04092         return;
04093       default:
04094         llvm_unreachable("Invalid logical operator.");
04095     }
04096   }
04097 
04098   void VisitExpr(Expr *E) {
04099     E->printPretty(OS, Helper, Policy);
04100   }
04101 
04102 public:
04103   void print(CFGTerminator T) {
04104     if (T.isTemporaryDtorsBranch())
04105       OS << "(Temp Dtor) ";
04106     Visit(T.getStmt());
04107   }
04108 };
04109 } // end anonymous namespace
04110 
04111 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
04112                        const CFGElement &E) {
04113   if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
04114     const Stmt *S = CS->getStmt();
04115     assert(S != nullptr && "Expecting non-null Stmt");
04116 
04117     // special printing for statement-expressions.
04118     if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
04119       const CompoundStmt *Sub = SE->getSubStmt();
04120 
04121       if (Sub->children()) {
04122         OS << "({ ... ; ";
04123         Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
04124         OS << " })\n";
04125         return;
04126       }
04127     }
04128     // special printing for comma expressions.
04129     if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
04130       if (B->getOpcode() == BO_Comma) {
04131         OS << "... , ";
04132         Helper.handledStmt(B->getRHS(),OS);
04133         OS << '\n';
04134         return;
04135       }
04136     }
04137     S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
04138 
04139     if (isa<CXXOperatorCallExpr>(S)) {
04140       OS << " (OperatorCall)";
04141     }
04142     else if (isa<CXXBindTemporaryExpr>(S)) {
04143       OS << " (BindTemporary)";
04144     }
04145     else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
04146       OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
04147     }
04148     else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
04149       OS << " (" << CE->getStmtClassName() << ", "
04150          << CE->getCastKindName()
04151          << ", " << CE->getType().getAsString()
04152          << ")";
04153     }
04154 
04155     // Expressions need a newline.
04156     if (isa<Expr>(S))
04157       OS << '\n';
04158 
04159   } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
04160     const CXXCtorInitializer *I = IE->getInitializer();
04161     if (I->isBaseInitializer())
04162       OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
04163     else if (I->isDelegatingInitializer())
04164       OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
04165     else OS << I->getAnyMember()->getName();
04166 
04167     OS << "(";
04168     if (Expr *IE = I->getInit())
04169       IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
04170     OS << ")";
04171 
04172     if (I->isBaseInitializer())
04173       OS << " (Base initializer)\n";
04174     else if (I->isDelegatingInitializer())
04175       OS << " (Delegating initializer)\n";
04176     else OS << " (Member initializer)\n";
04177 
04178   } else if (Optional<CFGAutomaticObjDtor> DE =
04179                  E.getAs<CFGAutomaticObjDtor>()) {
04180     const VarDecl *VD = DE->getVarDecl();
04181     Helper.handleDecl(VD, OS);
04182 
04183     const Type* T = VD->getType().getTypePtr();
04184     if (const ReferenceType* RT = T->getAs<ReferenceType>())
04185       T = RT->getPointeeType().getTypePtr();
04186     T = T->getBaseElementTypeUnsafe();
04187 
04188     OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
04189     OS << " (Implicit destructor)\n";
04190 
04191   } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
04192     OS << "CFGNewAllocator(";
04193     if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
04194       AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
04195     OS << ")\n";
04196   } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
04197     const CXXRecordDecl *RD = DE->getCXXRecordDecl();
04198     if (!RD)
04199       return;
04200     CXXDeleteExpr *DelExpr =
04201         const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
04202     Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
04203     OS << "->~" << RD->getName().str() << "()";
04204     OS << " (Implicit destructor)\n";
04205   } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
04206     const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
04207     OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
04208     OS << " (Base object destructor)\n";
04209 
04210   } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
04211     const FieldDecl *FD = ME->getFieldDecl();
04212     const Type *T = FD->getType()->getBaseElementTypeUnsafe();
04213     OS << "this->" << FD->getName();
04214     OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
04215     OS << " (Member object destructor)\n";
04216 
04217   } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
04218     const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
04219     OS << "~";
04220     BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
04221     OS << "() (Temporary object destructor)\n";
04222   }
04223 }
04224 
04225 static void print_block(raw_ostream &OS, const CFG* cfg,
04226                         const CFGBlock &B,
04227                         StmtPrinterHelper &Helper, bool print_edges,
04228                         bool ShowColors) {
04229 
04230   Helper.setBlockID(B.getBlockID());
04231 
04232   // Print the header.
04233   if (ShowColors)
04234     OS.changeColor(raw_ostream::YELLOW, true);
04235   
04236   OS << "\n [B" << B.getBlockID();
04237 
04238   if (&B == &cfg->getEntry())
04239     OS << " (ENTRY)]\n";
04240   else if (&B == &cfg->getExit())
04241     OS << " (EXIT)]\n";
04242   else if (&B == cfg->getIndirectGotoBlock())
04243     OS << " (INDIRECT GOTO DISPATCH)]\n";
04244   else if (B.hasNoReturnElement())
04245     OS << " (NORETURN)]\n";
04246   else
04247     OS << "]\n";
04248   
04249   if (ShowColors)
04250     OS.resetColor();
04251 
04252   // Print the label of this block.
04253   if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
04254 
04255     if (print_edges)
04256       OS << "  ";
04257 
04258     if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
04259       OS << L->getName();
04260     else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
04261       OS << "case ";
04262       if (C->getLHS())
04263         C->getLHS()->printPretty(OS, &Helper,
04264                                  PrintingPolicy(Helper.getLangOpts()));
04265       if (C->getRHS()) {
04266         OS << " ... ";
04267         C->getRHS()->printPretty(OS, &Helper,
04268                                  PrintingPolicy(Helper.getLangOpts()));
04269       }
04270     } else if (isa<DefaultStmt>(Label))
04271       OS << "default";
04272     else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
04273       OS << "catch (";
04274       if (CS->getExceptionDecl())
04275         CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
04276                                       0);
04277       else
04278         OS << "...";
04279       OS << ")";
04280 
04281     } else
04282       llvm_unreachable("Invalid label statement in CFGBlock.");
04283 
04284     OS << ":\n";
04285   }
04286 
04287   // Iterate through the statements in the block and print them.
04288   unsigned j = 1;
04289 
04290   for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
04291        I != E ; ++I, ++j ) {
04292 
04293     // Print the statement # in the basic block and the statement itself.
04294     if (print_edges)
04295       OS << " ";
04296 
04297     OS << llvm::format("%3d", j) << ": ";
04298 
04299     Helper.setStmtID(j);
04300 
04301     print_elem(OS, Helper, *I);
04302   }
04303 
04304   // Print the terminator of this block.
04305   if (B.getTerminator()) {
04306     if (ShowColors)
04307       OS.changeColor(raw_ostream::GREEN);
04308 
04309     OS << "   T: ";
04310 
04311     Helper.setBlockID(-1);
04312 
04313     PrintingPolicy PP(Helper.getLangOpts());
04314     CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
04315     TPrinter.print(B.getTerminator());
04316     OS << '\n';
04317     
04318     if (ShowColors)
04319       OS.resetColor();
04320   }
04321 
04322   if (print_edges) {
04323     // Print the predecessors of this block.
04324     if (!B.pred_empty()) {
04325       const raw_ostream::Colors Color = raw_ostream::BLUE;
04326       if (ShowColors)
04327         OS.changeColor(Color);
04328       OS << "   Preds " ;
04329       if (ShowColors)
04330         OS.resetColor();
04331       OS << '(' << B.pred_size() << "):";
04332       unsigned i = 0;
04333 
04334       if (ShowColors)
04335         OS.changeColor(Color);
04336       
04337       for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
04338            I != E; ++I, ++i) {
04339 
04340         if (i % 10 == 8)
04341           OS << "\n     ";
04342 
04343         CFGBlock *B = *I;
04344         bool Reachable = true;
04345         if (!B) {
04346           Reachable = false;
04347           B = I->getPossiblyUnreachableBlock();
04348         }
04349 
04350         OS << " B" << B->getBlockID();
04351         if (!Reachable)
04352           OS << "(Unreachable)";
04353       }
04354       
04355       if (ShowColors)
04356         OS.resetColor();
04357 
04358       OS << '\n';
04359     }
04360 
04361     // Print the successors of this block.
04362     if (!B.succ_empty()) {
04363       const raw_ostream::Colors Color = raw_ostream::MAGENTA;
04364       if (ShowColors)
04365         OS.changeColor(Color);
04366       OS << "   Succs ";
04367       if (ShowColors)
04368         OS.resetColor();
04369       OS << '(' << B.succ_size() << "):";
04370       unsigned i = 0;
04371 
04372       if (ShowColors)
04373         OS.changeColor(Color);
04374 
04375       for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
04376            I != E; ++I, ++i) {
04377 
04378         if (i % 10 == 8)
04379           OS << "\n    ";
04380 
04381         CFGBlock *B = *I;
04382 
04383         bool Reachable = true;
04384         if (!B) {
04385           Reachable = false;
04386           B = I->getPossiblyUnreachableBlock();
04387         }
04388 
04389         if (B) {
04390           OS << " B" << B->getBlockID();
04391           if (!Reachable)
04392             OS << "(Unreachable)";
04393         }
04394         else {
04395           OS << " NULL";
04396         }
04397       }
04398 
04399       if (ShowColors)
04400         OS.resetColor();
04401       OS << '\n';
04402     }
04403   }
04404 }
04405 
04406 
04407 /// dump - A simple pretty printer of a CFG that outputs to stderr.
04408 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
04409   print(llvm::errs(), LO, ShowColors);
04410 }
04411 
04412 /// print - A simple pretty printer of a CFG that outputs to an ostream.
04413 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
04414   StmtPrinterHelper Helper(this, LO);
04415 
04416   // Print the entry block.
04417   print_block(OS, this, getEntry(), Helper, true, ShowColors);
04418 
04419   // Iterate through the CFGBlocks and print them one by one.
04420   for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
04421     // Skip the entry block, because we already printed it.
04422     if (&(**I) == &getEntry() || &(**I) == &getExit())
04423       continue;
04424 
04425     print_block(OS, this, **I, Helper, true, ShowColors);
04426   }
04427 
04428   // Print the exit block.
04429   print_block(OS, this, getExit(), Helper, true, ShowColors);
04430   OS << '\n';
04431   OS.flush();
04432 }
04433 
04434 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
04435 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
04436                     bool ShowColors) const {
04437   print(llvm::errs(), cfg, LO, ShowColors);
04438 }
04439 
04440 void CFGBlock::dump() const {
04441   dump(getParent(), LangOptions(), false);
04442 }
04443 
04444 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
04445 ///   Generally this will only be called from CFG::print.
04446 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
04447                      const LangOptions &LO, bool ShowColors) const {
04448   StmtPrinterHelper Helper(cfg, LO);
04449   print_block(OS, cfg, *this, Helper, true, ShowColors);
04450   OS << '\n';
04451 }
04452 
04453 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
04454 void CFGBlock::printTerminator(raw_ostream &OS,
04455                                const LangOptions &LO) const {
04456   CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
04457   TPrinter.print(getTerminator());
04458 }
04459 
04460 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
04461   Stmt *Terminator = this->Terminator;
04462   if (!Terminator)
04463     return nullptr;
04464 
04465   Expr *E = nullptr;
04466 
04467   switch (Terminator->getStmtClass()) {
04468     default:
04469       break;
04470 
04471     case Stmt::CXXForRangeStmtClass:
04472       E = cast<CXXForRangeStmt>(Terminator)->getCond();
04473       break;
04474 
04475     case Stmt::ForStmtClass:
04476       E = cast<ForStmt>(Terminator)->getCond();
04477       break;
04478 
04479     case Stmt::WhileStmtClass:
04480       E = cast<WhileStmt>(Terminator)->getCond();
04481       break;
04482 
04483     case Stmt::DoStmtClass:
04484       E = cast<DoStmt>(Terminator)->getCond();
04485       break;
04486 
04487     case Stmt::IfStmtClass:
04488       E = cast<IfStmt>(Terminator)->getCond();
04489       break;
04490 
04491     case Stmt::ChooseExprClass:
04492       E = cast<ChooseExpr>(Terminator)->getCond();
04493       break;
04494 
04495     case Stmt::IndirectGotoStmtClass:
04496       E = cast<IndirectGotoStmt>(Terminator)->getTarget();
04497       break;
04498 
04499     case Stmt::SwitchStmtClass:
04500       E = cast<SwitchStmt>(Terminator)->getCond();
04501       break;
04502 
04503     case Stmt::BinaryConditionalOperatorClass:
04504       E = cast<BinaryConditionalOperator>(Terminator)->getCond();
04505       break;
04506 
04507     case Stmt::ConditionalOperatorClass:
04508       E = cast<ConditionalOperator>(Terminator)->getCond();
04509       break;
04510 
04511     case Stmt::BinaryOperatorClass: // '&&' and '||'
04512       E = cast<BinaryOperator>(Terminator)->getLHS();
04513       break;
04514 
04515     case Stmt::ObjCForCollectionStmtClass:
04516       return Terminator;
04517   }
04518 
04519   if (!StripParens)
04520     return E;
04521 
04522   return E ? E->IgnoreParens() : nullptr;
04523 }
04524 
04525 //===----------------------------------------------------------------------===//
04526 // CFG Graphviz Visualization
04527 //===----------------------------------------------------------------------===//
04528 
04529 
04530 #ifndef NDEBUG
04531 static StmtPrinterHelper* GraphHelper;
04532 #endif
04533 
04534 void CFG::viewCFG(const LangOptions &LO) const {
04535 #ifndef NDEBUG
04536   StmtPrinterHelper H(this, LO);
04537   GraphHelper = &H;
04538   llvm::ViewGraph(this,"CFG");
04539   GraphHelper = nullptr;
04540 #endif
04541 }
04542 
04543 namespace llvm {
04544 template<>
04545 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
04546 
04547   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
04548 
04549   static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
04550 
04551 #ifndef NDEBUG
04552     std::string OutSStr;
04553     llvm::raw_string_ostream Out(OutSStr);
04554     print_block(Out,Graph, *Node, *GraphHelper, false, false);
04555     std::string& OutStr = Out.str();
04556 
04557     if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
04558 
04559     // Process string output to make it nicer...
04560     for (unsigned i = 0; i != OutStr.length(); ++i)
04561       if (OutStr[i] == '\n') {                            // Left justify
04562         OutStr[i] = '\\';
04563         OutStr.insert(OutStr.begin()+i+1, 'l');
04564       }
04565 
04566     return OutStr;
04567 #else
04568     return "";
04569 #endif
04570   }
04571 };
04572 } // end namespace llvm