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