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