1e580d831SEugene Zelenko //===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
2fa0734ecSArgyrios Kyrtzidis //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fa0734ecSArgyrios Kyrtzidis //
7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
8fa0734ecSArgyrios Kyrtzidis //
9fa0734ecSArgyrios Kyrtzidis //  This file defines the template classes ExplodedNode and ExplodedGraph,
10fa0734ecSArgyrios Kyrtzidis //  which represent a path-sensitive, intra-procedural "exploded graph."
11fa0734ecSArgyrios Kyrtzidis //
12fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
13fa0734ecSArgyrios Kyrtzidis 
14f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
15e580d831SEugene Zelenko #include "clang/AST/Expr.h"
16e580d831SEugene Zelenko #include "clang/AST/ExprObjC.h"
173a02247dSChandler Carruth #include "clang/AST/ParentMap.h"
183a02247dSChandler Carruth #include "clang/AST/Stmt.h"
19*dd53bdbfSKristof Umann #include "clang/Analysis/CFGStmtMap.h"
20e580d831SEugene Zelenko #include "clang/Analysis/ProgramPoint.h"
21e580d831SEugene Zelenko #include "clang/Analysis/Support/BumpVector.h"
22e580d831SEugene Zelenko #include "clang/Basic/LLVM.h"
234f7df9beSJordan Rose #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25e580d831SEugene Zelenko #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
263a02247dSChandler Carruth #include "llvm/ADT/DenseSet.h"
27e580d831SEugene Zelenko #include "llvm/ADT/FoldingSet.h"
28e580d831SEugene Zelenko #include "llvm/ADT/Optional.h"
29e580d831SEugene Zelenko #include "llvm/ADT/PointerUnion.h"
30fa0734ecSArgyrios Kyrtzidis #include "llvm/ADT/SmallVector.h"
31e580d831SEugene Zelenko #include "llvm/Support/Casting.h"
32e580d831SEugene Zelenko #include <cassert>
33e580d831SEugene Zelenko #include <memory>
34fa0734ecSArgyrios Kyrtzidis 
35fa0734ecSArgyrios Kyrtzidis using namespace clang;
36fa0734ecSArgyrios Kyrtzidis using namespace ento;
37fa0734ecSArgyrios Kyrtzidis 
38fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
39a40f8ebcSTed Kremenek // Cleanup.
40a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
41a40f8ebcSTed Kremenek 
42e580d831SEugene Zelenko ExplodedGraph::ExplodedGraph() = default;
4344d2973bSTed Kremenek 
44e580d831SEugene Zelenko ExplodedGraph::~ExplodedGraph() = default;
45a40f8ebcSTed Kremenek 
46a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
47a40f8ebcSTed Kremenek // Node reclamation.
48a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
49a40f8ebcSTed Kremenek 
5004fa9e3dSTed Kremenek bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
5104fa9e3dSTed Kremenek   if (!Ex->isLValue())
5204fa9e3dSTed Kremenek     return false;
5304fa9e3dSTed Kremenek   return isa<DeclRefExpr>(Ex) ||
5404fa9e3dSTed Kremenek          isa<MemberExpr>(Ex) ||
5504fa9e3dSTed Kremenek          isa<ObjCIvarRefExpr>(Ex);
5604fa9e3dSTed Kremenek }
5704fa9e3dSTed Kremenek 
581dd7fd71STed Kremenek bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
598f564058STed Kremenek   // First, we only consider nodes for reclamation of the following
608f564058STed Kremenek   // conditions apply:
611dd7fd71STed Kremenek   //
621dd7fd71STed Kremenek   // (1) 1 predecessor (that has one successor)
631dd7fd71STed Kremenek   // (2) 1 successor (that has one predecessor)
648f564058STed Kremenek   //
658f564058STed Kremenek   // If a node has no successor it is on the "frontier", while a node
668f564058STed Kremenek   // with no predecessor is a root.
678f564058STed Kremenek   //
688f564058STed Kremenek   // After these prerequisites, we discard all "filler" nodes that
698f564058STed Kremenek   // are used only for intermediate processing, and are not essential
708f564058STed Kremenek   // for analyzer history:
718f564058STed Kremenek   //
728f564058STed Kremenek   // (a) PreStmtPurgeDeadSymbols
738f564058STed Kremenek   //
748f564058STed Kremenek   // We then discard all other nodes where *all* of the following conditions
758f564058STed Kremenek   // apply:
768f564058STed Kremenek   //
77199fdd82SJordan Rose   // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
781dd7fd71STed Kremenek   // (4) There is no 'tag' for the ProgramPoint.
791dd7fd71STed Kremenek   // (5) The 'store' is the same as the predecessor.
801dd7fd71STed Kremenek   // (6) The 'GDM' is the same as the predecessor.
811dd7fd71STed Kremenek   // (7) The LocationContext is the same as the predecessor.
8296250482STed Kremenek   // (8) Expressions that are *not* lvalue expressions.
8396250482STed Kremenek   // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
8468a172caSAnton Yartsev   // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
8568a172caSAnton Yartsev   //      PreImplicitCall (so that we would be able to find it when retrying a
8668a172caSAnton Yartsev   //      call with no inlining).
87681cce99SJordan Rose   // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
881dd7fd71STed Kremenek 
891dd7fd71STed Kremenek   // Conditions 1 and 2.
901dd7fd71STed Kremenek   if (node->pred_size() != 1 || node->succ_size() != 1)
911dd7fd71STed Kremenek     return false;
921dd7fd71STed Kremenek 
931dd7fd71STed Kremenek   const ExplodedNode *pred = *(node->pred_begin());
941dd7fd71STed Kremenek   if (pred->succ_size() != 1)
951dd7fd71STed Kremenek     return false;
961dd7fd71STed Kremenek 
971dd7fd71STed Kremenek   const ExplodedNode *succ = *(node->succ_begin());
981dd7fd71STed Kremenek   if (succ->pred_size() != 1)
991dd7fd71STed Kremenek     return false;
1001dd7fd71STed Kremenek 
1018f564058STed Kremenek   // Now reclaim any nodes that are (by definition) not essential to
1028f564058STed Kremenek   // analysis history and are not consulted by any client code.
1031dd7fd71STed Kremenek   ProgramPoint progPoint = node->getLocation();
1048f564058STed Kremenek   if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
105f352d8c7STed Kremenek     return !progPoint.getTag();
1068f564058STed Kremenek 
1078f564058STed Kremenek   // Condition 3.
10887396b9bSDavid Blaikie   if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
1091dd7fd71STed Kremenek     return false;
1101dd7fd71STed Kremenek 
1111dd7fd71STed Kremenek   // Condition 4.
11254417f6dSAnna Zaks   if (progPoint.getTag())
1131dd7fd71STed Kremenek     return false;
1141dd7fd71STed Kremenek 
1151dd7fd71STed Kremenek   // Conditions 5, 6, and 7.
1161dd7fd71STed Kremenek   ProgramStateRef state = node->getState();
1171dd7fd71STed Kremenek   ProgramStateRef pred_state = pred->getState();
1181dd7fd71STed Kremenek   if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
1191dd7fd71STed Kremenek       progPoint.getLocationContext() != pred->getLocationContext())
1201dd7fd71STed Kremenek     return false;
1211dd7fd71STed Kremenek 
12254417f6dSAnna Zaks   // All further checks require expressions. As per #3, we know that we have
12354417f6dSAnna Zaks   // a PostStmt.
12454417f6dSAnna Zaks   const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
12504fa9e3dSTed Kremenek   if (!Ex)
12604fa9e3dSTed Kremenek     return false;
12704fa9e3dSTed Kremenek 
12804fa9e3dSTed Kremenek   // Condition 8.
12904fa9e3dSTed Kremenek   // Do not collect nodes for "interesting" lvalue expressions since they are
13004fa9e3dSTed Kremenek   // used extensively for generating path diagnostics.
13104fa9e3dSTed Kremenek   if (isInterestingLValueExpr(Ex))
13296250482STed Kremenek     return false;
13396250482STed Kremenek 
13496250482STed Kremenek   // Condition 9.
13567e0062bSAnna Zaks   // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
13667e0062bSAnna Zaks   // diagnostic generation; specifically, so that we could anchor arrows
13767e0062bSAnna Zaks   // pointing to the beginning of statements (as written in code).
138fc76d855SKristof Umann   const ParentMap &PM = progPoint.getLocationContext()->getParentMap();
1391dd7fd71STed Kremenek   if (!PM.isConsumedExpr(Ex))
1401dd7fd71STed Kremenek     return false;
1411dd7fd71STed Kremenek 
14296250482STed Kremenek   // Condition 10.
143bec49efdSAnna Zaks   const ProgramPoint SuccLoc = succ->getLocation();
14487396b9bSDavid Blaikie   if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
145e537cc05SJordan Rose     if (CallEvent::isCallStmt(SP->getStmt()))
146bec49efdSAnna Zaks       return false;
147bec49efdSAnna Zaks 
14868a172caSAnton Yartsev   // Condition 10, continuation.
14968a172caSAnton Yartsev   if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
15068a172caSAnton Yartsev     return false;
15168a172caSAnton Yartsev 
1521dd7fd71STed Kremenek   return true;
1531dd7fd71STed Kremenek }
1541dd7fd71STed Kremenek 
1551dd7fd71STed Kremenek void ExplodedGraph::collectNode(ExplodedNode *node) {
1561dd7fd71STed Kremenek   // Removing a node means:
1571dd7fd71STed Kremenek   // (a) changing the predecessors successor to the successor of this node
1581dd7fd71STed Kremenek   // (b) changing the successors predecessor to the predecessor of this node
1591dd7fd71STed Kremenek   // (c) Putting 'node' onto freeNodes.
1601dd7fd71STed Kremenek   assert(node->pred_size() == 1 || node->succ_size() == 1);
1611dd7fd71STed Kremenek   ExplodedNode *pred = *(node->pred_begin());
1621dd7fd71STed Kremenek   ExplodedNode *succ = *(node->succ_begin());
1631dd7fd71STed Kremenek   pred->replaceSuccessor(succ);
1641dd7fd71STed Kremenek   succ->replacePredecessor(pred);
165a2aa929eSTed Kremenek   FreeNodes.push_back(node);
1661dd7fd71STed Kremenek   Nodes.RemoveNode(node);
1671dd7fd71STed Kremenek   --NumNodes;
1681dd7fd71STed Kremenek   node->~ExplodedNode();
1691dd7fd71STed Kremenek }
1701dd7fd71STed Kremenek 
17135e55fe4STed Kremenek void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
172a2aa929eSTed Kremenek   if (ChangedNodes.empty())
173a40f8ebcSTed Kremenek     return;
17444d2973bSTed Kremenek 
175746c06d0SJordan Rose   // Only periodically reclaim nodes so that we can build up a set of
17635e55fe4STed Kremenek   // nodes that meet the reclamation criteria.  Freshly created nodes
17735e55fe4STed Kremenek   // by definition have no successor, and thus cannot be reclaimed (see below).
178746c06d0SJordan Rose   assert(ReclaimCounter > 0);
179746c06d0SJordan Rose   if (--ReclaimCounter != 0)
18035e55fe4STed Kremenek     return;
181746c06d0SJordan Rose   ReclaimCounter = ReclaimNodeInterval;
18235e55fe4STed Kremenek 
183e580d831SEugene Zelenko   for (const auto node : ChangedNodes)
1841dd7fd71STed Kremenek     if (shouldCollect(node))
1851dd7fd71STed Kremenek       collectNode(node);
186a2aa929eSTed Kremenek   ChangedNodes.clear();
187a40f8ebcSTed Kremenek }
188a40f8ebcSTed Kremenek 
189a40f8ebcSTed Kremenek //===----------------------------------------------------------------------===//
190fa0734ecSArgyrios Kyrtzidis // ExplodedNode.
191fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
192fa0734ecSArgyrios Kyrtzidis 
1932b10f3f8SJordan Rose // An NodeGroup's storage type is actually very much like a TinyPtrVector:
1942b10f3f8SJordan Rose // it can be either a pointer to a single ExplodedNode, or a pointer to a
1952b10f3f8SJordan Rose // BumpVector allocated with the ExplodedGraph's allocator. This allows the
1962b10f3f8SJordan Rose // common case of single-node NodeGroups to be implemented with no extra memory.
1972b10f3f8SJordan Rose //
1982b10f3f8SJordan Rose // Consequently, each of the NodeGroup methods have up to four cases to handle:
1992b10f3f8SJordan Rose // 1. The flag is set and this group does not actually contain any nodes.
2002b10f3f8SJordan Rose // 2. The group is empty, in which case the storage value is null.
2012b10f3f8SJordan Rose // 3. The group contains a single node.
2022b10f3f8SJordan Rose // 4. The group contains more than one node.
203e580d831SEugene Zelenko using ExplodedNodeVector = BumpVector<ExplodedNode *>;
204e580d831SEugene Zelenko using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
205fa0734ecSArgyrios Kyrtzidis 
206fa0734ecSArgyrios Kyrtzidis void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
207fa0734ecSArgyrios Kyrtzidis   assert(!V->isSink());
208fa0734ecSArgyrios Kyrtzidis   Preds.addNode(V, G);
209fa0734ecSArgyrios Kyrtzidis   V->Succs.addNode(this, G);
210fa0734ecSArgyrios Kyrtzidis }
211fa0734ecSArgyrios Kyrtzidis 
212a40f8ebcSTed Kremenek void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
2132b10f3f8SJordan Rose   assert(!getFlag());
2142b10f3f8SJordan Rose 
21580547386SJordan Rose   GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
21680547386SJordan Rose   assert(Storage.is<ExplodedNode *>());
21780547386SJordan Rose   Storage = node;
21880547386SJordan Rose   assert(Storage.is<ExplodedNode *>());
219a40f8ebcSTed Kremenek }
220a40f8ebcSTed Kremenek 
221fa0734ecSArgyrios Kyrtzidis void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
222fa0734ecSArgyrios Kyrtzidis   assert(!getFlag());
223fa0734ecSArgyrios Kyrtzidis 
22480547386SJordan Rose   GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
22580547386SJordan Rose   if (Storage.isNull()) {
22680547386SJordan Rose     Storage = N;
22780547386SJordan Rose     assert(Storage.is<ExplodedNode *>());
22880547386SJordan Rose     return;
22980547386SJordan Rose   }
230fa0734ecSArgyrios Kyrtzidis 
23180547386SJordan Rose   ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
23280547386SJordan Rose 
23380547386SJordan Rose   if (!V) {
23480547386SJordan Rose     // Switch from single-node to multi-node representation.
23580547386SJordan Rose     ExplodedNode *Old = Storage.get<ExplodedNode *>();
23680547386SJordan Rose 
23780547386SJordan Rose     BumpVectorContext &Ctx = G.getNodeAllocator();
23880547386SJordan Rose     V = G.getAllocator().Allocate<ExplodedNodeVector>();
23980547386SJordan Rose     new (V) ExplodedNodeVector(Ctx, 4);
24080547386SJordan Rose     V->push_back(Old, Ctx);
24180547386SJordan Rose 
24280547386SJordan Rose     Storage = V;
24380547386SJordan Rose     assert(!getFlag());
24480547386SJordan Rose     assert(Storage.is<ExplodedNodeVector *>());
245fa0734ecSArgyrios Kyrtzidis   }
24680547386SJordan Rose 
24780547386SJordan Rose   V->push_back(N, G.getNodeAllocator());
248fa0734ecSArgyrios Kyrtzidis }
249fa0734ecSArgyrios Kyrtzidis 
250fa0734ecSArgyrios Kyrtzidis unsigned ExplodedNode::NodeGroup::size() const {
251fa0734ecSArgyrios Kyrtzidis   if (getFlag())
252fa0734ecSArgyrios Kyrtzidis     return 0;
253fa0734ecSArgyrios Kyrtzidis 
25480547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
25580547386SJordan Rose   if (Storage.isNull())
25680547386SJordan Rose     return 0;
25780547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
25880547386SJordan Rose     return V->size();
25980547386SJordan Rose   return 1;
260fa0734ecSArgyrios Kyrtzidis }
261fa0734ecSArgyrios Kyrtzidis 
26280547386SJordan Rose ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
263fa0734ecSArgyrios Kyrtzidis   if (getFlag())
2640dbb783cSCraig Topper     return nullptr;
265fa0734ecSArgyrios Kyrtzidis 
26680547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
26780547386SJordan Rose   if (Storage.isNull())
2680dbb783cSCraig Topper     return nullptr;
26980547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
27080547386SJordan Rose     return V->begin();
27180547386SJordan Rose   return Storage.getAddrOfPtr1();
272fa0734ecSArgyrios Kyrtzidis }
273fa0734ecSArgyrios Kyrtzidis 
27480547386SJordan Rose ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
275fa0734ecSArgyrios Kyrtzidis   if (getFlag())
2760dbb783cSCraig Topper     return nullptr;
277fa0734ecSArgyrios Kyrtzidis 
27880547386SJordan Rose   const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
27980547386SJordan Rose   if (Storage.isNull())
2800dbb783cSCraig Topper     return nullptr;
28180547386SJordan Rose   if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
28280547386SJordan Rose     return V->end();
28380547386SJordan Rose   return Storage.getAddrOfPtr1() + 1;
284fa0734ecSArgyrios Kyrtzidis }
285fa0734ecSArgyrios Kyrtzidis 
28684a2b30bSGeorge Karpenkov int64_t ExplodedNode::getID(ExplodedGraph *G) const {
287057647d8SArtem Dergachev   return G->getAllocator().identifyKnownAlignedObject<ExplodedNode>(this);
28884a2b30bSGeorge Karpenkov }
28984a2b30bSGeorge Karpenkov 
29098bee022SGeorge Karpenkov bool ExplodedNode::isTrivial() const {
29198bee022SGeorge Karpenkov   return pred_size() == 1 && succ_size() == 1 &&
292ff6df778SGeorge Karpenkov          getFirstPred()->getState()->getID() == getState()->getID() &&
293ff6df778SGeorge Karpenkov          getFirstPred()->succ_size() == 1;
29498bee022SGeorge Karpenkov }
29598bee022SGeorge Karpenkov 
296*dd53bdbfSKristof Umann const CFGBlock *ExplodedNode::getCFGBlock() const {
297*dd53bdbfSKristof Umann   ProgramPoint P = getLocation();
298*dd53bdbfSKristof Umann   if (auto BEP = P.getAs<BlockEntrance>())
299*dd53bdbfSKristof Umann     return BEP->getBlock();
300*dd53bdbfSKristof Umann 
301*dd53bdbfSKristof Umann   // Find the node's current statement in the CFG.
302*dd53bdbfSKristof Umann   if (const Stmt *S = PathDiagnosticLocation::getStmt(this))
303*dd53bdbfSKristof Umann     return getLocationContext()
304*dd53bdbfSKristof Umann         ->getAnalysisDeclContext()
305*dd53bdbfSKristof Umann         ->getCFGStmtMap()
306*dd53bdbfSKristof Umann         ->getBlock(S);
307*dd53bdbfSKristof Umann 
308*dd53bdbfSKristof Umann   return nullptr;
309*dd53bdbfSKristof Umann }
310*dd53bdbfSKristof Umann 
311fa0734ecSArgyrios Kyrtzidis ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
31249b1e38eSTed Kremenek                                      ProgramStateRef State,
31349ea5bf5SAnna Zaks                                      bool IsSink,
31449ea5bf5SAnna Zaks                                      bool* IsNew) {
315fa0734ecSArgyrios Kyrtzidis   // Profile 'State' to determine if we already have an existing node.
316fa0734ecSArgyrios Kyrtzidis   llvm::FoldingSetNodeID profile;
3170dbb783cSCraig Topper   void *InsertPos = nullptr;
318fa0734ecSArgyrios Kyrtzidis 
31949ea5bf5SAnna Zaks   NodeTy::Profile(profile, L, State, IsSink);
320fa0734ecSArgyrios Kyrtzidis   NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
321fa0734ecSArgyrios Kyrtzidis 
322fa0734ecSArgyrios Kyrtzidis   if (!V) {
323a2aa929eSTed Kremenek     if (!FreeNodes.empty()) {
324a2aa929eSTed Kremenek       V = FreeNodes.back();
325a2aa929eSTed Kremenek       FreeNodes.pop_back();
326a40f8ebcSTed Kremenek     }
327a40f8ebcSTed Kremenek     else {
328fa0734ecSArgyrios Kyrtzidis       // Allocate a new node.
329fa0734ecSArgyrios Kyrtzidis       V = (NodeTy*) getAllocator().Allocate<NodeTy>();
330a40f8ebcSTed Kremenek     }
331a40f8ebcSTed Kremenek 
33249ea5bf5SAnna Zaks     new (V) NodeTy(L, State, IsSink);
333fa0734ecSArgyrios Kyrtzidis 
334746c06d0SJordan Rose     if (ReclaimNodeInterval)
33535e55fe4STed Kremenek       ChangedNodes.push_back(V);
33635e55fe4STed Kremenek 
337fa0734ecSArgyrios Kyrtzidis     // Insert the node into the node set and return it.
338fa0734ecSArgyrios Kyrtzidis     Nodes.InsertNode(V, InsertPos);
339fa0734ecSArgyrios Kyrtzidis     ++NumNodes;
340fa0734ecSArgyrios Kyrtzidis 
341fa0734ecSArgyrios Kyrtzidis     if (IsNew) *IsNew = true;
342fa0734ecSArgyrios Kyrtzidis   }
343fa0734ecSArgyrios Kyrtzidis   else
344fa0734ecSArgyrios Kyrtzidis     if (IsNew) *IsNew = false;
345fa0734ecSArgyrios Kyrtzidis 
346fa0734ecSArgyrios Kyrtzidis   return V;
347fa0734ecSArgyrios Kyrtzidis }
348fa0734ecSArgyrios Kyrtzidis 
3494067e35fSBen Craig ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
3504067e35fSBen Craig                                                 ProgramStateRef State,
3514067e35fSBen Craig                                                 bool IsSink) {
3524067e35fSBen Craig   NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
3534067e35fSBen Craig   new (V) NodeTy(L, State, IsSink);
3544067e35fSBen Craig   return V;
3554067e35fSBen Craig }
3564067e35fSBen Craig 
357b564d1fbSDavid Blaikie std::unique_ptr<ExplodedGraph>
35825fac2f6SJordan Rose ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
3590833c84aSJordan Rose                     InterExplodedGraphMap *ForwardMap,
3600833c84aSJordan Rose                     InterExplodedGraphMap *InverseMap) const {
3610833c84aSJordan Rose   if (Nodes.empty())
3620dbb783cSCraig Topper     return nullptr;
363fa0734ecSArgyrios Kyrtzidis 
364e580d831SEugene Zelenko   using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
365fa0734ecSArgyrios Kyrtzidis   Pass1Ty Pass1;
366fa0734ecSArgyrios Kyrtzidis 
367e580d831SEugene Zelenko   using Pass2Ty = InterExplodedGraphMap;
3680833c84aSJordan Rose   InterExplodedGraphMap Pass2Scratch;
3690833c84aSJordan Rose   Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
370fa0734ecSArgyrios Kyrtzidis 
3710e62c1ccSChris Lattner   SmallVector<const ExplodedNode*, 10> WL1, WL2;
372fa0734ecSArgyrios Kyrtzidis 
373fa0734ecSArgyrios Kyrtzidis   // ===- Pass 1 (reverse DFS) -===
374e580d831SEugene Zelenko   for (const auto Sink : Sinks)
375e580d831SEugene Zelenko     if (Sink)
376e580d831SEugene Zelenko       WL1.push_back(Sink);
377fa0734ecSArgyrios Kyrtzidis 
3780833c84aSJordan Rose   // Process the first worklist until it is empty.
379fa0734ecSArgyrios Kyrtzidis   while (!WL1.empty()) {
38025284cc9SRobert Wilhelm     const ExplodedNode *N = WL1.pop_back_val();
381fa0734ecSArgyrios Kyrtzidis 
382fa0734ecSArgyrios Kyrtzidis     // Have we already visited this node?  If so, continue to the next one.
383ad8e079cSBenjamin Kramer     if (!Pass1.insert(N).second)
384fa0734ecSArgyrios Kyrtzidis       continue;
385fa0734ecSArgyrios Kyrtzidis 
386fa0734ecSArgyrios Kyrtzidis     // If this is a root enqueue it to the second worklist.
387fa0734ecSArgyrios Kyrtzidis     if (N->Preds.empty()) {
388fa0734ecSArgyrios Kyrtzidis       WL2.push_back(N);
389fa0734ecSArgyrios Kyrtzidis       continue;
390fa0734ecSArgyrios Kyrtzidis     }
391fa0734ecSArgyrios Kyrtzidis 
392fa0734ecSArgyrios Kyrtzidis     // Visit our predecessors and enqueue them.
393ad8e079cSBenjamin Kramer     WL1.append(N->Preds.begin(), N->Preds.end());
394fa0734ecSArgyrios Kyrtzidis   }
395fa0734ecSArgyrios Kyrtzidis 
396fa0734ecSArgyrios Kyrtzidis   // We didn't hit a root? Return with a null pointer for the new graph.
397fa0734ecSArgyrios Kyrtzidis   if (WL2.empty())
3980dbb783cSCraig Topper     return nullptr;
399fa0734ecSArgyrios Kyrtzidis 
400fa0734ecSArgyrios Kyrtzidis   // Create an empty graph.
401b564d1fbSDavid Blaikie   std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
402fa0734ecSArgyrios Kyrtzidis 
403fa0734ecSArgyrios Kyrtzidis   // ===- Pass 2 (forward DFS to construct the new graph) -===
404fa0734ecSArgyrios Kyrtzidis   while (!WL2.empty()) {
40525284cc9SRobert Wilhelm     const ExplodedNode *N = WL2.pop_back_val();
406fa0734ecSArgyrios Kyrtzidis 
407fa0734ecSArgyrios Kyrtzidis     // Skip this node if we have already processed it.
408fa0734ecSArgyrios Kyrtzidis     if (Pass2.find(N) != Pass2.end())
409fa0734ecSArgyrios Kyrtzidis       continue;
410fa0734ecSArgyrios Kyrtzidis 
411fa0734ecSArgyrios Kyrtzidis     // Create the corresponding node in the new graph and record the mapping
412fa0734ecSArgyrios Kyrtzidis     // from the old node to the new node.
4134067e35fSBen Craig     ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State, N->isSink());
414fa0734ecSArgyrios Kyrtzidis     Pass2[N] = NewN;
415fa0734ecSArgyrios Kyrtzidis 
416fa0734ecSArgyrios Kyrtzidis     // Also record the reverse mapping from the new node to the old node.
417fa0734ecSArgyrios Kyrtzidis     if (InverseMap) (*InverseMap)[NewN] = N;
418fa0734ecSArgyrios Kyrtzidis 
419fa0734ecSArgyrios Kyrtzidis     // If this node is a root, designate it as such in the graph.
420fa0734ecSArgyrios Kyrtzidis     if (N->Preds.empty())
421fa0734ecSArgyrios Kyrtzidis       G->addRoot(NewN);
422fa0734ecSArgyrios Kyrtzidis 
423fa0734ecSArgyrios Kyrtzidis     // In the case that some of the intended predecessors of NewN have already
424fa0734ecSArgyrios Kyrtzidis     // been created, we should hook them up as predecessors.
425fa0734ecSArgyrios Kyrtzidis 
426fa0734ecSArgyrios Kyrtzidis     // Walk through the predecessors of 'N' and hook up their corresponding
427fa0734ecSArgyrios Kyrtzidis     // nodes in the new graph (if any) to the freshly created node.
42880547386SJordan Rose     for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
42980547386SJordan Rose          I != E; ++I) {
430fa0734ecSArgyrios Kyrtzidis       Pass2Ty::iterator PI = Pass2.find(*I);
431fa0734ecSArgyrios Kyrtzidis       if (PI == Pass2.end())
432fa0734ecSArgyrios Kyrtzidis         continue;
433fa0734ecSArgyrios Kyrtzidis 
4340833c84aSJordan Rose       NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
435fa0734ecSArgyrios Kyrtzidis     }
436fa0734ecSArgyrios Kyrtzidis 
437fa0734ecSArgyrios Kyrtzidis     // In the case that some of the intended successors of NewN have already
438fa0734ecSArgyrios Kyrtzidis     // been created, we should hook them up as successors.  Otherwise, enqueue
439fa0734ecSArgyrios Kyrtzidis     // the new nodes from the original graph that should have nodes created
440fa0734ecSArgyrios Kyrtzidis     // in the new graph.
44180547386SJordan Rose     for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
44280547386SJordan Rose          I != E; ++I) {
443fa0734ecSArgyrios Kyrtzidis       Pass2Ty::iterator PI = Pass2.find(*I);
444fa0734ecSArgyrios Kyrtzidis       if (PI != Pass2.end()) {
4450833c84aSJordan Rose         const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
446fa0734ecSArgyrios Kyrtzidis         continue;
447fa0734ecSArgyrios Kyrtzidis       }
448fa0734ecSArgyrios Kyrtzidis 
449fa0734ecSArgyrios Kyrtzidis       // Enqueue nodes to the worklist that were marked during pass 1.
450fa0734ecSArgyrios Kyrtzidis       if (Pass1.count(*I))
451fa0734ecSArgyrios Kyrtzidis         WL2.push_back(*I);
452fa0734ecSArgyrios Kyrtzidis     }
453fa0734ecSArgyrios Kyrtzidis   }
454fa0734ecSArgyrios Kyrtzidis 
455fa0734ecSArgyrios Kyrtzidis   return G;
456fa0734ecSArgyrios Kyrtzidis }
457