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