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