1 //=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the template classes ExplodedNode and ExplodedGraph,
11 //  which represent a path-sensitive, intra-procedural "exploded graph."
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 #include "clang/AST/Stmt.h"
18 #include "clang/AST/ParentMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include <vector>
23 
24 using namespace clang;
25 using namespace ento;
26 
27 //===----------------------------------------------------------------------===//
28 // Node auditing.
29 //===----------------------------------------------------------------------===//
30 
31 // An out of line virtual method to provide a home for the class vtable.
32 ExplodedNode::Auditor::~Auditor() {}
33 
34 #ifndef NDEBUG
35 static ExplodedNode::Auditor* NodeAuditor = 0;
36 #endif
37 
38 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
39 #ifndef NDEBUG
40   NodeAuditor = A;
41 #endif
42 }
43 
44 //===----------------------------------------------------------------------===//
45 // Cleanup.
46 //===----------------------------------------------------------------------===//
47 
48 typedef std::vector<ExplodedNode*> NodeList;
49 static inline NodeList*& getNodeList(void *&p) { return (NodeList*&) p; }
50 
51 static const unsigned CounterTop = 1000;
52 
53 ExplodedGraph::ExplodedGraph()
54   : NumNodes(0), recentlyAllocatedNodes(0),
55     freeNodes(0), reclaimNodes(false),
56     reclaimCounter(CounterTop) {}
57 
58 ExplodedGraph::~ExplodedGraph() {
59   if (reclaimNodes) {
60     delete getNodeList(recentlyAllocatedNodes);
61     delete getNodeList(freeNodes);
62   }
63 }
64 
65 //===----------------------------------------------------------------------===//
66 // Node reclamation.
67 //===----------------------------------------------------------------------===//
68 
69 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
70   if (!recentlyAllocatedNodes)
71     return;
72 
73   // Only periodically relcaim nodes so that we can build up a set of
74   // nodes that meet the reclamation criteria.  Freshly created nodes
75   // by definition have no successor, and thus cannot be reclaimed (see below).
76   assert(reclaimCounter > 0);
77   if (--reclaimCounter != 0)
78     return;
79   reclaimCounter = CounterTop;
80 
81   NodeList &nl = *getNodeList(recentlyAllocatedNodes);
82 
83   // Reclaimn all nodes that match *all* the following criteria:
84   //
85   // (1) 1 predecessor (that has one successor)
86   // (2) 1 successor (that has one predecessor)
87   // (3) The ProgramPoint is for a PostStmt.
88   // (4) There is no 'tag' for the ProgramPoint.
89   // (5) The 'store' is the same as the predecessor.
90   // (6) The 'GDM' is the same as the predecessor.
91   // (7) The LocationContext is the same as the predecessor.
92   // (8) The PostStmt is for a non-consumed Stmt or Expr.
93 
94   for (NodeList::iterator i = nl.begin(), e = nl.end() ; i != e; ++i) {
95     ExplodedNode *node = *i;
96 
97     // Conditions 1 and 2.
98     if (node->pred_size() != 1 || node->succ_size() != 1)
99       continue;
100 
101     ExplodedNode *pred = *(node->pred_begin());
102     if (pred->succ_size() != 1)
103       continue;
104 
105     ExplodedNode *succ = *(node->succ_begin());
106     if (succ->pred_size() != 1)
107       continue;
108 
109     // Condition 3.
110     ProgramPoint progPoint = node->getLocation();
111     if (!isa<PostStmt>(progPoint) ||
112         (isa<CallEnter>(progPoint) || isa<CallExit>(progPoint)))
113       continue;
114     // Condition 4.
115     PostStmt ps = cast<PostStmt>(progPoint);
116     if (ps.getTag())
117       continue;
118 
119     if (isa<BinaryOperator>(ps.getStmt()))
120       continue;
121 
122     // Conditions 5, 6, and 7.
123     const ProgramState *state = node->getState();
124     const ProgramState *pred_state = pred->getState();
125     if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
126         progPoint.getLocationContext() != pred->getLocationContext())
127       continue;
128 
129     // Condition 8.
130     if (const Expr *Ex = dyn_cast<Expr>(ps.getStmt())) {
131       ParentMap &PM = progPoint.getLocationContext()->getParentMap();
132       if (!PM.isConsumedExpr(Ex))
133         continue;
134     }
135 
136     // If we reach here, we can remove the node.  This means:
137     // (a) changing the predecessors successor to the successor of this node
138     // (b) changing the successors predecessor to the predecessor of this node
139     // (c) Putting 'node' onto freeNodes.
140     pred->replaceSuccessor(succ);
141     succ->replacePredecessor(pred);
142     if (!freeNodes)
143       freeNodes = new NodeList();
144     getNodeList(freeNodes)->push_back(node);
145     Nodes.RemoveNode(node);
146     --NumNodes;
147     node->~ExplodedNode();
148   }
149 
150   nl.clear();
151 }
152 
153 //===----------------------------------------------------------------------===//
154 // ExplodedNode.
155 //===----------------------------------------------------------------------===//
156 
157 static inline BumpVector<ExplodedNode*>& getVector(void *P) {
158   return *reinterpret_cast<BumpVector<ExplodedNode*>*>(P);
159 }
160 
161 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
162   assert (!V->isSink());
163   Preds.addNode(V, G);
164   V->Succs.addNode(this, G);
165 #ifndef NDEBUG
166   if (NodeAuditor) NodeAuditor->AddEdge(V, this);
167 #endif
168 }
169 
170 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
171   assert(getKind() == Size1);
172   P = reinterpret_cast<uintptr_t>(node);
173   assert(getKind() == Size1);
174 }
175 
176 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
177   assert((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0);
178   assert(!getFlag());
179 
180   if (getKind() == Size1) {
181     if (ExplodedNode *NOld = getNode()) {
182       BumpVectorContext &Ctx = G.getNodeAllocator();
183       BumpVector<ExplodedNode*> *V =
184         G.getAllocator().Allocate<BumpVector<ExplodedNode*> >();
185       new (V) BumpVector<ExplodedNode*>(Ctx, 4);
186 
187       assert((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0);
188       V->push_back(NOld, Ctx);
189       V->push_back(N, Ctx);
190       P = reinterpret_cast<uintptr_t>(V) | SizeOther;
191       assert(getPtr() == (void*) V);
192       assert(getKind() == SizeOther);
193     }
194     else {
195       P = reinterpret_cast<uintptr_t>(N);
196       assert(getKind() == Size1);
197     }
198   }
199   else {
200     assert(getKind() == SizeOther);
201     getVector(getPtr()).push_back(N, G.getNodeAllocator());
202   }
203 }
204 
205 unsigned ExplodedNode::NodeGroup::size() const {
206   if (getFlag())
207     return 0;
208 
209   if (getKind() == Size1)
210     return getNode() ? 1 : 0;
211   else
212     return getVector(getPtr()).size();
213 }
214 
215 ExplodedNode **ExplodedNode::NodeGroup::begin() const {
216   if (getFlag())
217     return NULL;
218 
219   if (getKind() == Size1)
220     return (ExplodedNode**) (getPtr() ? &P : NULL);
221   else
222     return const_cast<ExplodedNode**>(&*(getVector(getPtr()).begin()));
223 }
224 
225 ExplodedNode** ExplodedNode::NodeGroup::end() const {
226   if (getFlag())
227     return NULL;
228 
229   if (getKind() == Size1)
230     return (ExplodedNode**) (getPtr() ? &P+1 : NULL);
231   else {
232     // Dereferencing end() is undefined behaviour. The vector is not empty, so
233     // we can dereference the last elem and then add 1 to the result.
234     return const_cast<ExplodedNode**>(getVector(getPtr()).end());
235   }
236 }
237 
238 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
239                                      const ProgramState *State,
240                                      bool IsSink,
241                                      bool* IsNew) {
242   // Profile 'State' to determine if we already have an existing node.
243   llvm::FoldingSetNodeID profile;
244   void *InsertPos = 0;
245 
246   NodeTy::Profile(profile, L, State, IsSink);
247   NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
248 
249   if (!V) {
250     if (freeNodes && !getNodeList(freeNodes)->empty()) {
251       NodeList *nl = getNodeList(freeNodes);
252       V = nl->back();
253       nl->pop_back();
254     }
255     else {
256       // Allocate a new node.
257       V = (NodeTy*) getAllocator().Allocate<NodeTy>();
258     }
259 
260     new (V) NodeTy(L, State, IsSink);
261 
262     if (reclaimNodes) {
263       if (!recentlyAllocatedNodes)
264         recentlyAllocatedNodes = new NodeList();
265       getNodeList(recentlyAllocatedNodes)->push_back(V);
266     }
267 
268     // Insert the node into the node set and return it.
269     Nodes.InsertNode(V, InsertPos);
270 
271     ++NumNodes;
272 
273     if (IsNew) *IsNew = true;
274   }
275   else
276     if (IsNew) *IsNew = false;
277 
278   return V;
279 }
280 
281 std::pair<ExplodedGraph*, InterExplodedGraphMap*>
282 ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
283                llvm::DenseMap<const void*, const void*> *InverseMap) const {
284 
285   if (NBeg == NEnd)
286     return std::make_pair((ExplodedGraph*) 0,
287                           (InterExplodedGraphMap*) 0);
288 
289   assert (NBeg < NEnd);
290 
291   llvm::OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
292 
293   ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap);
294 
295   return std::make_pair(static_cast<ExplodedGraph*>(G), M.take());
296 }
297 
298 ExplodedGraph*
299 ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources,
300                             const ExplodedNode* const* EndSources,
301                             InterExplodedGraphMap* M,
302                    llvm::DenseMap<const void*, const void*> *InverseMap) const {
303 
304   typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
305   Pass1Ty Pass1;
306 
307   typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty;
308   Pass2Ty& Pass2 = M->M;
309 
310   SmallVector<const ExplodedNode*, 10> WL1, WL2;
311 
312   // ===- Pass 1 (reverse DFS) -===
313   for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) {
314     assert(*I);
315     WL1.push_back(*I);
316   }
317 
318   // Process the first worklist until it is empty.  Because it is a std::list
319   // it acts like a FIFO queue.
320   while (!WL1.empty()) {
321     const ExplodedNode *N = WL1.back();
322     WL1.pop_back();
323 
324     // Have we already visited this node?  If so, continue to the next one.
325     if (Pass1.count(N))
326       continue;
327 
328     // Otherwise, mark this node as visited.
329     Pass1.insert(N);
330 
331     // If this is a root enqueue it to the second worklist.
332     if (N->Preds.empty()) {
333       WL2.push_back(N);
334       continue;
335     }
336 
337     // Visit our predecessors and enqueue them.
338     for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I)
339       WL1.push_back(*I);
340   }
341 
342   // We didn't hit a root? Return with a null pointer for the new graph.
343   if (WL2.empty())
344     return 0;
345 
346   // Create an empty graph.
347   ExplodedGraph* G = MakeEmptyGraph();
348 
349   // ===- Pass 2 (forward DFS to construct the new graph) -===
350   while (!WL2.empty()) {
351     const ExplodedNode *N = WL2.back();
352     WL2.pop_back();
353 
354     // Skip this node if we have already processed it.
355     if (Pass2.find(N) != Pass2.end())
356       continue;
357 
358     // Create the corresponding node in the new graph and record the mapping
359     // from the old node to the new node.
360     ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0);
361     Pass2[N] = NewN;
362 
363     // Also record the reverse mapping from the new node to the old node.
364     if (InverseMap) (*InverseMap)[NewN] = N;
365 
366     // If this node is a root, designate it as such in the graph.
367     if (N->Preds.empty())
368       G->addRoot(NewN);
369 
370     // In the case that some of the intended predecessors of NewN have already
371     // been created, we should hook them up as predecessors.
372 
373     // Walk through the predecessors of 'N' and hook up their corresponding
374     // nodes in the new graph (if any) to the freshly created node.
375     for (ExplodedNode **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) {
376       Pass2Ty::iterator PI = Pass2.find(*I);
377       if (PI == Pass2.end())
378         continue;
379 
380       NewN->addPredecessor(PI->second, *G);
381     }
382 
383     // In the case that some of the intended successors of NewN have already
384     // been created, we should hook them up as successors.  Otherwise, enqueue
385     // the new nodes from the original graph that should have nodes created
386     // in the new graph.
387     for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) {
388       Pass2Ty::iterator PI = Pass2.find(*I);
389       if (PI != Pass2.end()) {
390         PI->second->addPredecessor(NewN, *G);
391         continue;
392       }
393 
394       // Enqueue nodes to the worklist that were marked during pass 1.
395       if (Pass1.count(*I))
396         WL2.push_back(*I);
397     }
398   }
399 
400   return G;
401 }
402 
403 void InterExplodedGraphMap::anchor() { }
404 
405 ExplodedNode*
406 InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
407   llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =
408     M.find(N);
409 
410   return I == M.end() ? 0 : I->second;
411 }
412 
413