CFG.cpp revision 4347259d31856682ac492d955359add71613f1c3
1//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the CFG and CFGBuilder classes for representing and
11//  building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Analysis/Support/SaveAndRestore.h"
16#include "clang/Analysis/CFG.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/PrettyPrinter.h"
20#include "llvm/Support/GraphWriter.h"
21#include "llvm/Support/Allocator.h"
22#include "llvm/Support/Format.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/OwningPtr.h"
26
27using namespace clang;
28
29namespace {
30
31static SourceLocation GetEndLoc(Decl* D) {
32  if (VarDecl* VD = dyn_cast<VarDecl>(D))
33    if (Expr* Ex = VD->getInit())
34      return Ex->getSourceRange().getEnd();
35
36  return D->getLocation();
37}
38
39class AddStmtChoice {
40public:
41  enum Kind { NotAlwaysAdd = 0, AlwaysAdd, AlwaysAddAsLValue };
42public:
43  AddStmtChoice(Kind kind) : k(kind) {}
44  bool alwaysAdd() const { return k != NotAlwaysAdd; }
45  bool asLValue() const { return k == AlwaysAddAsLValue; }
46private:
47  Kind k;
48};
49
50/// CFGBuilder - This class implements CFG construction from an AST.
51///   The builder is stateful: an instance of the builder should be used to only
52///   construct a single CFG.
53///
54///   Example usage:
55///
56///     CFGBuilder builder;
57///     CFG* cfg = builder.BuildAST(stmt1);
58///
59///  CFG construction is done via a recursive walk of an AST.  We actually parse
60///  the AST in reverse order so that the successor of a basic block is
61///  constructed prior to its predecessor.  This allows us to nicely capture
62///  implicit fall-throughs without extra basic blocks.
63///
64class CFGBuilder {
65  ASTContext *Context;
66  llvm::OwningPtr<CFG> cfg;
67
68  CFGBlock* Block;
69  CFGBlock* Succ;
70  CFGBlock* ContinueTargetBlock;
71  CFGBlock* BreakTargetBlock;
72  CFGBlock* SwitchTerminatedBlock;
73  CFGBlock* DefaultCaseBlock;
74  CFGBlock* TryTerminatedBlock;
75
76  // LabelMap records the mapping from Label expressions to their blocks.
77  typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
78  LabelMapTy LabelMap;
79
80  // A list of blocks that end with a "goto" that must be backpatched to their
81  // resolved targets upon completion of CFG construction.
82  typedef std::vector<CFGBlock*> BackpatchBlocksTy;
83  BackpatchBlocksTy BackpatchBlocks;
84
85  // A list of labels whose address has been taken (for indirect gotos).
86  typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
87  LabelSetTy AddressTakenLabels;
88
89public:
90  explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
91                          Block(NULL), Succ(NULL),
92                          ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
93                          SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
94                          TryTerminatedBlock(NULL) {}
95
96  // buildCFG - Used by external clients to construct the CFG.
97  CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, bool AddScopes);
98
99private:
100  // Visitors to walk an AST and construct the CFG.
101  CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
102  CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
103  CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
104  CFGBlock *VisitBreakStmt(BreakStmt *B);
105  CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
106  CFGBlock *VisitCaseStmt(CaseStmt *C);
107  CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
108  CFGBlock *VisitCompoundStmt(CompoundStmt *C);
109  CFGBlock *VisitConditionalOperator(ConditionalOperator *C,
110                                     AddStmtChoice asc);
111  CFGBlock *VisitContinueStmt(ContinueStmt *C);
112  CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
113  CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
114  CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
115  CFGBlock *VisitDeclStmt(DeclStmt *DS);
116  CFGBlock *VisitDeclSubExpr(Decl* D);
117  CFGBlock *VisitDefaultStmt(DefaultStmt *D);
118  CFGBlock *VisitDoStmt(DoStmt *D);
119  CFGBlock *VisitForStmt(ForStmt *F);
120  CFGBlock *VisitGotoStmt(GotoStmt* G);
121  CFGBlock *VisitIfStmt(IfStmt *I);
122  CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
123  CFGBlock *VisitLabelStmt(LabelStmt *L);
124  CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
125  CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
126  CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
127  CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
128  CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
129  CFGBlock *VisitReturnStmt(ReturnStmt* R);
130  CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
131  CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
132  CFGBlock *VisitSwitchStmt(SwitchStmt *S);
133  CFGBlock *VisitWhileStmt(WhileStmt *W);
134
135  CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
136  CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
137  CFGBlock *VisitChildren(Stmt* S);
138
139  // NYS == Not Yet Supported
140  CFGBlock* NYS() {
141    badCFG = true;
142    return Block;
143  }
144
145  CFGBlock *StartScope(Stmt *S, CFGBlock *B) {
146    if (!AddScopes)
147      return B;
148
149    if (B == 0)
150      B = createBlock();
151    B->StartScope(S, cfg->getBumpVectorContext());
152    return B;
153  }
154
155  void EndScope(Stmt *S) {
156    if (!AddScopes)
157      return;
158
159    if (Block == 0)
160      Block = createBlock();
161    Block->EndScope(S, cfg->getBumpVectorContext());
162  }
163
164  void autoCreateBlock() { if (!Block) Block = createBlock(); }
165  CFGBlock *createBlock(bool add_successor = true);
166  bool FinishBlock(CFGBlock* B);
167  CFGBlock *addStmt(Stmt *S, AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
168    return Visit(S, asc);
169  }
170
171  void AppendStmt(CFGBlock *B, Stmt *S,
172                  AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
173    B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue());
174  }
175
176  void AddSuccessor(CFGBlock *B, CFGBlock *S) {
177    B->addSuccessor(S, cfg->getBumpVectorContext());
178  }
179
180  /// TryResult - a class representing a variant over the values
181  ///  'true', 'false', or 'unknown'.  This is returned by TryEvaluateBool,
182  ///  and is used by the CFGBuilder to decide if a branch condition
183  ///  can be decided up front during CFG construction.
184  class TryResult {
185    int X;
186  public:
187    TryResult(bool b) : X(b ? 1 : 0) {}
188    TryResult() : X(-1) {}
189
190    bool isTrue() const { return X == 1; }
191    bool isFalse() const { return X == 0; }
192    bool isKnown() const { return X >= 0; }
193    void negate() {
194      assert(isKnown());
195      X ^= 0x1;
196    }
197  };
198
199  /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
200  /// if we can evaluate to a known value, otherwise return -1.
201  TryResult TryEvaluateBool(Expr *S) {
202    Expr::EvalResult Result;
203    if (!S->isTypeDependent() && !S->isValueDependent() &&
204        S->Evaluate(Result, *Context) && Result.Val.isInt())
205      return Result.Val.getInt().getBoolValue();
206
207    return TryResult();
208  }
209
210  bool badCFG;
211  bool AddScopes;
212};
213
214// FIXME: Add support for dependent-sized array types in C++?
215// Does it even make sense to build a CFG for an uninstantiated template?
216static VariableArrayType* FindVA(Type* t) {
217  while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
218    if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
219      if (vat->getSizeExpr())
220        return vat;
221
222    t = vt->getElementType().getTypePtr();
223  }
224
225  return 0;
226}
227
228/// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
229///  arbitrary statement.  Examples include a single expression or a function
230///  body (compound statement).  The ownership of the returned CFG is
231///  transferred to the caller.  If CFG construction fails, this method returns
232///  NULL.
233CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C,
234                          bool AddScopes) {
235  Context = C;
236  assert(cfg.get());
237  if (!Statement)
238    return NULL;
239
240  this->AddScopes = AddScopes;
241  badCFG = false;
242
243  // Create an empty block that will serve as the exit block for the CFG.  Since
244  // this is the first block added to the CFG, it will be implicitly registered
245  // as the exit block.
246  Succ = createBlock();
247  assert(Succ == &cfg->getExit());
248  Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
249
250  // Visit the statements and create the CFG.
251  CFGBlock* B = addStmt(Statement);
252
253  if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
254    // FIXME: Add code for base initializers and member initializers.
255    (void)CD;
256  }
257  if (!B)
258    B = Succ;
259
260  if (B) {
261    // Finalize the last constructed block.  This usually involves reversing the
262    // order of the statements in the block.
263    if (Block) FinishBlock(B);
264
265    // Backpatch the gotos whose label -> block mappings we didn't know when we
266    // encountered them.
267    for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
268         E = BackpatchBlocks.end(); I != E; ++I ) {
269
270      CFGBlock* B = *I;
271      GotoStmt* G = cast<GotoStmt>(B->getTerminator());
272      LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
273
274      // If there is no target for the goto, then we are looking at an
275      // incomplete AST.  Handle this by not registering a successor.
276      if (LI == LabelMap.end()) continue;
277
278      AddSuccessor(B, LI->second);
279    }
280
281    // Add successors to the Indirect Goto Dispatch block (if we have one).
282    if (CFGBlock* B = cfg->getIndirectGotoBlock())
283      for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
284           E = AddressTakenLabels.end(); I != E; ++I ) {
285
286        // Lookup the target block.
287        LabelMapTy::iterator LI = LabelMap.find(*I);
288
289        // If there is no target block that contains label, then we are looking
290        // at an incomplete AST.  Handle this by not registering a successor.
291        if (LI == LabelMap.end()) continue;
292
293        AddSuccessor(B, LI->second);
294      }
295
296    Succ = B;
297  }
298
299  // Create an empty entry block that has no predecessors.
300  cfg->setEntry(createBlock());
301
302  return badCFG ? NULL : cfg.take();
303}
304
305/// createBlock - Used to lazily create blocks that are connected
306///  to the current (global) succcessor.
307CFGBlock* CFGBuilder::createBlock(bool add_successor) {
308  CFGBlock* B = cfg->createBlock();
309  if (add_successor && Succ)
310    AddSuccessor(B, Succ);
311  return B;
312}
313
314/// FinishBlock - "Finalize" the block by checking if we have a bad CFG.
315bool CFGBuilder::FinishBlock(CFGBlock* B) {
316  if (badCFG)
317    return false;
318
319  assert(B);
320  return true;
321}
322
323/// Visit - Walk the subtree of a statement and add extra
324///   blocks for ternary operators, &&, and ||.  We also process "," and
325///   DeclStmts (which may contain nested control-flow).
326CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
327tryAgain:
328  switch (S->getStmtClass()) {
329    default:
330      return VisitStmt(S, asc);
331
332    case Stmt::AddrLabelExprClass:
333      return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
334
335    case Stmt::BinaryOperatorClass:
336      return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
337
338    case Stmt::BlockExprClass:
339      return VisitBlockExpr(cast<BlockExpr>(S), asc);
340
341    case Stmt::BreakStmtClass:
342      return VisitBreakStmt(cast<BreakStmt>(S));
343
344    case Stmt::CallExprClass:
345      return VisitCallExpr(cast<CallExpr>(S), asc);
346
347    case Stmt::CaseStmtClass:
348      return VisitCaseStmt(cast<CaseStmt>(S));
349
350    case Stmt::ChooseExprClass:
351      return VisitChooseExpr(cast<ChooseExpr>(S), asc);
352
353    case Stmt::CompoundStmtClass:
354      return VisitCompoundStmt(cast<CompoundStmt>(S));
355
356    case Stmt::ConditionalOperatorClass:
357      return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
358
359    case Stmt::ContinueStmtClass:
360      return VisitContinueStmt(cast<ContinueStmt>(S));
361
362    case Stmt::CXXCatchStmtClass:
363      return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
364
365    case Stmt::CXXThrowExprClass:
366      return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
367
368    case Stmt::CXXTryStmtClass:
369      return VisitCXXTryStmt(cast<CXXTryStmt>(S));
370
371    case Stmt::DeclStmtClass:
372      return VisitDeclStmt(cast<DeclStmt>(S));
373
374    case Stmt::DefaultStmtClass:
375      return VisitDefaultStmt(cast<DefaultStmt>(S));
376
377    case Stmt::DoStmtClass:
378      return VisitDoStmt(cast<DoStmt>(S));
379
380    case Stmt::ForStmtClass:
381      return VisitForStmt(cast<ForStmt>(S));
382
383    case Stmt::GotoStmtClass:
384      return VisitGotoStmt(cast<GotoStmt>(S));
385
386    case Stmt::IfStmtClass:
387      return VisitIfStmt(cast<IfStmt>(S));
388
389    case Stmt::IndirectGotoStmtClass:
390      return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
391
392    case Stmt::LabelStmtClass:
393      return VisitLabelStmt(cast<LabelStmt>(S));
394
395    case Stmt::ObjCAtCatchStmtClass:
396      return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
397
398    case Stmt::ObjCAtSynchronizedStmtClass:
399      return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
400
401    case Stmt::ObjCAtThrowStmtClass:
402      return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
403
404    case Stmt::ObjCAtTryStmtClass:
405      return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
406
407    case Stmt::ObjCForCollectionStmtClass:
408      return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
409
410    case Stmt::ParenExprClass:
411      S = cast<ParenExpr>(S)->getSubExpr();
412      goto tryAgain;
413
414    case Stmt::NullStmtClass:
415      return Block;
416
417    case Stmt::ReturnStmtClass:
418      return VisitReturnStmt(cast<ReturnStmt>(S));
419
420    case Stmt::SizeOfAlignOfExprClass:
421      return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
422
423    case Stmt::StmtExprClass:
424      return VisitStmtExpr(cast<StmtExpr>(S), asc);
425
426    case Stmt::SwitchStmtClass:
427      return VisitSwitchStmt(cast<SwitchStmt>(S));
428
429    case Stmt::WhileStmtClass:
430      return VisitWhileStmt(cast<WhileStmt>(S));
431  }
432}
433
434CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
435  if (asc.alwaysAdd()) {
436    autoCreateBlock();
437    AppendStmt(Block, S, asc);
438  }
439
440  return VisitChildren(S);
441}
442
443/// VisitChildren - Visit the children of a Stmt.
444CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
445  CFGBlock *B = Block;
446  for (Stmt::child_iterator I = Terminator->child_begin(),
447         E = Terminator->child_end(); I != E; ++I) {
448    if (*I) B = Visit(*I);
449  }
450  return B;
451}
452
453CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
454                                         AddStmtChoice asc) {
455  AddressTakenLabels.insert(A->getLabel());
456
457  if (asc.alwaysAdd()) {
458    autoCreateBlock();
459    AppendStmt(Block, A, asc);
460  }
461
462  return Block;
463}
464
465CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
466                                          AddStmtChoice asc) {
467  if (B->isLogicalOp()) { // && or ||
468    CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
469    AppendStmt(ConfluenceBlock, B, asc);
470
471    if (!FinishBlock(ConfluenceBlock))
472      return 0;
473
474    // create the block evaluating the LHS
475    CFGBlock* LHSBlock = createBlock(false);
476    LHSBlock->setTerminator(B);
477
478    // create the block evaluating the RHS
479    Succ = ConfluenceBlock;
480    Block = NULL;
481    CFGBlock* RHSBlock = addStmt(B->getRHS());
482    if (!FinishBlock(RHSBlock))
483      return 0;
484
485    // See if this is a known constant.
486    TryResult KnownVal = TryEvaluateBool(B->getLHS());
487    if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr))
488      KnownVal.negate();
489
490    // Now link the LHSBlock with RHSBlock.
491    if (B->getOpcode() == BinaryOperator::LOr) {
492      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
493      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
494    } else {
495      assert(B->getOpcode() == BinaryOperator::LAnd);
496      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
497      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
498    }
499
500    // Generate the blocks for evaluating the LHS.
501    Block = LHSBlock;
502    return addStmt(B->getLHS());
503  }
504  else if (B->getOpcode() == BinaryOperator::Comma) { // ,
505    autoCreateBlock();
506    AppendStmt(Block, B, asc);
507    addStmt(B->getRHS());
508    return addStmt(B->getLHS());
509  }
510
511  return VisitStmt(B, asc);
512}
513
514CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
515  if (asc.alwaysAdd()) {
516    autoCreateBlock();
517    AppendStmt(Block, E, asc);
518  }
519  return Block;
520}
521
522CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
523  // "break" is a control-flow statement.  Thus we stop processing the current
524  // block.
525  if (Block && !FinishBlock(Block))
526      return 0;
527
528  // Now create a new block that ends with the break statement.
529  Block = createBlock(false);
530  Block->setTerminator(B);
531
532  // If there is no target for the break, then we are looking at an incomplete
533  // AST.  This means that the CFG cannot be constructed.
534  if (BreakTargetBlock)
535    AddSuccessor(Block, BreakTargetBlock);
536  else
537    badCFG = true;
538
539
540  return Block;
541}
542
543CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
544  // If this is a call to a no-return function, this stops the block here.
545  bool NoReturn = false;
546  if (C->getCallee()->getType().getNoReturnAttr()) {
547    NoReturn = true;
548  }
549
550  bool CanThrow = false;
551
552  // Languages without exceptions are assumed to not throw.
553  if (Context->getLangOptions().Exceptions) {
554    CanThrow = true;
555  }
556
557  if (FunctionDecl *FD = C->getDirectCallee()) {
558    if (FD->hasAttr<NoReturnAttr>())
559      NoReturn = true;
560    if (FD->hasAttr<NoThrowAttr>())
561      CanThrow = false;
562  }
563
564  if (!NoReturn && !CanThrow)
565    return VisitStmt(C, asc);
566
567  if (Block) {
568    Succ = Block;
569    if (!FinishBlock(Block))
570      return 0;
571  }
572
573  Block = createBlock(!NoReturn);
574  AppendStmt(Block, C, asc);
575
576  if (NoReturn) {
577    // Wire this to the exit block directly.
578    AddSuccessor(Block, &cfg->getExit());
579  }
580  if (CanThrow) {
581    // Add exceptional edges.
582    if (TryTerminatedBlock)
583      AddSuccessor(Block, TryTerminatedBlock);
584    else
585      AddSuccessor(Block, &cfg->getExit());
586  }
587
588  return VisitChildren(C);
589}
590
591CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
592                                      AddStmtChoice asc) {
593  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
594  AppendStmt(ConfluenceBlock, C, asc);
595  if (!FinishBlock(ConfluenceBlock))
596    return 0;
597
598  Succ = ConfluenceBlock;
599  Block = NULL;
600  CFGBlock* LHSBlock = addStmt(C->getLHS());
601  if (!FinishBlock(LHSBlock))
602    return 0;
603
604  Succ = ConfluenceBlock;
605  Block = NULL;
606  CFGBlock* RHSBlock = addStmt(C->getRHS());
607  if (!FinishBlock(RHSBlock))
608    return 0;
609
610  Block = createBlock(false);
611  // See if this is a known constant.
612  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
613  AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
614  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
615  Block->setTerminator(C);
616  return addStmt(C->getCond());
617}
618
619
620CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
621  EndScope(C);
622
623  CFGBlock* LastBlock = Block;
624
625  for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
626       I != E; ++I ) {
627    LastBlock = addStmt(*I);
628
629    if (badCFG)
630      return NULL;
631  }
632
633  LastBlock = StartScope(C, LastBlock);
634
635  return LastBlock;
636}
637
638CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C,
639                                               AddStmtChoice asc) {
640  // Create the confluence block that will "merge" the results of the ternary
641  // expression.
642  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
643  AppendStmt(ConfluenceBlock, C, asc);
644  if (!FinishBlock(ConfluenceBlock))
645    return 0;
646
647  // Create a block for the LHS expression if there is an LHS expression.  A
648  // GCC extension allows LHS to be NULL, causing the condition to be the
649  // value that is returned instead.
650  //  e.g: x ?: y is shorthand for: x ? x : y;
651  Succ = ConfluenceBlock;
652  Block = NULL;
653  CFGBlock* LHSBlock = NULL;
654  if (C->getLHS()) {
655    LHSBlock = addStmt(C->getLHS());
656    if (!FinishBlock(LHSBlock))
657      return 0;
658    Block = NULL;
659  }
660
661  // Create the block for the RHS expression.
662  Succ = ConfluenceBlock;
663  CFGBlock* RHSBlock = addStmt(C->getRHS());
664  if (!FinishBlock(RHSBlock))
665    return 0;
666
667  // Create the block that will contain the condition.
668  Block = createBlock(false);
669
670  // See if this is a known constant.
671  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
672  if (LHSBlock) {
673    AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
674  } else {
675    if (KnownVal.isFalse()) {
676      // If we know the condition is false, add NULL as the successor for
677      // the block containing the condition.  In this case, the confluence
678      // block will have just one predecessor.
679      AddSuccessor(Block, 0);
680      assert(ConfluenceBlock->pred_size() == 1);
681    } else {
682      // If we have no LHS expression, add the ConfluenceBlock as a direct
683      // successor for the block containing the condition.  Moreover, we need to
684      // reverse the order of the predecessors in the ConfluenceBlock because
685      // the RHSBlock will have been added to the succcessors already, and we
686      // want the first predecessor to the the block containing the expression
687      // for the case when the ternary expression evaluates to true.
688      AddSuccessor(Block, ConfluenceBlock);
689      assert(ConfluenceBlock->pred_size() == 2);
690      std::reverse(ConfluenceBlock->pred_begin(),
691                   ConfluenceBlock->pred_end());
692    }
693  }
694
695  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
696  Block->setTerminator(C);
697  return addStmt(C->getCond());
698}
699
700CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
701  autoCreateBlock();
702
703  if (DS->isSingleDecl()) {
704    AppendStmt(Block, DS);
705    return VisitDeclSubExpr(DS->getSingleDecl());
706  }
707
708  CFGBlock *B = 0;
709
710  // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
711  typedef llvm::SmallVector<Decl*,10> BufTy;
712  BufTy Buf(DS->decl_begin(), DS->decl_end());
713
714  for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
715    // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
716    unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
717               ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
718
719    // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
720    // automatically freed with the CFG.
721    DeclGroupRef DG(*I);
722    Decl *D = *I;
723    void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
724    DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
725
726    // Append the fake DeclStmt to block.
727    AppendStmt(Block, DSNew);
728    B = VisitDeclSubExpr(D);
729  }
730
731  return B;
732}
733
734/// VisitDeclSubExpr - Utility method to add block-level expressions for
735///  initializers in Decls.
736CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
737  assert(Block);
738
739  VarDecl *VD = dyn_cast<VarDecl>(D);
740
741  if (!VD)
742    return Block;
743
744  Expr *Init = VD->getInit();
745
746  if (Init) {
747    // Optimization: Don't create separate block-level statements for literals.
748    switch (Init->getStmtClass()) {
749      case Stmt::IntegerLiteralClass:
750      case Stmt::CharacterLiteralClass:
751      case Stmt::StringLiteralClass:
752        break;
753      default:
754        Block = addStmt(Init,
755                        VD->getType()->isReferenceType()
756                        ? AddStmtChoice::AlwaysAddAsLValue
757                        : AddStmtChoice::AlwaysAdd);
758    }
759  }
760
761  // If the type of VD is a VLA, then we must process its size expressions.
762  for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
763       VA = FindVA(VA->getElementType().getTypePtr()))
764    Block = addStmt(VA->getSizeExpr());
765
766  return Block;
767}
768
769CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
770  // We may see an if statement in the middle of a basic block, or it may be the
771  // first statement we are processing.  In either case, we create a new basic
772  // block.  First, we create the blocks for the then...else statements, and
773  // then we create the block containing the if statement.  If we were in the
774  // middle of a block, we stop processing that block.  That block is then the
775  // implicit successor for the "then" and "else" clauses.
776
777  // The block we were proccessing is now finished.  Make it the successor
778  // block.
779  if (Block) {
780    Succ = Block;
781    if (!FinishBlock(Block))
782      return 0;
783  }
784
785  // Process the false branch.
786  CFGBlock* ElseBlock = Succ;
787
788  if (Stmt* Else = I->getElse()) {
789    SaveAndRestore<CFGBlock*> sv(Succ);
790
791    // NULL out Block so that the recursive call to Visit will
792    // create a new basic block.
793    Block = NULL;
794    ElseBlock = addStmt(Else);
795
796    if (!ElseBlock) // Can occur when the Else body has all NullStmts.
797      ElseBlock = sv.get();
798    else if (Block) {
799      if (!FinishBlock(ElseBlock))
800        return 0;
801    }
802  }
803
804  // Process the true branch.
805  CFGBlock* ThenBlock;
806  {
807    Stmt* Then = I->getThen();
808    assert(Then);
809    SaveAndRestore<CFGBlock*> sv(Succ);
810    Block = NULL;
811    ThenBlock = addStmt(Then);
812
813    if (!ThenBlock) {
814      // We can reach here if the "then" body has all NullStmts.
815      // Create an empty block so we can distinguish between true and false
816      // branches in path-sensitive analyses.
817      ThenBlock = createBlock(false);
818      AddSuccessor(ThenBlock, sv.get());
819    } else if (Block) {
820      if (!FinishBlock(ThenBlock))
821        return 0;
822    }
823  }
824
825  // Now create a new block containing the if statement.
826  Block = createBlock(false);
827
828  // Set the terminator of the new block to the If statement.
829  Block->setTerminator(I);
830
831  // See if this is a known constant.
832  const TryResult &KnownVal = TryEvaluateBool(I->getCond());
833
834  // Now add the successors.
835  AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
836  AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
837
838  // Add the condition as the last statement in the new block.  This may create
839  // new blocks as the condition may contain control-flow.  Any newly created
840  // blocks will be pointed to be "Block".
841  Block = addStmt(I->getCond());
842
843  // Finally, if the IfStmt contains a condition variable, add both the IfStmt
844  // and the condition variable initialization to the CFG.
845  if (VarDecl *VD = I->getConditionVariable()) {
846    if (Expr *Init = VD->getInit()) {
847      autoCreateBlock();
848      AppendStmt(Block, I, AddStmtChoice::AlwaysAdd);
849      addStmt(Init);
850    }
851  }
852
853  return Block;
854}
855
856
857CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
858  // If we were in the middle of a block we stop processing that block.
859  //
860  // NOTE: If a "return" appears in the middle of a block, this means that the
861  //       code afterwards is DEAD (unreachable).  We still keep a basic block
862  //       for that code; a simple "mark-and-sweep" from the entry block will be
863  //       able to report such dead blocks.
864  if (Block)
865    FinishBlock(Block);
866
867  // Create the new block.
868  Block = createBlock(false);
869
870  // The Exit block is the only successor.
871  AddSuccessor(Block, &cfg->getExit());
872
873  // Add the return statement to the block.  This may create new blocks if R
874  // contains control-flow (short-circuit operations).
875  return VisitStmt(R, AddStmtChoice::AlwaysAdd);
876}
877
878CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
879  // Get the block of the labeled statement.  Add it to our map.
880  addStmt(L->getSubStmt());
881  CFGBlock* LabelBlock = Block;
882
883  if (!LabelBlock)              // This can happen when the body is empty, i.e.
884    LabelBlock = createBlock(); // scopes that only contains NullStmts.
885
886  assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
887  LabelMap[ L ] = LabelBlock;
888
889  // Labels partition blocks, so this is the end of the basic block we were
890  // processing (L is the block's label).  Because this is label (and we have
891  // already processed the substatement) there is no extra control-flow to worry
892  // about.
893  LabelBlock->setLabel(L);
894  if (!FinishBlock(LabelBlock))
895    return 0;
896
897  // We set Block to NULL to allow lazy creation of a new block (if necessary);
898  Block = NULL;
899
900  // This block is now the implicit successor of other blocks.
901  Succ = LabelBlock;
902
903  return LabelBlock;
904}
905
906CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
907  // Goto is a control-flow statement.  Thus we stop processing the current
908  // block and create a new one.
909  if (Block)
910    FinishBlock(Block);
911
912  Block = createBlock(false);
913  Block->setTerminator(G);
914
915  // If we already know the mapping to the label block add the successor now.
916  LabelMapTy::iterator I = LabelMap.find(G->getLabel());
917
918  if (I == LabelMap.end())
919    // We will need to backpatch this block later.
920    BackpatchBlocks.push_back(Block);
921  else
922    AddSuccessor(Block, I->second);
923
924  return Block;
925}
926
927CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
928  CFGBlock* LoopSuccessor = NULL;
929
930  // "for" is a control-flow statement.  Thus we stop processing the current
931  // block.
932  if (Block) {
933    if (!FinishBlock(Block))
934      return 0;
935    LoopSuccessor = Block;
936  } else
937    LoopSuccessor = Succ;
938
939  // Because of short-circuit evaluation, the condition of the loop can span
940  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
941  // evaluate the condition.
942  CFGBlock* ExitConditionBlock = createBlock(false);
943  CFGBlock* EntryConditionBlock = ExitConditionBlock;
944
945  // Set the terminator for the "exit" condition block.
946  ExitConditionBlock->setTerminator(F);
947
948  // Now add the actual condition to the condition block.  Because the condition
949  // itself may contain control-flow, new blocks may be created.
950  if (Stmt* C = F->getCond()) {
951    Block = ExitConditionBlock;
952    EntryConditionBlock = addStmt(C);
953    assert(Block == EntryConditionBlock);
954
955    // If this block contains a condition variable, add both the condition
956    // variable and initializer to the CFG.
957    if (VarDecl *VD = F->getConditionVariable()) {
958      if (Expr *Init = VD->getInit()) {
959        autoCreateBlock();
960        AppendStmt(Block, F, AddStmtChoice::AlwaysAdd);
961        EntryConditionBlock = addStmt(Init);
962        assert(Block == EntryConditionBlock);
963      }
964    }
965
966    if (Block) {
967      if (!FinishBlock(EntryConditionBlock))
968        return 0;
969    }
970  }
971
972  // The condition block is the implicit successor for the loop body as well as
973  // any code above the loop.
974  Succ = EntryConditionBlock;
975
976  // See if this is a known constant.
977  TryResult KnownVal(true);
978
979  if (F->getCond())
980    KnownVal = TryEvaluateBool(F->getCond());
981
982  // Now create the loop body.
983  {
984    assert(F->getBody());
985
986    // Save the current values for Block, Succ, and continue and break targets
987    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
988      save_continue(ContinueTargetBlock),
989      save_break(BreakTargetBlock);
990
991    // Create a new block to contain the (bottom) of the loop body.
992    Block = NULL;
993
994    if (Stmt* I = F->getInc()) {
995      // Generate increment code in its own basic block.  This is the target of
996      // continue statements.
997      Succ = addStmt(I);
998    } else {
999      // No increment code.  Create a special, empty, block that is used as the
1000      // target block for "looping back" to the start of the loop.
1001      assert(Succ == EntryConditionBlock);
1002      Succ = createBlock();
1003    }
1004
1005    // Finish up the increment (or empty) block if it hasn't been already.
1006    if (Block) {
1007      assert(Block == Succ);
1008      if (!FinishBlock(Block))
1009        return 0;
1010      Block = 0;
1011    }
1012
1013    ContinueTargetBlock = Succ;
1014
1015    // The starting block for the loop increment is the block that should
1016    // represent the 'loop target' for looping back to the start of the loop.
1017    ContinueTargetBlock->setLoopTarget(F);
1018
1019    // All breaks should go to the code following the loop.
1020    BreakTargetBlock = LoopSuccessor;
1021
1022    // Now populate the body block, and in the process create new blocks as we
1023    // walk the body of the loop.
1024    CFGBlock* BodyBlock = addStmt(F->getBody());
1025
1026    if (!BodyBlock)
1027      BodyBlock = ContinueTargetBlock; // can happen for "for (...;...;...) ;"
1028    else if (Block && !FinishBlock(BodyBlock))
1029      return 0;
1030
1031    // This new body block is a successor to our "exit" condition block.
1032    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1033  }
1034
1035  // Link up the condition block with the code that follows the loop.  (the
1036  // false branch).
1037  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1038
1039  // If the loop contains initialization, create a new block for those
1040  // statements.  This block can also contain statements that precede the loop.
1041  if (Stmt* I = F->getInit()) {
1042    Block = createBlock();
1043    return addStmt(I);
1044  } else {
1045    // There is no loop initialization.  We are thus basically a while loop.
1046    // NULL out Block to force lazy block construction.
1047    Block = NULL;
1048    Succ = EntryConditionBlock;
1049    return EntryConditionBlock;
1050  }
1051}
1052
1053CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1054  // Objective-C fast enumeration 'for' statements:
1055  //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1056  //
1057  //  for ( Type newVariable in collection_expression ) { statements }
1058  //
1059  //  becomes:
1060  //
1061  //   prologue:
1062  //     1. collection_expression
1063  //     T. jump to loop_entry
1064  //   loop_entry:
1065  //     1. side-effects of element expression
1066  //     1. ObjCForCollectionStmt [performs binding to newVariable]
1067  //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
1068  //   TB:
1069  //     statements
1070  //     T. jump to loop_entry
1071  //   FB:
1072  //     what comes after
1073  //
1074  //  and
1075  //
1076  //  Type existingItem;
1077  //  for ( existingItem in expression ) { statements }
1078  //
1079  //  becomes:
1080  //
1081  //   the same with newVariable replaced with existingItem; the binding works
1082  //   the same except that for one ObjCForCollectionStmt::getElement() returns
1083  //   a DeclStmt and the other returns a DeclRefExpr.
1084  //
1085
1086  CFGBlock* LoopSuccessor = 0;
1087
1088  if (Block) {
1089    if (!FinishBlock(Block))
1090      return 0;
1091    LoopSuccessor = Block;
1092    Block = 0;
1093  } else
1094    LoopSuccessor = Succ;
1095
1096  // Build the condition blocks.
1097  CFGBlock* ExitConditionBlock = createBlock(false);
1098  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1099
1100  // Set the terminator for the "exit" condition block.
1101  ExitConditionBlock->setTerminator(S);
1102
1103  // The last statement in the block should be the ObjCForCollectionStmt, which
1104  // performs the actual binding to 'element' and determines if there are any
1105  // more items in the collection.
1106  AppendStmt(ExitConditionBlock, S);
1107  Block = ExitConditionBlock;
1108
1109  // Walk the 'element' expression to see if there are any side-effects.  We
1110  // generate new blocks as necesary.  We DON'T add the statement by default to
1111  // the CFG unless it contains control-flow.
1112  EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1113  if (Block) {
1114    if (!FinishBlock(EntryConditionBlock))
1115      return 0;
1116    Block = 0;
1117  }
1118
1119  // The condition block is the implicit successor for the loop body as well as
1120  // any code above the loop.
1121  Succ = EntryConditionBlock;
1122
1123  // Now create the true branch.
1124  {
1125    // Save the current values for Succ, continue and break targets.
1126    SaveAndRestore<CFGBlock*> save_Succ(Succ),
1127      save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
1128
1129    BreakTargetBlock = LoopSuccessor;
1130    ContinueTargetBlock = EntryConditionBlock;
1131
1132    CFGBlock* BodyBlock = addStmt(S->getBody());
1133
1134    if (!BodyBlock)
1135      BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1136    else if (Block) {
1137      if (!FinishBlock(BodyBlock))
1138        return 0;
1139    }
1140
1141    // This new body block is a successor to our "exit" condition block.
1142    AddSuccessor(ExitConditionBlock, BodyBlock);
1143  }
1144
1145  // Link up the condition block with the code that follows the loop.
1146  // (the false branch).
1147  AddSuccessor(ExitConditionBlock, LoopSuccessor);
1148
1149  // Now create a prologue block to contain the collection expression.
1150  Block = createBlock();
1151  return addStmt(S->getCollection());
1152}
1153
1154CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1155  // FIXME: Add locking 'primitives' to CFG for @synchronized.
1156
1157  // Inline the body.
1158  CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1159
1160  // The sync body starts its own basic block.  This makes it a little easier
1161  // for diagnostic clients.
1162  if (SyncBlock) {
1163    if (!FinishBlock(SyncBlock))
1164      return 0;
1165
1166    Block = 0;
1167  }
1168
1169  Succ = SyncBlock;
1170
1171  // Inline the sync expression.
1172  return addStmt(S->getSynchExpr());
1173}
1174
1175CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1176  // FIXME
1177  return NYS();
1178}
1179
1180CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1181  CFGBlock* LoopSuccessor = NULL;
1182
1183  // "while" is a control-flow statement.  Thus we stop processing the current
1184  // block.
1185  if (Block) {
1186    if (!FinishBlock(Block))
1187      return 0;
1188    LoopSuccessor = Block;
1189  } else
1190    LoopSuccessor = Succ;
1191
1192  // Because of short-circuit evaluation, the condition of the loop can span
1193  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1194  // evaluate the condition.
1195  CFGBlock* ExitConditionBlock = createBlock(false);
1196  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1197
1198  // Set the terminator for the "exit" condition block.
1199  ExitConditionBlock->setTerminator(W);
1200
1201  // Now add the actual condition to the condition block.  Because the condition
1202  // itself may contain control-flow, new blocks may be created.  Thus we update
1203  // "Succ" after adding the condition.
1204  if (Stmt* C = W->getCond()) {
1205    Block = ExitConditionBlock;
1206    EntryConditionBlock = addStmt(C);
1207    assert(Block == EntryConditionBlock);
1208
1209    // If this block contains a condition variable, add both the condition
1210    // variable and initializer to the CFG.
1211    if (VarDecl *VD = W->getConditionVariable()) {
1212      if (Expr *Init = VD->getInit()) {
1213        autoCreateBlock();
1214        AppendStmt(Block, W, AddStmtChoice::AlwaysAdd);
1215        EntryConditionBlock = addStmt(Init);
1216        assert(Block == EntryConditionBlock);
1217      }
1218    }
1219
1220    if (Block) {
1221      if (!FinishBlock(EntryConditionBlock))
1222        return 0;
1223    }
1224  }
1225
1226  // The condition block is the implicit successor for the loop body as well as
1227  // any code above the loop.
1228  Succ = EntryConditionBlock;
1229
1230  // See if this is a known constant.
1231  const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1232
1233  // Process the loop body.
1234  {
1235    assert(W->getBody());
1236
1237    // Save the current values for Block, Succ, and continue and break targets
1238    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1239                              save_continue(ContinueTargetBlock),
1240                              save_break(BreakTargetBlock);
1241
1242    // Create an empty block to represent the transition block for looping back
1243    // to the head of the loop.
1244    Block = 0;
1245    assert(Succ == EntryConditionBlock);
1246    Succ = createBlock();
1247    Succ->setLoopTarget(W);
1248    ContinueTargetBlock = Succ;
1249
1250    // All breaks should go to the code following the loop.
1251    BreakTargetBlock = LoopSuccessor;
1252
1253    // NULL out Block to force lazy instantiation of blocks for the body.
1254    Block = NULL;
1255
1256    // Create the body.  The returned block is the entry to the loop body.
1257    CFGBlock* BodyBlock = addStmt(W->getBody());
1258
1259    if (!BodyBlock)
1260      BodyBlock = ContinueTargetBlock; // can happen for "while(...) ;"
1261    else if (Block) {
1262      if (!FinishBlock(BodyBlock))
1263        return 0;
1264    }
1265
1266    // Add the loop body entry as a successor to the condition.
1267    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1268  }
1269
1270  // Link up the condition block with the code that follows the loop.  (the
1271  // false branch).
1272  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1273
1274  // There can be no more statements in the condition block since we loop back
1275  // to this block.  NULL out Block to force lazy creation of another block.
1276  Block = NULL;
1277
1278  // Return the condition block, which is the dominating block for the loop.
1279  Succ = EntryConditionBlock;
1280  return EntryConditionBlock;
1281}
1282
1283
1284CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1285  // FIXME: For now we pretend that @catch and the code it contains does not
1286  //  exit.
1287  return Block;
1288}
1289
1290CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1291  // FIXME: This isn't complete.  We basically treat @throw like a return
1292  //  statement.
1293
1294  // If we were in the middle of a block we stop processing that block.
1295  if (Block && !FinishBlock(Block))
1296    return 0;
1297
1298  // Create the new block.
1299  Block = createBlock(false);
1300
1301  // The Exit block is the only successor.
1302  AddSuccessor(Block, &cfg->getExit());
1303
1304  // Add the statement to the block.  This may create new blocks if S contains
1305  // control-flow (short-circuit operations).
1306  return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1307}
1308
1309CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1310  // If we were in the middle of a block we stop processing that block.
1311  if (Block && !FinishBlock(Block))
1312    return 0;
1313
1314  // Create the new block.
1315  Block = createBlock(false);
1316
1317  if (TryTerminatedBlock)
1318    // The current try statement is the only successor.
1319    AddSuccessor(Block, TryTerminatedBlock);
1320  else
1321    // otherwise the Exit block is the only successor.
1322    AddSuccessor(Block, &cfg->getExit());
1323
1324  // Add the statement to the block.  This may create new blocks if S contains
1325  // control-flow (short-circuit operations).
1326  return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1327}
1328
1329CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1330  CFGBlock* LoopSuccessor = NULL;
1331
1332  // "do...while" is a control-flow statement.  Thus we stop processing the
1333  // current block.
1334  if (Block) {
1335    if (!FinishBlock(Block))
1336      return 0;
1337    LoopSuccessor = Block;
1338  } else
1339    LoopSuccessor = Succ;
1340
1341  // Because of short-circuit evaluation, the condition of the loop can span
1342  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1343  // evaluate the condition.
1344  CFGBlock* ExitConditionBlock = createBlock(false);
1345  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1346
1347  // Set the terminator for the "exit" condition block.
1348  ExitConditionBlock->setTerminator(D);
1349
1350  // Now add the actual condition to the condition block.  Because the condition
1351  // itself may contain control-flow, new blocks may be created.
1352  if (Stmt* C = D->getCond()) {
1353    Block = ExitConditionBlock;
1354    EntryConditionBlock = addStmt(C);
1355    if (Block) {
1356      if (!FinishBlock(EntryConditionBlock))
1357        return 0;
1358    }
1359  }
1360
1361  // The condition block is the implicit successor for the loop body.
1362  Succ = EntryConditionBlock;
1363
1364  // See if this is a known constant.
1365  const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1366
1367  // Process the loop body.
1368  CFGBlock* BodyBlock = NULL;
1369  {
1370    assert(D->getBody());
1371
1372    // Save the current values for Block, Succ, and continue and break targets
1373    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1374      save_continue(ContinueTargetBlock),
1375      save_break(BreakTargetBlock);
1376
1377    // All continues within this loop should go to the condition block
1378    ContinueTargetBlock = EntryConditionBlock;
1379
1380    // All breaks should go to the code following the loop.
1381    BreakTargetBlock = LoopSuccessor;
1382
1383    // NULL out Block to force lazy instantiation of blocks for the body.
1384    Block = NULL;
1385
1386    // Create the body.  The returned block is the entry to the loop body.
1387    BodyBlock = addStmt(D->getBody());
1388
1389    if (!BodyBlock)
1390      BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1391    else if (Block) {
1392      if (!FinishBlock(BodyBlock))
1393        return 0;
1394    }
1395
1396    // Add an intermediate block between the BodyBlock and the
1397    // ExitConditionBlock to represent the "loop back" transition.  Create an
1398    // empty block to represent the transition block for looping back to the
1399    // head of the loop.
1400    // FIXME: Can we do this more efficiently without adding another block?
1401    Block = NULL;
1402    Succ = BodyBlock;
1403    CFGBlock *LoopBackBlock = createBlock();
1404    LoopBackBlock->setLoopTarget(D);
1405
1406    // Add the loop body entry as a successor to the condition.
1407    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : LoopBackBlock);
1408  }
1409
1410  // Link up the condition block with the code that follows the loop.
1411  // (the false branch).
1412  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1413
1414  // There can be no more statements in the body block(s) since we loop back to
1415  // the body.  NULL out Block to force lazy creation of another block.
1416  Block = NULL;
1417
1418  // Return the loop body, which is the dominating block for the loop.
1419  Succ = BodyBlock;
1420  return BodyBlock;
1421}
1422
1423CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1424  // "continue" is a control-flow statement.  Thus we stop processing the
1425  // current block.
1426  if (Block && !FinishBlock(Block))
1427      return 0;
1428
1429  // Now create a new block that ends with the continue statement.
1430  Block = createBlock(false);
1431  Block->setTerminator(C);
1432
1433  // If there is no target for the continue, then we are looking at an
1434  // incomplete AST.  This means the CFG cannot be constructed.
1435  if (ContinueTargetBlock)
1436    AddSuccessor(Block, ContinueTargetBlock);
1437  else
1438    badCFG = true;
1439
1440  return Block;
1441}
1442
1443CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1444                                             AddStmtChoice asc) {
1445
1446  if (asc.alwaysAdd()) {
1447    autoCreateBlock();
1448    AppendStmt(Block, E);
1449  }
1450
1451  // VLA types have expressions that must be evaluated.
1452  if (E->isArgumentType()) {
1453    for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1454         VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1455      addStmt(VA->getSizeExpr());
1456  }
1457
1458  return Block;
1459}
1460
1461/// VisitStmtExpr - Utility method to handle (nested) statement
1462///  expressions (a GCC extension).
1463CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
1464  if (asc.alwaysAdd()) {
1465    autoCreateBlock();
1466    AppendStmt(Block, SE);
1467  }
1468  return VisitCompoundStmt(SE->getSubStmt());
1469}
1470
1471CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1472  // "switch" is a control-flow statement.  Thus we stop processing the current
1473  // block.
1474  CFGBlock* SwitchSuccessor = NULL;
1475
1476  if (Block) {
1477    if (!FinishBlock(Block))
1478      return 0;
1479    SwitchSuccessor = Block;
1480  } else SwitchSuccessor = Succ;
1481
1482  // Save the current "switch" context.
1483  SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1484                            save_break(BreakTargetBlock),
1485                            save_default(DefaultCaseBlock);
1486
1487  // Set the "default" case to be the block after the switch statement.  If the
1488  // switch statement contains a "default:", this value will be overwritten with
1489  // the block for that code.
1490  DefaultCaseBlock = SwitchSuccessor;
1491
1492  // Create a new block that will contain the switch statement.
1493  SwitchTerminatedBlock = createBlock(false);
1494
1495  // Now process the switch body.  The code after the switch is the implicit
1496  // successor.
1497  Succ = SwitchSuccessor;
1498  BreakTargetBlock = SwitchSuccessor;
1499
1500  // When visiting the body, the case statements should automatically get linked
1501  // up to the switch.  We also don't keep a pointer to the body, since all
1502  // control-flow from the switch goes to case/default statements.
1503  assert(Terminator->getBody() && "switch must contain a non-NULL body");
1504  Block = NULL;
1505  CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1506  if (Block) {
1507    if (!FinishBlock(BodyBlock))
1508      return 0;
1509  }
1510
1511  // If we have no "default:" case, the default transition is to the code
1512  // following the switch body.
1513  AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
1514
1515  // Add the terminator and condition in the switch block.
1516  SwitchTerminatedBlock->setTerminator(Terminator);
1517  assert(Terminator->getCond() && "switch condition must be non-NULL");
1518  Block = SwitchTerminatedBlock;
1519  Block = addStmt(Terminator->getCond());
1520
1521  // Finally, if the SwitchStmt contains a condition variable, add both the
1522  // SwitchStmt and the condition variable initialization to the CFG.
1523  if (VarDecl *VD = Terminator->getConditionVariable()) {
1524    if (Expr *Init = VD->getInit()) {
1525      autoCreateBlock();
1526      AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd);
1527      addStmt(Init);
1528    }
1529  }
1530
1531  return Block;
1532}
1533
1534CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1535  // CaseStmts are essentially labels, so they are the first statement in a
1536  // block.
1537
1538  if (CS->getSubStmt())
1539    addStmt(CS->getSubStmt());
1540
1541  CFGBlock* CaseBlock = Block;
1542  if (!CaseBlock)
1543    CaseBlock = createBlock();
1544
1545  // Cases statements partition blocks, so this is the top of the basic block we
1546  // were processing (the "case XXX:" is the label).
1547  CaseBlock->setLabel(CS);
1548
1549  if (!FinishBlock(CaseBlock))
1550    return 0;
1551
1552  // Add this block to the list of successors for the block with the switch
1553  // statement.
1554  assert(SwitchTerminatedBlock);
1555  AddSuccessor(SwitchTerminatedBlock, CaseBlock);
1556
1557  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1558  Block = NULL;
1559
1560  // This block is now the implicit successor of other blocks.
1561  Succ = CaseBlock;
1562
1563  return CaseBlock;
1564}
1565
1566CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1567  if (Terminator->getSubStmt())
1568    addStmt(Terminator->getSubStmt());
1569
1570  DefaultCaseBlock = Block;
1571
1572  if (!DefaultCaseBlock)
1573    DefaultCaseBlock = createBlock();
1574
1575  // Default statements partition blocks, so this is the top of the basic block
1576  // we were processing (the "default:" is the label).
1577  DefaultCaseBlock->setLabel(Terminator);
1578
1579  if (!FinishBlock(DefaultCaseBlock))
1580    return 0;
1581
1582  // Unlike case statements, we don't add the default block to the successors
1583  // for the switch statement immediately.  This is done when we finish
1584  // processing the switch statement.  This allows for the default case
1585  // (including a fall-through to the code after the switch statement) to always
1586  // be the last successor of a switch-terminated block.
1587
1588  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1589  Block = NULL;
1590
1591  // This block is now the implicit successor of other blocks.
1592  Succ = DefaultCaseBlock;
1593
1594  return DefaultCaseBlock;
1595}
1596
1597CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
1598  // "try"/"catch" is a control-flow statement.  Thus we stop processing the
1599  // current block.
1600  CFGBlock* TrySuccessor = NULL;
1601
1602  if (Block) {
1603    if (!FinishBlock(Block))
1604      return 0;
1605    TrySuccessor = Block;
1606  } else TrySuccessor = Succ;
1607
1608  CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
1609
1610  // Create a new block that will contain the try statement.
1611  CFGBlock *NewTryTerminatedBlock = createBlock(false);
1612  // Add the terminator in the try block.
1613  NewTryTerminatedBlock->setTerminator(Terminator);
1614
1615  bool HasCatchAll = false;
1616  for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
1617    // The code after the try is the implicit successor.
1618    Succ = TrySuccessor;
1619    CXXCatchStmt *CS = Terminator->getHandler(h);
1620    if (CS->getExceptionDecl() == 0) {
1621      HasCatchAll = true;
1622    }
1623    Block = NULL;
1624    CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
1625    if (CatchBlock == 0)
1626      return 0;
1627    // Add this block to the list of successors for the block with the try
1628    // statement.
1629    AddSuccessor(NewTryTerminatedBlock, CatchBlock);
1630  }
1631  if (!HasCatchAll) {
1632    if (PrevTryTerminatedBlock)
1633      AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
1634    else
1635      AddSuccessor(NewTryTerminatedBlock, &cfg->getExit());
1636  }
1637
1638  // The code after the try is the implicit successor.
1639  Succ = TrySuccessor;
1640
1641  // Save the current "try" context.
1642  SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
1643  TryTerminatedBlock = NewTryTerminatedBlock;
1644
1645  assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
1646  Block = NULL;
1647  Block = addStmt(Terminator->getTryBlock());
1648  return Block;
1649}
1650
1651CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
1652  // CXXCatchStmt are treated like labels, so they are the first statement in a
1653  // block.
1654
1655  if (CS->getHandlerBlock())
1656    addStmt(CS->getHandlerBlock());
1657
1658  CFGBlock* CatchBlock = Block;
1659  if (!CatchBlock)
1660    CatchBlock = createBlock();
1661
1662  CatchBlock->setLabel(CS);
1663
1664  if (!FinishBlock(CatchBlock))
1665    return 0;
1666
1667  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1668  Block = NULL;
1669
1670  return CatchBlock;
1671}
1672
1673CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1674  // Lazily create the indirect-goto dispatch block if there isn't one already.
1675  CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1676
1677  if (!IBlock) {
1678    IBlock = createBlock(false);
1679    cfg->setIndirectGotoBlock(IBlock);
1680  }
1681
1682  // IndirectGoto is a control-flow statement.  Thus we stop processing the
1683  // current block and create a new one.
1684  if (Block && !FinishBlock(Block))
1685    return 0;
1686
1687  Block = createBlock(false);
1688  Block->setTerminator(I);
1689  AddSuccessor(Block, IBlock);
1690  return addStmt(I->getTarget());
1691}
1692
1693} // end anonymous namespace
1694
1695/// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
1696///  no successors or predecessors.  If this is the first block created in the
1697///  CFG, it is automatically set to be the Entry and Exit of the CFG.
1698CFGBlock* CFG::createBlock() {
1699  bool first_block = begin() == end();
1700
1701  // Create the block.
1702  CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
1703  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
1704  Blocks.push_back(Mem, BlkBVC);
1705
1706  // If this is the first block, set it as the Entry and Exit.
1707  if (first_block)
1708    Entry = Exit = &back();
1709
1710  // Return the block.
1711  return &back();
1712}
1713
1714/// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
1715///  CFG is returned to the caller.
1716CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
1717                   bool AddScopes) {
1718  CFGBuilder Builder;
1719  return Builder.buildCFG(D, Statement, C, AddScopes);
1720}
1721
1722//===----------------------------------------------------------------------===//
1723// CFG: Queries for BlkExprs.
1724//===----------------------------------------------------------------------===//
1725
1726namespace {
1727  typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1728}
1729
1730static void FindSubExprAssignments(Stmt *S,
1731                                   llvm::SmallPtrSet<Expr*,50>& Set) {
1732  if (!S)
1733    return;
1734
1735  for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1736    Stmt *child = *I;
1737    if (!child)
1738      continue;
1739
1740    if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
1741      if (B->isAssignmentOp()) Set.insert(B);
1742
1743    FindSubExprAssignments(child, Set);
1744  }
1745}
1746
1747static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1748  BlkExprMapTy* M = new BlkExprMapTy();
1749
1750  // Look for assignments that are used as subexpressions.  These are the only
1751  // assignments that we want to *possibly* register as a block-level
1752  // expression.  Basically, if an assignment occurs both in a subexpression and
1753  // at the block-level, it is a block-level expression.
1754  llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1755
1756  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1757    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1758      FindSubExprAssignments(*BI, SubExprAssignments);
1759
1760  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1761
1762    // Iterate over the statements again on identify the Expr* and Stmt* at the
1763    // block-level that are block-level expressions.
1764
1765    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1766      if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1767
1768        if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1769          // Assignment expressions that are not nested within another
1770          // expression are really "statements" whose value is never used by
1771          // another expression.
1772          if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1773            continue;
1774        } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1775          // Special handling for statement expressions.  The last statement in
1776          // the statement expression is also a block-level expr.
1777          const CompoundStmt* C = Terminator->getSubStmt();
1778          if (!C->body_empty()) {
1779            unsigned x = M->size();
1780            (*M)[C->body_back()] = x;
1781          }
1782        }
1783
1784        unsigned x = M->size();
1785        (*M)[Exp] = x;
1786      }
1787
1788    // Look at terminators.  The condition is a block-level expression.
1789
1790    Stmt* S = (*I)->getTerminatorCondition();
1791
1792    if (S && M->find(S) == M->end()) {
1793        unsigned x = M->size();
1794        (*M)[S] = x;
1795    }
1796  }
1797
1798  return M;
1799}
1800
1801CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1802  assert(S != NULL);
1803  if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1804
1805  BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1806  BlkExprMapTy::iterator I = M->find(S);
1807  return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
1808}
1809
1810unsigned CFG::getNumBlkExprs() {
1811  if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1812    return M->size();
1813  else {
1814    // We assume callers interested in the number of BlkExprs will want
1815    // the map constructed if it doesn't already exist.
1816    BlkExprMap = (void*) PopulateBlkExprMap(*this);
1817    return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1818  }
1819}
1820
1821//===----------------------------------------------------------------------===//
1822// Cleanup: CFG dstor.
1823//===----------------------------------------------------------------------===//
1824
1825CFG::~CFG() {
1826  delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1827}
1828
1829//===----------------------------------------------------------------------===//
1830// CFG pretty printing
1831//===----------------------------------------------------------------------===//
1832
1833namespace {
1834
1835class StmtPrinterHelper : public PrinterHelper  {
1836  typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1837  StmtMapTy StmtMap;
1838  signed CurrentBlock;
1839  unsigned CurrentStmt;
1840  const LangOptions &LangOpts;
1841public:
1842
1843  StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1844    : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1845    for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1846      unsigned j = 1;
1847      for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
1848           BI != BEnd; ++BI, ++j )
1849        StmtMap[*BI] = std::make_pair((*I)->getBlockID(),j);
1850      }
1851  }
1852
1853  virtual ~StmtPrinterHelper() {}
1854
1855  const LangOptions &getLangOpts() const { return LangOpts; }
1856  void setBlockID(signed i) { CurrentBlock = i; }
1857  void setStmtID(unsigned i) { CurrentStmt = i; }
1858
1859  virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1860
1861    StmtMapTy::iterator I = StmtMap.find(Terminator);
1862
1863    if (I == StmtMap.end())
1864      return false;
1865
1866    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1867                          && I->second.second == CurrentStmt) {
1868      return false;
1869    }
1870
1871    OS << "[B" << I->second.first << "." << I->second.second << "]";
1872    return true;
1873  }
1874};
1875} // end anonymous namespace
1876
1877
1878namespace {
1879class CFGBlockTerminatorPrint
1880  : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1881
1882  llvm::raw_ostream& OS;
1883  StmtPrinterHelper* Helper;
1884  PrintingPolicy Policy;
1885public:
1886  CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1887                          const PrintingPolicy &Policy)
1888    : OS(os), Helper(helper), Policy(Policy) {}
1889
1890  void VisitIfStmt(IfStmt* I) {
1891    OS << "if ";
1892    I->getCond()->printPretty(OS,Helper,Policy);
1893  }
1894
1895  // Default case.
1896  void VisitStmt(Stmt* Terminator) {
1897    Terminator->printPretty(OS, Helper, Policy);
1898  }
1899
1900  void VisitForStmt(ForStmt* F) {
1901    OS << "for (" ;
1902    if (F->getInit())
1903      OS << "...";
1904    OS << "; ";
1905    if (Stmt* C = F->getCond())
1906      C->printPretty(OS, Helper, Policy);
1907    OS << "; ";
1908    if (F->getInc())
1909      OS << "...";
1910    OS << ")";
1911  }
1912
1913  void VisitWhileStmt(WhileStmt* W) {
1914    OS << "while " ;
1915    if (Stmt* C = W->getCond())
1916      C->printPretty(OS, Helper, Policy);
1917  }
1918
1919  void VisitDoStmt(DoStmt* D) {
1920    OS << "do ... while ";
1921    if (Stmt* C = D->getCond())
1922      C->printPretty(OS, Helper, Policy);
1923  }
1924
1925  void VisitSwitchStmt(SwitchStmt* Terminator) {
1926    OS << "switch ";
1927    Terminator->getCond()->printPretty(OS, Helper, Policy);
1928  }
1929
1930  void VisitCXXTryStmt(CXXTryStmt* CS) {
1931    OS << "try ...";
1932  }
1933
1934  void VisitConditionalOperator(ConditionalOperator* C) {
1935    C->getCond()->printPretty(OS, Helper, Policy);
1936    OS << " ? ... : ...";
1937  }
1938
1939  void VisitChooseExpr(ChooseExpr* C) {
1940    OS << "__builtin_choose_expr( ";
1941    C->getCond()->printPretty(OS, Helper, Policy);
1942    OS << " )";
1943  }
1944
1945  void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1946    OS << "goto *";
1947    I->getTarget()->printPretty(OS, Helper, Policy);
1948  }
1949
1950  void VisitBinaryOperator(BinaryOperator* B) {
1951    if (!B->isLogicalOp()) {
1952      VisitExpr(B);
1953      return;
1954    }
1955
1956    B->getLHS()->printPretty(OS, Helper, Policy);
1957
1958    switch (B->getOpcode()) {
1959      case BinaryOperator::LOr:
1960        OS << " || ...";
1961        return;
1962      case BinaryOperator::LAnd:
1963        OS << " && ...";
1964        return;
1965      default:
1966        assert(false && "Invalid logical operator.");
1967    }
1968  }
1969
1970  void VisitExpr(Expr* E) {
1971    E->printPretty(OS, Helper, Policy);
1972  }
1973};
1974} // end anonymous namespace
1975
1976
1977static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1978                       const CFGElement &E) {
1979  Stmt *Terminator = E;
1980
1981  if (E.asStartScope()) {
1982    OS << "start scope\n";
1983    return;
1984  }
1985  if (E.asEndScope()) {
1986    OS << "end scope\n";
1987    return;
1988  }
1989
1990  if (Helper) {
1991    // special printing for statement-expressions.
1992    if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
1993      CompoundStmt* Sub = SE->getSubStmt();
1994
1995      if (Sub->child_begin() != Sub->child_end()) {
1996        OS << "({ ... ; ";
1997        Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
1998        OS << " })\n";
1999        return;
2000      }
2001    }
2002
2003    // special printing for comma expressions.
2004    if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
2005      if (B->getOpcode() == BinaryOperator::Comma) {
2006        OS << "... , ";
2007        Helper->handledStmt(B->getRHS(),OS);
2008        OS << '\n';
2009        return;
2010      }
2011    }
2012  }
2013
2014  Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2015
2016  // Expressions need a newline.
2017  if (isa<Expr>(Terminator)) OS << '\n';
2018}
2019
2020static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
2021                        const CFGBlock& B,
2022                        StmtPrinterHelper* Helper, bool print_edges) {
2023
2024  if (Helper) Helper->setBlockID(B.getBlockID());
2025
2026  // Print the header.
2027  OS << "\n [ B" << B.getBlockID();
2028
2029  if (&B == &cfg->getEntry())
2030    OS << " (ENTRY) ]\n";
2031  else if (&B == &cfg->getExit())
2032    OS << " (EXIT) ]\n";
2033  else if (&B == cfg->getIndirectGotoBlock())
2034    OS << " (INDIRECT GOTO DISPATCH) ]\n";
2035  else
2036    OS << " ]\n";
2037
2038  // Print the label of this block.
2039  if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
2040
2041    if (print_edges)
2042      OS << "    ";
2043
2044    if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
2045      OS << L->getName();
2046    else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
2047      OS << "case ";
2048      C->getLHS()->printPretty(OS, Helper,
2049                               PrintingPolicy(Helper->getLangOpts()));
2050      if (C->getRHS()) {
2051        OS << " ... ";
2052        C->getRHS()->printPretty(OS, Helper,
2053                                 PrintingPolicy(Helper->getLangOpts()));
2054      }
2055    } else if (isa<DefaultStmt>(Label))
2056      OS << "default";
2057    else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
2058      OS << "catch (";
2059      if (CS->getExceptionDecl())
2060        CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
2061                                      0);
2062      else
2063        OS << "...";
2064      OS << ")";
2065
2066    } else
2067      assert(false && "Invalid label statement in CFGBlock.");
2068
2069    OS << ":\n";
2070  }
2071
2072  // Iterate through the statements in the block and print them.
2073  unsigned j = 1;
2074
2075  for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
2076       I != E ; ++I, ++j ) {
2077
2078    // Print the statement # in the basic block and the statement itself.
2079    if (print_edges)
2080      OS << "    ";
2081
2082    OS << llvm::format("%3d", j) << ": ";
2083
2084    if (Helper)
2085      Helper->setStmtID(j);
2086
2087    print_stmt(OS,Helper,*I);
2088  }
2089
2090  // Print the terminator of this block.
2091  if (B.getTerminator()) {
2092    if (print_edges)
2093      OS << "    ";
2094
2095    OS << "  T: ";
2096
2097    if (Helper) Helper->setBlockID(-1);
2098
2099    CFGBlockTerminatorPrint TPrinter(OS, Helper,
2100                                     PrintingPolicy(Helper->getLangOpts()));
2101    TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
2102    OS << '\n';
2103  }
2104
2105  if (print_edges) {
2106    // Print the predecessors of this block.
2107    OS << "    Predecessors (" << B.pred_size() << "):";
2108    unsigned i = 0;
2109
2110    for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
2111         I != E; ++I, ++i) {
2112
2113      if (i == 8 || (i-8) == 0)
2114        OS << "\n     ";
2115
2116      OS << " B" << (*I)->getBlockID();
2117    }
2118
2119    OS << '\n';
2120
2121    // Print the successors of this block.
2122    OS << "    Successors (" << B.succ_size() << "):";
2123    i = 0;
2124
2125    for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
2126         I != E; ++I, ++i) {
2127
2128      if (i == 8 || (i-8) % 10 == 0)
2129        OS << "\n    ";
2130
2131      if (*I)
2132        OS << " B" << (*I)->getBlockID();
2133      else
2134        OS  << " NULL";
2135    }
2136
2137    OS << '\n';
2138  }
2139}
2140
2141
2142/// dump - A simple pretty printer of a CFG that outputs to stderr.
2143void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
2144
2145/// print - A simple pretty printer of a CFG that outputs to an ostream.
2146void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
2147  StmtPrinterHelper Helper(this, LO);
2148
2149  // Print the entry block.
2150  print_block(OS, this, getEntry(), &Helper, true);
2151
2152  // Iterate through the CFGBlocks and print them one by one.
2153  for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
2154    // Skip the entry block, because we already printed it.
2155    if (&(**I) == &getEntry() || &(**I) == &getExit())
2156      continue;
2157
2158    print_block(OS, this, **I, &Helper, true);
2159  }
2160
2161  // Print the exit block.
2162  print_block(OS, this, getExit(), &Helper, true);
2163  OS.flush();
2164}
2165
2166/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
2167void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
2168  print(llvm::errs(), cfg, LO);
2169}
2170
2171/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
2172///   Generally this will only be called from CFG::print.
2173void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
2174                     const LangOptions &LO) const {
2175  StmtPrinterHelper Helper(cfg, LO);
2176  print_block(OS, cfg, *this, &Helper, true);
2177}
2178
2179/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
2180void CFGBlock::printTerminator(llvm::raw_ostream &OS,
2181                               const LangOptions &LO) const {
2182  CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
2183  TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
2184}
2185
2186Stmt* CFGBlock::getTerminatorCondition() {
2187
2188  if (!Terminator)
2189    return NULL;
2190
2191  Expr* E = NULL;
2192
2193  switch (Terminator->getStmtClass()) {
2194    default:
2195      break;
2196
2197    case Stmt::ForStmtClass:
2198      E = cast<ForStmt>(Terminator)->getCond();
2199      break;
2200
2201    case Stmt::WhileStmtClass:
2202      E = cast<WhileStmt>(Terminator)->getCond();
2203      break;
2204
2205    case Stmt::DoStmtClass:
2206      E = cast<DoStmt>(Terminator)->getCond();
2207      break;
2208
2209    case Stmt::IfStmtClass:
2210      E = cast<IfStmt>(Terminator)->getCond();
2211      break;
2212
2213    case Stmt::ChooseExprClass:
2214      E = cast<ChooseExpr>(Terminator)->getCond();
2215      break;
2216
2217    case Stmt::IndirectGotoStmtClass:
2218      E = cast<IndirectGotoStmt>(Terminator)->getTarget();
2219      break;
2220
2221    case Stmt::SwitchStmtClass:
2222      E = cast<SwitchStmt>(Terminator)->getCond();
2223      break;
2224
2225    case Stmt::ConditionalOperatorClass:
2226      E = cast<ConditionalOperator>(Terminator)->getCond();
2227      break;
2228
2229    case Stmt::BinaryOperatorClass: // '&&' and '||'
2230      E = cast<BinaryOperator>(Terminator)->getLHS();
2231      break;
2232
2233    case Stmt::ObjCForCollectionStmtClass:
2234      return Terminator;
2235  }
2236
2237  return E ? E->IgnoreParens() : NULL;
2238}
2239
2240bool CFGBlock::hasBinaryBranchTerminator() const {
2241
2242  if (!Terminator)
2243    return false;
2244
2245  Expr* E = NULL;
2246
2247  switch (Terminator->getStmtClass()) {
2248    default:
2249      return false;
2250
2251    case Stmt::ForStmtClass:
2252    case Stmt::WhileStmtClass:
2253    case Stmt::DoStmtClass:
2254    case Stmt::IfStmtClass:
2255    case Stmt::ChooseExprClass:
2256    case Stmt::ConditionalOperatorClass:
2257    case Stmt::BinaryOperatorClass:
2258      return true;
2259  }
2260
2261  return E ? E->IgnoreParens() : NULL;
2262}
2263
2264
2265//===----------------------------------------------------------------------===//
2266// CFG Graphviz Visualization
2267//===----------------------------------------------------------------------===//
2268
2269
2270#ifndef NDEBUG
2271static StmtPrinterHelper* GraphHelper;
2272#endif
2273
2274void CFG::viewCFG(const LangOptions &LO) const {
2275#ifndef NDEBUG
2276  StmtPrinterHelper H(this, LO);
2277  GraphHelper = &H;
2278  llvm::ViewGraph(this,"CFG");
2279  GraphHelper = NULL;
2280#endif
2281}
2282
2283namespace llvm {
2284template<>
2285struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2286
2287  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2288
2289  static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
2290
2291#ifndef NDEBUG
2292    std::string OutSStr;
2293    llvm::raw_string_ostream Out(OutSStr);
2294    print_block(Out,Graph, *Node, GraphHelper, false);
2295    std::string& OutStr = Out.str();
2296
2297    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
2298
2299    // Process string output to make it nicer...
2300    for (unsigned i = 0; i != OutStr.length(); ++i)
2301      if (OutStr[i] == '\n') {                            // Left justify
2302        OutStr[i] = '\\';
2303        OutStr.insert(OutStr.begin()+i+1, 'l');
2304      }
2305
2306    return OutStr;
2307#else
2308    return "";
2309#endif
2310  }
2311};
2312} // end namespace llvm
2313