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         RS = dyn_cast<ReturnStmt>(LastStmt->getStmt());
311       }
312     }
313 
314     // Process the final state transition.
315     SubEng.processEndOfFunction(BuilderCtx, Pred, RS);
316 
317     // This path is done. Don't enqueue any more nodes.
318     return;
319   }
320 
321   // Call into the SubEngine to process entering the CFGBlock.
322   ExplodedNodeSet dstNodes;
323   BlockEntrance BE(Blk, Pred->getLocationContext());
324   NodeBuilderWithSinks nodeBuilder(Pred, dstNodes, BuilderCtx, BE);
325   SubEng.processCFGBlockEntrance(L, nodeBuilder, Pred);
326 
327   // Auto-generate a node.
328   if (!nodeBuilder.hasGeneratedNodes()) {
329     nodeBuilder.generateNode(Pred->State, Pred);
330   }
331 
332   // Enqueue nodes onto the worklist.
333   enqueue(dstNodes);
334 }
335 
336 void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
337                                        ExplodedNode *Pred) {
338 
339   // Increment the block counter.
340   const LocationContext *LC = Pred->getLocationContext();
341   unsigned BlockId = L.getBlock()->getBlockID();
342   BlockCounter Counter = WList->getBlockCounter();
343   Counter = BCounterFactory.IncrementCount(Counter, LC->getCurrentStackFrame(),
344                                            BlockId);
345   WList->setBlockCounter(Counter);
346 
347   // Process the entrance of the block.
348   if (Optional<CFGElement> E = L.getFirstElement()) {
349     NodeBuilderContext Ctx(*this, L.getBlock(), Pred);
350     SubEng.processCFGElement(*E, Pred, 0, &Ctx);
351   }
352   else
353     HandleBlockExit(L.getBlock(), Pred);
354 }
355 
356 void CoreEngine::HandleBlockExit(const CFGBlock * B, ExplodedNode *Pred) {
357 
358   if (const Stmt *Term = B->getTerminator()) {
359     switch (Term->getStmtClass()) {
360       default:
361         llvm_unreachable("Analysis for this terminator not implemented.");
362 
363       case Stmt::CXXBindTemporaryExprClass:
364         HandleCleanupTemporaryBranch(
365             cast<CXXBindTemporaryExpr>(B->getTerminator().getStmt()), B, Pred);
366         return;
367 
368       // Model static initializers.
369       case Stmt::DeclStmtClass:
370         HandleStaticInit(cast<DeclStmt>(Term), B, Pred);
371         return;
372 
373       case Stmt::BinaryOperatorClass: // '&&' and '||'
374         HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
375         return;
376 
377       case Stmt::BinaryConditionalOperatorClass:
378       case Stmt::ConditionalOperatorClass:
379         HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
380                      Term, B, Pred);
381         return;
382 
383         // FIXME: Use constant-folding in CFG construction to simplify this
384         // case.
385 
386       case Stmt::ChooseExprClass:
387         HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
388         return;
389 
390       case Stmt::CXXTryStmtClass: {
391         // Generate a node for each of the successors.
392         // Our logic for EH analysis can certainly be improved.
393         for (CFGBlock::const_succ_iterator it = B->succ_begin(),
394              et = B->succ_end(); it != et; ++it) {
395           if (const CFGBlock *succ = *it) {
396             generateNode(BlockEdge(B, succ, Pred->getLocationContext()),
397                          Pred->State, Pred);
398           }
399         }
400         return;
401       }
402 
403       case Stmt::DoStmtClass:
404         HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
405         return;
406 
407       case Stmt::CXXForRangeStmtClass:
408         HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
409         return;
410 
411       case Stmt::ForStmtClass:
412         HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
413         return;
414 
415       case Stmt::ContinueStmtClass:
416       case Stmt::BreakStmtClass:
417       case Stmt::GotoStmtClass:
418         break;
419 
420       case Stmt::IfStmtClass:
421         HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
422         return;
423 
424       case Stmt::IndirectGotoStmtClass: {
425         // Only 1 successor: the indirect goto dispatch block.
426         assert (B->succ_size() == 1);
427 
428         IndirectGotoNodeBuilder
429            builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
430                    *(B->succ_begin()), this);
431 
432         SubEng.processIndirectGoto(builder);
433         return;
434       }
435 
436       case Stmt::ObjCForCollectionStmtClass: {
437         // In the case of ObjCForCollectionStmt, it appears twice in a CFG:
438         //
439         //  (1) inside a basic block, which represents the binding of the
440         //      'element' variable to a value.
441         //  (2) in a terminator, which represents the branch.
442         //
443         // For (1), subengines will bind a value (i.e., 0 or 1) indicating
444         // whether or not collection contains any more elements.  We cannot
445         // just test to see if the element is nil because a container can
446         // contain nil elements.
447         HandleBranch(Term, Term, B, Pred);
448         return;
449       }
450 
451       case Stmt::SwitchStmtClass: {
452         SwitchNodeBuilder builder(Pred, B, cast<SwitchStmt>(Term)->getCond(),
453                                     this);
454 
455         SubEng.processSwitch(builder);
456         return;
457       }
458 
459       case Stmt::WhileStmtClass:
460         HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
461         return;
462     }
463   }
464 
465   assert (B->succ_size() == 1 &&
466           "Blocks with no terminator should have at most 1 successor.");
467 
468   generateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()),
469                Pred->State, Pred);
470 }
471 
472 void CoreEngine::HandleCallEnter(const CallEnter &CE, ExplodedNode *Pred) {
473   NodeBuilderContext BuilderCtx(*this, CE.getEntry(), Pred);
474   SubEng.processCallEnter(BuilderCtx, CE, Pred);
475 }
476 
477 void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,
478                                 const CFGBlock * B, ExplodedNode *Pred) {
479   assert(B->succ_size() == 2);
480   NodeBuilderContext Ctx(*this, B, Pred);
481   ExplodedNodeSet Dst;
482   SubEng.processBranch(Cond, Term, Ctx, Pred, Dst,
483                        *(B->succ_begin()), *(B->succ_begin()+1));
484   // Enqueue the new frontier onto the worklist.
485   enqueue(Dst);
486 }
487 
488 void CoreEngine::HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
489                                               const CFGBlock *B,
490                                               ExplodedNode *Pred) {
491   assert(B->succ_size() == 2);
492   NodeBuilderContext Ctx(*this, B, Pred);
493   ExplodedNodeSet Dst;
494   SubEng.processCleanupTemporaryBranch(BTE, Ctx, Pred, Dst, *(B->succ_begin()),
495                                        *(B->succ_begin() + 1));
496   // Enqueue the new frontier onto the worklist.
497   enqueue(Dst);
498 }
499 
500 void CoreEngine::HandleStaticInit(const DeclStmt *DS, const CFGBlock *B,
501                                   ExplodedNode *Pred) {
502   assert(B->succ_size() == 2);
503   NodeBuilderContext Ctx(*this, B, Pred);
504   ExplodedNodeSet Dst;
505   SubEng.processStaticInitializer(DS, Ctx, Pred, Dst,
506                                   *(B->succ_begin()), *(B->succ_begin()+1));
507   // Enqueue the new frontier onto the worklist.
508   enqueue(Dst);
509 }
510 
511 
512 void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,
513                                   ExplodedNode *Pred) {
514   assert(B);
515   assert(!B->empty());
516 
517   if (StmtIdx == B->size())
518     HandleBlockExit(B, Pred);
519   else {
520     NodeBuilderContext Ctx(*this, B, Pred);
521     SubEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx, &Ctx);
522   }
523 }
524 
525 /// generateNode - Utility method to generate nodes, hook up successors,
526 ///  and add nodes to the worklist.
527 void CoreEngine::generateNode(const ProgramPoint &Loc,
528                               ProgramStateRef State,
529                               ExplodedNode *Pred) {
530 
531   bool IsNew;
532   ExplodedNode *Node = G.getNode(Loc, State, false, &IsNew);
533 
534   if (Pred)
535     Node->addPredecessor(Pred, G); // Link 'Node' with its predecessor.
536   else {
537     assert (IsNew);
538     G.addRoot(Node); // 'Node' has no predecessor.  Make it a root.
539   }
540 
541   // Only add 'Node' to the worklist if it was freshly generated.
542   if (IsNew) WList->enqueue(Node);
543 }
544 
545 void CoreEngine::enqueueStmtNode(ExplodedNode *N,
546                                  const CFGBlock *Block, unsigned Idx) {
547   assert(Block);
548   assert (!N->isSink());
549 
550   // Check if this node entered a callee.
551   if (N->getLocation().getAs<CallEnter>()) {
552     // Still use the index of the CallExpr. It's needed to create the callee
553     // StackFrameContext.
554     WList->enqueue(N, Block, Idx);
555     return;
556   }
557 
558   // Do not create extra nodes. Move to the next CFG element.
559   if (N->getLocation().getAs<PostInitializer>() ||
560       N->getLocation().getAs<PostImplicitCall>()||
561       N->getLocation().getAs<LoopExit>()) {
562     WList->enqueue(N, Block, Idx+1);
563     return;
564   }
565 
566   if (N->getLocation().getAs<EpsilonPoint>()) {
567     WList->enqueue(N, Block, Idx);
568     return;
569   }
570 
571   if ((*Block)[Idx].getKind() == CFGElement::NewAllocator) {
572     WList->enqueue(N, Block, Idx+1);
573     return;
574   }
575 
576   // At this point, we know we're processing a normal statement.
577   CFGStmt CS = (*Block)[Idx].castAs<CFGStmt>();
578   PostStmt Loc(CS.getStmt(), N->getLocationContext());
579 
580   if (Loc == N->getLocation().withTag(nullptr)) {
581     // Note: 'N' should be a fresh node because otherwise it shouldn't be
582     // a member of Deferred.
583     WList->enqueue(N, Block, Idx+1);
584     return;
585   }
586 
587   bool IsNew;
588   ExplodedNode *Succ = G.getNode(Loc, N->getState(), false, &IsNew);
589   Succ->addPredecessor(N, G);
590 
591   if (IsNew)
592     WList->enqueue(Succ, Block, Idx+1);
593 }
594 
595 ExplodedNode *CoreEngine::generateCallExitBeginNode(ExplodedNode *N,
596                                                     const ReturnStmt *RS) {
597   // Create a CallExitBegin node and enqueue it.
598   const StackFrameContext *LocCtx
599                          = cast<StackFrameContext>(N->getLocationContext());
600 
601   // Use the callee location context.
602   CallExitBegin Loc(LocCtx, RS);
603 
604   bool isNew;
605   ExplodedNode *Node = G.getNode(Loc, N->getState(), false, &isNew);
606   Node->addPredecessor(N, G);
607   return isNew ? Node : nullptr;
608 }
609 
610 
611 void CoreEngine::enqueue(ExplodedNodeSet &Set) {
612   for (ExplodedNodeSet::iterator I = Set.begin(),
613                                  E = Set.end(); I != E; ++I) {
614     WList->enqueue(*I);
615   }
616 }
617 
618 void CoreEngine::enqueue(ExplodedNodeSet &Set,
619                          const CFGBlock *Block, unsigned Idx) {
620   for (ExplodedNodeSet::iterator I = Set.begin(),
621                                  E = Set.end(); I != E; ++I) {
622     enqueueStmtNode(*I, Block, Idx);
623   }
624 }
625 
626 void CoreEngine::enqueueEndOfFunction(ExplodedNodeSet &Set, const ReturnStmt *RS) {
627   for (ExplodedNodeSet::iterator I = Set.begin(), E = Set.end(); I != E; ++I) {
628     ExplodedNode *N = *I;
629     // If we are in an inlined call, generate CallExitBegin node.
630     if (N->getLocationContext()->getParent()) {
631       N = generateCallExitBeginNode(N, RS);
632       if (N)
633         WList->enqueue(N);
634     } else {
635       // TODO: We should run remove dead bindings here.
636       G.addEndOfPath(N);
637       NumPathsExplored++;
638     }
639   }
640 }
641 
642 
643 void NodeBuilder::anchor() { }
644 
645 ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
646                                             ProgramStateRef State,
647                                             ExplodedNode *FromN,
648                                             bool MarkAsSink) {
649   HasGeneratedNodes = true;
650   bool IsNew;
651   ExplodedNode *N = C.Eng.G.getNode(Loc, State, MarkAsSink, &IsNew);
652   N->addPredecessor(FromN, C.Eng.G);
653   Frontier.erase(FromN);
654 
655   if (!IsNew)
656     return nullptr;
657 
658   if (!MarkAsSink)
659     Frontier.Add(N);
660 
661   return N;
662 }
663 
664 void NodeBuilderWithSinks::anchor() { }
665 
666 StmtNodeBuilder::~StmtNodeBuilder() {
667   if (EnclosingBldr)
668     for (ExplodedNodeSet::iterator I = Frontier.begin(),
669                                    E = Frontier.end(); I != E; ++I )
670       EnclosingBldr->addNodes(*I);
671 }
672 
673 void BranchNodeBuilder::anchor() { }
674 
675 ExplodedNode *BranchNodeBuilder::generateNode(ProgramStateRef State,
676                                               bool branch,
677                                               ExplodedNode *NodePred) {
678   // If the branch has been marked infeasible we should not generate a node.
679   if (!isFeasible(branch))
680     return nullptr;
681 
682   ProgramPoint Loc = BlockEdge(C.Block, branch ? DstT:DstF,
683                                NodePred->getLocationContext());
684   ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
685   return Succ;
686 }
687 
688 ExplodedNode*
689 IndirectGotoNodeBuilder::generateNode(const iterator &I,
690                                       ProgramStateRef St,
691                                       bool IsSink) {
692   bool IsNew;
693   ExplodedNode *Succ =
694       Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
695                     St, IsSink, &IsNew);
696   Succ->addPredecessor(Pred, Eng.G);
697 
698   if (!IsNew)
699     return nullptr;
700 
701   if (!IsSink)
702     Eng.WList->enqueue(Succ);
703 
704   return Succ;
705 }
706 
707 
708 ExplodedNode*
709 SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
710                                         ProgramStateRef St) {
711 
712   bool IsNew;
713   ExplodedNode *Succ =
714       Eng.G.getNode(BlockEdge(Src, I.getBlock(), Pred->getLocationContext()),
715                     St, false, &IsNew);
716   Succ->addPredecessor(Pred, Eng.G);
717   if (!IsNew)
718     return nullptr;
719 
720   Eng.WList->enqueue(Succ);
721   return Succ;
722 }
723 
724 
725 ExplodedNode*
726 SwitchNodeBuilder::generateDefaultCaseNode(ProgramStateRef St,
727                                            bool IsSink) {
728   // Get the block for the default case.
729   assert(Src->succ_rbegin() != Src->succ_rend());
730   CFGBlock *DefaultBlock = *Src->succ_rbegin();
731 
732   // Sanity check for default blocks that are unreachable and not caught
733   // by earlier stages.
734   if (!DefaultBlock)
735     return nullptr;
736 
737   bool IsNew;
738   ExplodedNode *Succ =
739       Eng.G.getNode(BlockEdge(Src, DefaultBlock, Pred->getLocationContext()),
740                     St, IsSink, &IsNew);
741   Succ->addPredecessor(Pred, Eng.G);
742 
743   if (!IsNew)
744     return nullptr;
745 
746   if (!IsSink)
747     Eng.WList->enqueue(Succ);
748 
749   return Succ;
750 }
751