1 //=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the template classes ExplodedNode and ExplodedGraph,
11 // which represent a path-sensitive, intra-procedural "exploded graph."
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
16 #include "clang/AST/ParentMap.h"
17 #include "clang/AST/Stmt.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
24 using namespace clang;
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 // An out of line virtual method to provide a home for the class vtable.
32 ExplodedNode::Auditor::~Auditor() {}
35 static ExplodedNode::Auditor* NodeAuditor = nullptr;
38 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 ExplodedGraph::ExplodedGraph()
49 : NumNodes(0), ReclaimNodeInterval(0) {}
51 ExplodedGraph::~ExplodedGraph() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 bool ExplodedGraph::isInterestingLValueExpr(const Expr *Ex) {
60 return isa<DeclRefExpr>(Ex) ||
61 isa<MemberExpr>(Ex) ||
62 isa<ObjCIvarRefExpr>(Ex);
65 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
66 // First, we only consider nodes for reclamation of the following
69 // (1) 1 predecessor (that has one successor)
70 // (2) 1 successor (that has one predecessor)
72 // If a node has no successor it is on the "frontier", while a node
73 // with no predecessor is a root.
75 // After these prerequisites, we discard all "filler" nodes that
76 // are used only for intermediate processing, and are not essential
77 // for analyzer history:
79 // (a) PreStmtPurgeDeadSymbols
81 // We then discard all other nodes where *all* of the following conditions
84 // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
85 // (4) There is no 'tag' for the ProgramPoint.
86 // (5) The 'store' is the same as the predecessor.
87 // (6) The 'GDM' is the same as the predecessor.
88 // (7) The LocationContext is the same as the predecessor.
89 // (8) Expressions that are *not* lvalue expressions.
90 // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
91 // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
92 // PreImplicitCall (so that we would be able to find it when retrying a
93 // call with no inlining).
94 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
96 // Conditions 1 and 2.
97 if (node->pred_size() != 1 || node->succ_size() != 1)
100 const ExplodedNode *pred = *(node->pred_begin());
101 if (pred->succ_size() != 1)
104 const ExplodedNode *succ = *(node->succ_begin());
105 if (succ->pred_size() != 1)
108 // Now reclaim any nodes that are (by definition) not essential to
109 // analysis history and are not consulted by any client code.
110 ProgramPoint progPoint = node->getLocation();
111 if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
112 return !progPoint.getTag();
115 if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
119 if (progPoint.getTag())
122 // Conditions 5, 6, and 7.
123 ProgramStateRef state = node->getState();
124 ProgramStateRef pred_state = pred->getState();
125 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
126 progPoint.getLocationContext() != pred->getLocationContext())
129 // All further checks require expressions. As per #3, we know that we have
131 const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
136 // Do not collect nodes for "interesting" lvalue expressions since they are
137 // used extensively for generating path diagnostics.
138 if (isInterestingLValueExpr(Ex))
142 // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
143 // diagnostic generation; specifically, so that we could anchor arrows
144 // pointing to the beginning of statements (as written in code).
145 ParentMap &PM = progPoint.getLocationContext()->getParentMap();
146 if (!PM.isConsumedExpr(Ex))
150 const ProgramPoint SuccLoc = succ->getLocation();
151 if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
152 if (CallEvent::isCallStmt(SP->getStmt()))
155 // Condition 10, continuation.
156 if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
162 void ExplodedGraph::collectNode(ExplodedNode *node) {
163 // Removing a node means:
164 // (a) changing the predecessors successor to the successor of this node
165 // (b) changing the successors predecessor to the predecessor of this node
166 // (c) Putting 'node' onto freeNodes.
167 assert(node->pred_size() == 1 || node->succ_size() == 1);
168 ExplodedNode *pred = *(node->pred_begin());
169 ExplodedNode *succ = *(node->succ_begin());
170 pred->replaceSuccessor(succ);
171 succ->replacePredecessor(pred);
172 FreeNodes.push_back(node);
173 Nodes.RemoveNode(node);
175 node->~ExplodedNode();
178 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
179 if (ChangedNodes.empty())
182 // Only periodically reclaim nodes so that we can build up a set of
183 // nodes that meet the reclamation criteria. Freshly created nodes
184 // by definition have no successor, and thus cannot be reclaimed (see below).
185 assert(ReclaimCounter > 0);
186 if (--ReclaimCounter != 0)
188 ReclaimCounter = ReclaimNodeInterval;
190 for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
192 ExplodedNode *node = *it;
193 if (shouldCollect(node))
196 ChangedNodes.clear();
199 //===----------------------------------------------------------------------===//
201 //===----------------------------------------------------------------------===//
203 // An NodeGroup's storage type is actually very much like a TinyPtrVector:
204 // it can be either a pointer to a single ExplodedNode, or a pointer to a
205 // BumpVector allocated with the ExplodedGraph's allocator. This allows the
206 // common case of single-node NodeGroups to be implemented with no extra memory.
208 // Consequently, each of the NodeGroup methods have up to four cases to handle:
209 // 1. The flag is set and this group does not actually contain any nodes.
210 // 2. The group is empty, in which case the storage value is null.
211 // 3. The group contains a single node.
212 // 4. The group contains more than one node.
213 typedef BumpVector<ExplodedNode *> ExplodedNodeVector;
214 typedef llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *> GroupStorage;
216 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
217 assert (!V->isSink());
219 V->Succs.addNode(this, G);
221 if (NodeAuditor) NodeAuditor->AddEdge(V, this);
225 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
228 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
229 assert(Storage.is<ExplodedNode *>());
231 assert(Storage.is<ExplodedNode *>());
234 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
237 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
238 if (Storage.isNull()) {
240 assert(Storage.is<ExplodedNode *>());
244 ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
247 // Switch from single-node to multi-node representation.
248 ExplodedNode *Old = Storage.get<ExplodedNode *>();
250 BumpVectorContext &Ctx = G.getNodeAllocator();
251 V = G.getAllocator().Allocate<ExplodedNodeVector>();
252 new (V) ExplodedNodeVector(Ctx, 4);
253 V->push_back(Old, Ctx);
257 assert(Storage.is<ExplodedNodeVector *>());
260 V->push_back(N, G.getNodeAllocator());
263 unsigned ExplodedNode::NodeGroup::size() const {
267 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
268 if (Storage.isNull())
270 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
275 ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
279 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
280 if (Storage.isNull())
282 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
284 return Storage.getAddrOfPtr1();
287 ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
291 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
292 if (Storage.isNull())
294 if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
296 return Storage.getAddrOfPtr1() + 1;
299 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
300 ProgramStateRef State,
303 // Profile 'State' to determine if we already have an existing node.
304 llvm::FoldingSetNodeID profile;
305 void *InsertPos = nullptr;
307 NodeTy::Profile(profile, L, State, IsSink);
308 NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
311 if (!FreeNodes.empty()) {
312 V = FreeNodes.back();
313 FreeNodes.pop_back();
316 // Allocate a new node.
317 V = (NodeTy*) getAllocator().Allocate<NodeTy>();
320 new (V) NodeTy(L, State, IsSink);
322 if (ReclaimNodeInterval)
323 ChangedNodes.push_back(V);
325 // Insert the node into the node set and return it.
326 Nodes.InsertNode(V, InsertPos);
329 if (IsNew) *IsNew = true;
332 if (IsNew) *IsNew = false;
337 ExplodedNode *ExplodedGraph::createUncachedNode(const ProgramPoint &L,
338 ProgramStateRef State,
340 NodeTy *V = (NodeTy *) getAllocator().Allocate<NodeTy>();
341 new (V) NodeTy(L, State, IsSink);
345 std::unique_ptr<ExplodedGraph>
346 ExplodedGraph::trim(ArrayRef<const NodeTy *> Sinks,
347 InterExplodedGraphMap *ForwardMap,
348 InterExplodedGraphMap *InverseMap) const {
353 typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
356 typedef InterExplodedGraphMap Pass2Ty;
357 InterExplodedGraphMap Pass2Scratch;
358 Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
360 SmallVector<const ExplodedNode*, 10> WL1, WL2;
362 // ===- Pass 1 (reverse DFS) -===
363 for (ArrayRef<const NodeTy *>::iterator I = Sinks.begin(), E = Sinks.end();
369 // Process the first worklist until it is empty.
370 while (!WL1.empty()) {
371 const ExplodedNode *N = WL1.pop_back_val();
373 // Have we already visited this node? If so, continue to the next one.
374 if (!Pass1.insert(N).second)
377 // If this is a root enqueue it to the second worklist.
378 if (N->Preds.empty()) {
383 // Visit our predecessors and enqueue them.
384 WL1.append(N->Preds.begin(), N->Preds.end());
387 // We didn't hit a root? Return with a null pointer for the new graph.
391 // Create an empty graph.
392 std::unique_ptr<ExplodedGraph> G = MakeEmptyGraph();
394 // ===- Pass 2 (forward DFS to construct the new graph) -===
395 while (!WL2.empty()) {
396 const ExplodedNode *N = WL2.pop_back_val();
398 // Skip this node if we have already processed it.
399 if (Pass2.find(N) != Pass2.end())
402 // Create the corresponding node in the new graph and record the mapping
403 // from the old node to the new node.
404 ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State, N->isSink());
407 // Also record the reverse mapping from the new node to the old node.
408 if (InverseMap) (*InverseMap)[NewN] = N;
410 // If this node is a root, designate it as such in the graph.
411 if (N->Preds.empty())
414 // In the case that some of the intended predecessors of NewN have already
415 // been created, we should hook them up as predecessors.
417 // Walk through the predecessors of 'N' and hook up their corresponding
418 // nodes in the new graph (if any) to the freshly created node.
419 for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
421 Pass2Ty::iterator PI = Pass2.find(*I);
422 if (PI == Pass2.end())
425 NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
428 // In the case that some of the intended successors of NewN have already
429 // been created, we should hook them up as successors. Otherwise, enqueue
430 // the new nodes from the original graph that should have nodes created
432 for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
434 Pass2Ty::iterator PI = Pass2.find(*I);
435 if (PI != Pass2.end()) {
436 const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
440 // Enqueue nodes to the worklist that were marked during pass 1.