1 //==- CoreEngine.cpp - Path-Sensitive Dataflow Engine ------------*- 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 a generic engine for intraprocedural, path-sensitive,
11 //  dataflow analysis via graph reachability engine.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/StmtCXX.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Support/Casting.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 #define DEBUG_TYPE "CoreEngine"
28 
29 STATISTIC(NumSteps,
30             "The # of steps executed.");
31 STATISTIC(NumReachedMaxSteps,
32             "The # of times we reached the max number of steps.");
33 STATISTIC(NumPathsExplored,
34             "The # of paths explored by the analyzer.");
35 
36 //===----------------------------------------------------------------------===//
37 // Worklist classes for exploration of reachable states.
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 class DFS : public WorkList {
42   SmallVector<WorkListUnit,20> Stack;
43 public:
44   bool hasWork() const override {
45     return !Stack.empty();
46   }
47 
48   void enqueue(const WorkListUnit& U) override {
49     Stack.push_back(U);
50   }
51 
52   WorkListUnit dequeue() override {
53     assert (!Stack.empty());
54     const WorkListUnit& U = Stack.back();
55     Stack.pop_back(); // This technically "invalidates" U, but we are fine.
56     return U;
57   }
58 };
59 
60 class BFS : public WorkList {
61   std::deque<WorkListUnit> Queue;
62 public:
63   bool hasWork() const override {
64     return !Queue.empty();
65   }
66 
67   void enqueue(const WorkListUnit& U) override {
68     Queue.push_back(U);
69   }
70 
71   WorkListUnit dequeue() override {
72     WorkListUnit U = Queue.front();
73     Queue.pop_front();
74     return U;
75   }
76 
77 };
78 
79 } // end anonymous namespace
80 
81 // Place the dstor for WorkList here because it contains virtual member
82 // functions, and we the code for the dstor generated in one compilation unit.
83 WorkList::~WorkList() {}
84 
85 std::unique_ptr<WorkList> WorkList::makeDFS() {
86   return llvm::make_unique<DFS>();
87 }
88 
89 std::unique_ptr<WorkList> WorkList::makeBFS() {
90   return llvm::make_unique<BFS>();
91 }
92 
93 namespace {
94   class BFSBlockDFSContents : public WorkList {
95     std::deque<WorkListUnit> Queue;
96     SmallVector<WorkListUnit,20> Stack;
97   public:
98     bool hasWork() const override {
99       return !Queue.empty() || !Stack.empty();
100     }
101 
102     void enqueue(const WorkListUnit& U) override {
103       if (U.getNode()->getLocation().getAs<BlockEntrance>())
104         Queue.push_front(U);
105       else
106         Stack.push_back(U);
107     }
108 
109     WorkListUnit dequeue() override {
110       // Process all basic blocks to completion.
111       if (!Stack.empty()) {
112         const WorkListUnit& U = Stack.back();
113         Stack.pop_back(); // This technically "invalidates" U, but we are fine.
114         return U;
115       }
116 
117       assert(!Queue.empty());
118       // Don't use const reference.  The subsequent pop_back() might make it
119       // unsafe.
120       WorkListUnit U = Queue.front();
121       Queue.pop_front();
122       return U;
123     }
124   };
125 } // end anonymous namespace
126 
127 std::unique_ptr<WorkList> WorkList::makeBFSBlockDFSContents() {
128   return llvm::make_unique<BFSBlockDFSContents>();
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // Core analysis engine.
133 //===----------------------------------------------------------------------===//
134 
135 static std::unique_ptr<WorkList> generateWorkList(AnalyzerOptions &Opts) {
136   switch (Opts.getExplorationStrategy()) {
137     case AnalyzerOptions::ExplorationStrategyKind::DFS:
138       return WorkList::makeDFS();
139     case AnalyzerOptions::ExplorationStrategyKind::BFS:
140       return WorkList::makeBFS();
141     case AnalyzerOptions::ExplorationStrategyKind::BFSBlockDFSContents:
142       return WorkList::makeBFSBlockDFSContents();
143     default:
144       llvm_unreachable("Unexpected case");
145   }
146 }
147 
148 CoreEngine::CoreEngine(SubEngine &subengine,
149     FunctionSummariesTy *FS,
150     AnalyzerOptions &Opts) : SubEng(subengine),
151                              WList(generateWorkList(Opts)),
152                              BCounterFactory(G.getAllocator()),
153                              FunctionSummaries(FS) {}
154 
155 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
156 bool CoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps,
157                                    ProgramStateRef InitState) {
158 
159   if (G.num_roots() == 0) { // Initialize the analysis by constructing
160     // the root if none exists.
161 
162     const CFGBlock *Entry = &(L->getCFG()->getEntry());
163 
164     assert (Entry->empty() &&
165             "Entry block must be empty.");
166 
167     assert (Entry->succ_size() == 1 &&
168             "Entry block must have 1 successor.");
169 
170     // Mark the entry block as visited.
171     FunctionSummaries->markVisitedBasicBlock(Entry->getBlockID(),
172                                              L->getDecl(),
173                                              L->getCFG()->getNumBlockIDs());
174 
175     // Get the solitary successor.
176     const CFGBlock *Succ = *(Entry->succ_begin());
177 
178     // Construct an edge representing the
179     // starting location in the function.
180     BlockEdge StartLoc(Entry, Succ, L);
181 
182     // Set the current block counter to being empty.
183     WList->setBlockCounter(BCounterFactory.GetEmptyCounter());
184 
185     if (!InitState)
186       InitState = SubEng.getInitialState(L);
187 
188     bool IsNew;
189     ExplodedNode *Node = G.getNode(StartLoc, InitState, false, &IsNew);
190     assert (IsNew);
191     G.addRoot(Node);
192 
193     NodeBuilderContext BuilderCtx(*this, StartLoc.getDst(), Node);
194     ExplodedNodeSet DstBegin;
195     SubEng.processBeginOfFunction(BuilderCtx, Node, DstBegin, StartLoc);
196 
197     enqueue(DstBegin);
198   }
199 
200   // Check if we have a steps limit
201   bool UnlimitedSteps = Steps == 0;
202   // Cap our pre-reservation in the event that the user specifies
203   // a very large number of maximum steps.
204   const unsigned PreReservationCap = 4000000;
205   if(!UnlimitedSteps)
206     G.reserve(std::min(Steps,PreReservationCap));
207 
208   while (WList->hasWork()) {
209     if (!UnlimitedSteps) {
210       if (Steps == 0) {
211         NumReachedMaxSteps++;
212         break;
213       }
214       --Steps;
215     }
216 
217     NumSteps++;
218 
219     const WorkListUnit& WU = WList->dequeue();
220 
221     // Set the current block counter.
222     WList->setBlockCounter(WU.getBlockCounter());
223 
224     // Retrieve the node.
225     ExplodedNode *Node = WU.getNode();
226 
227     dispatchWorkItem(Node, Node->getLocation(), WU);
228   }
229   SubEng.processEndWorklist(hasWorkRemaining());
230   return WList->hasWork();
231 }
232 
233 void CoreEngine::dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
234                                   const WorkListUnit& WU) {
235   // Dispatch on the location type.
236   switch (Loc.getKind()) {
237     case ProgramPoint::BlockEdgeKind:
238       HandleBlockEdge(Loc.castAs<BlockEdge>(), Pred);
239       break;
240 
241     case ProgramPoint::BlockEntranceKind:
242       HandleBlockEntrance(Loc.castAs<BlockEntrance>(), Pred);
243       break;
244 
245     case ProgramPoint::BlockExitKind:
246       assert (false && "BlockExit location never occur in forward analysis.");
247       break;
248 
249     case ProgramPoint::CallEnterKind: {
250       HandleCallEnter(Loc.castAs<CallEnter>(), Pred);
251       break;
252     }
253 
254     case ProgramPoint::CallExitBeginKind:
255       SubEng.processCallExit(Pred);
256       break;
257 
258     case ProgramPoint::EpsilonKind: {
259       assert(Pred->hasSinglePred() &&
260              "Assume epsilon has exactly one predecessor by construction");
261       ExplodedNode *PNode = Pred->getFirstPred();
262       dispatchWorkItem(Pred, PNode->getLocation(), WU);
263       break;
264     }
265     default:
266       assert(Loc.getAs<PostStmt>() ||
267              Loc.getAs<PostInitializer>() ||
268              Loc.getAs<PostImplicitCall>() ||
269              Loc.getAs<CallExitEnd>() ||
270              Loc.getAs<LoopExit>() ||
271              Loc.getAs<PostAllocatorCall>());
272       HandlePostStmt(WU.getBlock(), WU.getIndex(), Pred);
273       break;
274   }
275 }
276 
277 bool CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,
278                                                  unsigned Steps,
279                                                  ProgramStateRef InitState,
280                                                  ExplodedNodeSet &Dst) {
281   bool DidNotFinish = ExecuteWorkList(L, Steps, InitState);
282   for (ExplodedGraph::eop_iterator I = G.eop_begin(), E = G.eop_end(); I != E;
283        ++I) {
284     Dst.Add(*I);
285   }
286   return DidNotFinish;
287 }
288 
289 void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) {
290 
291   const CFGBlock *Blk = L.getDst();
292   NodeBuilderContext BuilderCtx(*this, Blk, Pred);
293 
294   // Mark this block as visited.
295   const LocationContext *LC = Pred->getLocationContext();
296   FunctionSummaries->markVisitedBasicBlock(Blk->getBlockID(),
297                                            LC->getDecl(),
298                                            LC->getCFG()->getNumBlockIDs());
299 
300   // Check if we are entering the EXIT block.
301   if (Blk == &(L.getLocationContext()->getCFG()->getExit())) {
302 
303     assert (L.getLocationContext()->getCFG()->getExit().size() == 0
304             && "EXIT block cannot contain Stmts.");
305 
306     // Get return statement..
307     const ReturnStmt *RS = nullptr;
308     if (!L.getSrc()->empty()) {
309       if (Optional<CFGStmt> LastStmt = L.getSrc()->back().getAs<CFGStmt>()) {
310         if ((RS = dyn_cast<ReturnStmt>(LastStmt->getStmt()))) {
311           if (!RS->getRetValue())
312             RS = nullptr;
313         }
314       }
315     }
316 
317     // Process the final state transition.
318     SubEng.processEndOfFunction(BuilderCtx, Pred, RS);
319 
320     // This path is done. Don't enqueue any more nodes.
321     return;
322   }
323 
324   // Call into the SubEngine to process entering the CFGBlock.
325   ExplodedNodeSet dstNodes;
326   BlockEntrance BE(Blk, Pred->getLocationContext());
327   NodeBuilderWithSinks nodeBuilder(Pred, dstNodes, BuilderCtx, BE);
328   SubEng.processCFGBlockEntrance(L, nodeBuilder, Pred);
329 
330   // Auto-generate a node.
331   if (!nodeBuilder.hasGeneratedNodes()) {
332     nodeBuilder.generateNode(Pred->State, Pred);
333   }
334 
335   // Enqueue nodes onto the worklist.
336   enqueue(dstNodes);
337 }
338 
339 void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
340                                        ExplodedNode *Pred) {
341 
342   // Increment the block counter.
343   const LocationContext *LC = Pred->getLocationContext();
344   unsigned BlockId = L.getBlock()->getBlockID();
345   BlockCounter Counter = WList->getBlockCounter();
346   Counter = BCounterFactory.IncrementCount(Counter, LC->getCurrentStackFrame(),
347                                            BlockId);
348   WList->setBlockCounter(Counter);
349 
350   // Process the entrance of the block.
351   if (Optional<CFGElement> E = L.getFirstElement()) {
352     NodeBuilderContext Ctx(*this, L.getBlock(), Pred);
353     SubEng.processCFGElement(*E, Pred, 0, &Ctx);
354   }
355   else
356     HandleBlockExit(L.getBlock(), Pred);
357 }
358 
359 void CoreEngine::HandleBlockExit(const CFGBlock * B, ExplodedNode *Pred) {
360 
361   if (const Stmt *Term = B->getTerminator()) {
362     switch (Term->getStmtClass()) {
363       default:
364         llvm_unreachable("Analysis for this terminator not implemented.");
365 
366       case Stmt::CXXBindTemporaryExprClass:
367         HandleCleanupTemporaryBranch(
368             cast<CXXBindTemporaryExpr>(B->getTerminator().getStmt()), B, Pred);
369         return;
370 
371       // Model static initializers.
372       case Stmt::DeclStmtClass:
373         HandleStaticInit(cast<DeclStmt>(Term), B, Pred);
374         return;
375 
376       case Stmt::BinaryOperatorClass: // '&&' and '||'
377         HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
378         return;
379 
380       case Stmt::BinaryConditionalOperatorClass:
381       case Stmt::ConditionalOperatorClass:
382         HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
383                      Term, B, Pred);
384         return;
385 
386         // FIXME: Use constant-folding in CFG construction to simplify this
387         // case.
388 
389       case Stmt::ChooseExprClass:
390         HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
391         return;
392 
393       case Stmt::CXXTryStmtClass: {
394         // Generate a node for each of the successors.
395         // Our logic for EH analysis can certainly be improved.
396         for (CFGBlock::const_succ_iterator it = B->succ_begin(),
397              et = B->succ_end(); it != et; ++it) {
398           if (const CFGBlock *succ = *it) {
399             generateNode(BlockEdge(B, succ, Pred->getLocationContext()),
400                          Pred->State, Pred);
401           }
402         }
403         return;
404       }
405 
406       case Stmt::DoStmtClass:
407         HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
408         return;
409 
410       case Stmt::CXXForRangeStmtClass:
411         HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
412         return;
413 
414       case Stmt::ForStmtClass:
415         HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
416         return;
417 
418       case Stmt::ContinueStmtClass:
419       case Stmt::BreakStmtClass:
420       case Stmt::GotoStmtClass:
421         break;
422 
423       case Stmt::IfStmtClass:
424         HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
425         return;
426 
427       case Stmt::IndirectGotoStmtClass: {
428         // Only 1 successor: the indirect goto dispatch block.
429         assert (B->succ_size() == 1);
430 
431         IndirectGotoNodeBuilder
432            builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
433                    *(B->succ_begin()), this);
434 
435         SubEng.processIndirectGoto(builder);
436         return;
437       }
438 
439       case Stmt::ObjCForCollectionStmtClass: {
440         // In the case of ObjCForCollectionStmt, it appears twice in a CFG:
441         //
442         //  (1) inside a basic block, which represents the binding of the
443         //      'element' variable to a value.
444         //  (2) in a terminator, which represents the branch.
445         //
446         // For (1), subengines will bind a value (i.e., 0 or 1) indicating
447         // whether or not collection contains any more elements.  We cannot
448         // just test to see if the element is nil because a container can
449         // contain nil elements.
450         HandleBranch(Term, Term, B, Pred);
451         return;
452       }
453 
454       case Stmt::SwitchStmtClass: {
455         SwitchNodeBuilder builder(Pred, B, cast<SwitchStmt>(Term)->getCond(),
456                                     this);
457 
458         SubEng.processSwitch(builder);
459         return;
460       }
461 
462       case Stmt::WhileStmtClass:
463         HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
464         return;
465     }
466   }
467 
468   assert (B->succ_size() == 1 &&
469           "Blocks with no terminator should have at most 1 successor.");
470 
471   generateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()),
472                Pred->State, Pred);
473 }
474 
475 void CoreEngine::HandleCallEnter(const CallEnter &CE, ExplodedNode *Pred) {
476   NodeBuilderContext BuilderCtx(*this, CE.getEntry(), Pred);
477   SubEng.processCallEnter(BuilderCtx, CE, Pred);
478 }
479 
480 void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,
481                                 const CFGBlock * B, ExplodedNode *Pred) {
482   assert(B->succ_size() == 2);
483   NodeBuilderContext Ctx(*this, B, Pred);
484   ExplodedNodeSet Dst;
485   SubEng.processBranch(Cond, Term, Ctx, Pred, Dst,
486                        *(B->succ_begin()), *(B->succ_begin()+1));
487   // Enqueue the new frontier onto the worklist.
488   enqueue(Dst);
489 }
490 
491 void CoreEngine::HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
492                                               const CFGBlock *B,
493                                               ExplodedNode *Pred) {
494   assert(B->succ_size() == 2);
495   NodeBuilderContext Ctx(*this, B, Pred);
496   ExplodedNodeSet Dst;
497   SubEng.processCleanupTemporaryBranch(BTE, Ctx, Pred, Dst, *(B->succ_begin()),
498                                        *(B->succ_begin() + 1));
499   // Enqueue the new frontier onto the worklist.
500   enqueue(Dst);
501 }
502 
503 void CoreEngine::HandleStaticInit(const DeclStmt *DS, const CFGBlock *B,
504                                   ExplodedNode *Pred) {
505   assert(B->succ_size() == 2);
506   NodeBuilderContext Ctx(*this, B, Pred);
507   ExplodedNodeSet Dst;
508   SubEng.processStaticInitializer(DS, Ctx, Pred, Dst,
509                                   *(B->succ_begin()), *(B->succ_begin()+1));
510   // Enqueue the new frontier onto the worklist.
511   enqueue(Dst);
512 }
513 
514 
515 void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,
516                                   ExplodedNode *Pred) {
517   assert(B);
518   assert(!B->empty());
519 
520   if (StmtIdx == B->size())
521     HandleBlockExit(B, Pred);
522   else {
523     NodeBuilderContext Ctx(*this, B, Pred);
524     SubEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx, &Ctx);
525   }
526 }
527 
528 /// generateNode - Utility method to generate nodes, hook up successors,
529 ///  and add nodes to the worklist.
530 void CoreEngine::generateNode(const ProgramPoint &Loc,
531                               ProgramStateRef State,
532                               ExplodedNode *Pred) {
533 
534   bool IsNew;
535   ExplodedNode *Node = G.getNode(Loc, State, false, &IsNew);
536 
537   if (Pred)
538     Node->addPredecessor(Pred, G); // Link 'Node' with its predecessor.
539   else {
540     assert (IsNew);
541     G.addRoot(Node); // 'Node' has no predecessor.  Make it a root.
542   }
543 
544   // Only add 'Node' to the worklist if it was freshly generated.
545   if (IsNew) WList->enqueue(Node);
546 }
547 
548 void CoreEngine::enqueueStmtNode(ExplodedNode *N,
549                                  const CFGBlock *Block, unsigned Idx) {
550   assert(Block);
551   assert (!N->isSink());
552 
553   // Check if this node entered a callee.
554   if (N->getLocation().getAs<CallEnter>()) {
555     // Still use the index of the CallExpr. It's needed to create the callee
556     // StackFrameContext.
557     WList->enqueue(N, Block, Idx);
558     return;
559   }
560 
561   // Do not create extra nodes. Move to the next CFG element.
562   if (N->getLocation().getAs<PostInitializer>() ||
563       N->getLocation().getAs<PostImplicitCall>()||
564       N->getLocation().getAs<LoopExit>()) {
565     WList->enqueue(N, Block, Idx+1);
566     return;
567   }
568 
569   if (N->getLocation().getAs<EpsilonPoint>()) {
570     WList->enqueue(N, Block, Idx);
571     return;
572   }
573 
574   if ((*Block)[Idx].getKind() == CFGElement::NewAllocator) {
575     WList->enqueue(N, Block, Idx+1);
576     return;
577   }
578 
579   // At this point, we know we're processing a normal statement.
580   CFGStmt CS = (*Block)[Idx].castAs<CFGStmt>();
581   PostStmt Loc(CS.getStmt(), N->getLocationContext());
582 
583   if (Loc == N->getLocation().withTag(nullptr)) {
584     // Note: 'N' should be a fresh node because otherwise it shouldn't be
585     // a member of Deferred.
586     WList->enqueue(N, Block, Idx+1);
587     return;
588   }
589 
590   bool IsNew;
591   ExplodedNode *Succ = G.getNode(Loc, N->getState(), false, &IsNew);
592   Succ->addPredecessor(N, G);
593 
594   if (IsNew)
595     WList->enqueue(Succ, Block, Idx+1);
596 }
597 
598 ExplodedNode *CoreEngine::generateCallExitBeginNode(ExplodedNode *N,
599                                                     const ReturnStmt *RS) {
600   // Create a CallExitBegin node and enqueue it.
601   const StackFrameContext *LocCtx
602                          = cast<StackFrameContext>(N->getLocationContext());
603 
604   // Use the callee location context.
605   CallExitBegin Loc(LocCtx, RS);
606 
607   bool isNew;
608   ExplodedNode *Node = G.getNode(Loc, N->getState(), false, &isNew);
609   Node->addPredecessor(N, G);
610   return isNew ? Node : nullptr;
611 }
612 
613 
614 void CoreEngine::enqueue(ExplodedNodeSet &Set) {
615   for (ExplodedNodeSet::iterator I = Set.begin(),
616                                  E = Set.end(); I != E; ++I) {
617     WList->enqueue(*I);
618   }
619 }
620 
621 void CoreEngine::enqueue(ExplodedNodeSet &Set,
622                          const CFGBlock *Block, unsigned Idx) {
623   for (ExplodedNodeSet::iterator I = Set.begin(),
624                                  E = Set.end(); I != E; ++I) {
625     enqueueStmtNode(*I, Block, Idx);
626   }
627 }
628 
629 void CoreEngine::enqueueEndOfFunction(ExplodedNodeSet &Set, const ReturnStmt *RS) {
630   for (ExplodedNodeSet::iterator I = Set.begin(), E = Set.end(); I != E; ++I) {
631     ExplodedNode *N = *I;
632     // If we are in an inlined call, generate CallExitBegin node.
633     if (N->getLocationContext()->getParent()) {
634       N = generateCallExitBeginNode(N, RS);
635       if (N)
636         WList->enqueue(N);
637     } else {
638       // TODO: We should run remove dead bindings here.
639       G.addEndOfPath(N);
640       NumPathsExplored++;
641     }
642   }
643 }
644 
645 
646 void NodeBuilder::anchor() { }
647 
648 ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
649                                             ProgramStateRef State,
650                                             ExplodedNode *FromN,
651                                             bool MarkAsSink) {
652   HasGeneratedNodes = true;
653   bool IsNew;
654   ExplodedNode *N = C.Eng.G.getNode(Loc, State, MarkAsSink, &IsNew);
655   N->addPredecessor(FromN, C.Eng.G);
656   Frontier.erase(FromN);
657 
658   if (!IsNew)
659     return nullptr;
660 
661   if (!MarkAsSink)
662     Frontier.Add(N);
663 
664   return N;
665 }
666 
667 void NodeBuilderWithSinks::anchor() { }
668 
669 StmtNodeBuilder::~StmtNodeBuilder() {
670   if (EnclosingBldr)
671     for (ExplodedNodeSet::iterator I = Frontier.begin(),
672                                    E = Frontier.end(); I != E; ++I )
673       EnclosingBldr->addNodes(*I);
674 }
675 
676 void BranchNodeBuilder::anchor() { }
677 
678 ExplodedNode *BranchNodeBuilder::generateNode(ProgramStateRef State,
679                                               bool branch,
680                                               ExplodedNode *NodePred) {
681   // If the branch has been marked infeasible we should not generate a node.
682   if (!isFeasible(branch))
683     return nullptr;
684 
685   ProgramPoint Loc = BlockEdge(C.Block, branch ? DstT:DstF,
686                                NodePred->getLocationContext());
687   ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
688   return Succ;
689 }
690 
691 ExplodedNode*
692 IndirectGotoNodeBuilder::generateNode(const iterator &I,
693                                       ProgramStateRef St,
694                                       bool IsSink) {
695   bool IsNew;
696   ExplodedNode *Succ =
697       Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
698                     St, IsSink, &IsNew);
699   Succ->addPredecessor(Pred, Eng.G);
700 
701   if (!IsNew)
702     return nullptr;
703 
704   if (!IsSink)
705     Eng.WList->enqueue(Succ);
706 
707   return Succ;
708 }
709 
710 
711 ExplodedNode*
712 SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
713                                         ProgramStateRef St) {
714 
715   bool IsNew;
716   ExplodedNode *Succ =
717       Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
718                     St, false, &IsNew);
719   Succ->addPredecessor(Pred, Eng.G);
720   if (!IsNew)
721     return nullptr;
722 
723   Eng.WList->enqueue(Succ);
724   return Succ;
725 }
726 
727 
728 ExplodedNode*
729 SwitchNodeBuilder::generateDefaultCaseNode(ProgramStateRef St,
730                                            bool IsSink) {
731   // Get the block for the default case.
732   assert(Src->succ_rbegin() != Src->succ_rend());
733   CFGBlock *DefaultBlock = *Src->succ_rbegin();
734 
735   // Sanity check for default blocks that are unreachable and not caught
736   // by earlier stages.
737   if (!DefaultBlock)
738     return nullptr;
739 
740   bool IsNew;
741   ExplodedNode *Succ =
742       Eng.G.getNode(BlockEdge(Src, DefaultBlock, Pred->getLocationContext()),
743                     St, IsSink, &IsNew);
744   Succ->addPredecessor(Pred, Eng.G);
745 
746   if (!IsNew)
747     return nullptr;
748 
749   if (!IsSink)
750     Eng.WList->enqueue(Succ);
751 
752   return Succ;
753 }
754