ExplodedGraph.h revision 9b663716449b618ba0390b1dbebc54fa8e971124
1//=-- ExplodedGraph.h - 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//  See "Precise interprocedural dataflow analysis via graph reachability"
13//  by Reps, Horwitz, and Sagiv
14//  (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
15//  exploded graph.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_CLANG_GR_EXPLODEDGRAPH
20#define LLVM_CLANG_GR_EXPLODEDGRAPH
21
22#include "clang/Analysis/ProgramPoint.h"
23#include "clang/Analysis/AnalysisContext.h"
24#include "clang/AST/Decl.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/Support/Allocator.h"
29#include "llvm/ADT/OwningPtr.h"
30#include "llvm/ADT/GraphTraits.h"
31#include "llvm/ADT/DepthFirstIterator.h"
32#include "llvm/Support/Casting.h"
33#include "clang/Analysis/Support/BumpVector.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
35
36namespace clang {
37
38class CFG;
39
40namespace ento {
41
42class ExplodedGraph;
43
44//===----------------------------------------------------------------------===//
45// ExplodedGraph "implementation" classes.  These classes are not typed to
46// contain a specific kind of state.  Typed-specialized versions are defined
47// on top of these classes.
48//===----------------------------------------------------------------------===//
49
50// ExplodedNode is not constified all over the engine because we need to add
51// successors to it at any time after creating it.
52
53class ExplodedNode : public llvm::FoldingSetNode {
54  friend class ExplodedGraph;
55  friend class CoreEngine;
56  friend class StmtNodeBuilder;
57  friend class BranchNodeBuilder;
58  friend class IndirectGotoNodeBuilder;
59  friend class SwitchNodeBuilder;
60  friend class EndOfFunctionNodeBuilder;
61
62  class NodeGroup {
63    enum { Size1 = 0x0, SizeOther = 0x1, AuxFlag = 0x2, Mask = 0x3 };
64    uintptr_t P;
65
66    unsigned getKind() const {
67      return P & 0x1;
68    }
69
70    void* getPtr() const {
71      assert (!getFlag());
72      return reinterpret_cast<void*>(P & ~Mask);
73    }
74
75    ExplodedNode *getNode() const {
76      return reinterpret_cast<ExplodedNode*>(getPtr());
77    }
78
79  public:
80    NodeGroup() : P(0) {}
81
82    ExplodedNode **begin() const;
83
84    ExplodedNode **end() const;
85
86    unsigned size() const;
87
88    bool empty() const { return (P & ~Mask) == 0; }
89
90    void addNode(ExplodedNode* N, ExplodedGraph &G);
91
92    void replaceNode(ExplodedNode *node);
93
94    void setFlag() {
95      assert(P == 0);
96      P = AuxFlag;
97    }
98
99    bool getFlag() const {
100      return P & AuxFlag ? true : false;
101    }
102  };
103
104  /// Location - The program location (within a function body) associated
105  ///  with this node.
106  const ProgramPoint Location;
107
108  /// State - The state associated with this node.
109  const GRState* State;
110
111  /// Preds - The predecessors of this node.
112  NodeGroup Preds;
113
114  /// Succs - The successors of this node.
115  NodeGroup Succs;
116
117public:
118
119  explicit ExplodedNode(const ProgramPoint& loc, const GRState* state)
120    : Location(loc), State(state) {
121    const_cast<GRState*>(State)->setReferencedByExplodedNode();
122  }
123
124  /// getLocation - Returns the edge associated with the given node.
125  ProgramPoint getLocation() const { return Location; }
126
127  const LocationContext *getLocationContext() const {
128    return getLocation().getLocationContext();
129  }
130
131  const Decl &getCodeDecl() const { return *getLocationContext()->getDecl(); }
132
133  CFG &getCFG() const { return *getLocationContext()->getCFG(); }
134
135  ParentMap &getParentMap() const {return getLocationContext()->getParentMap();}
136
137  LiveVariables &getLiveVariables() const {
138    return *getLocationContext()->getLiveVariables();
139  }
140
141  const GRState* getState() const { return State; }
142
143  template <typename T>
144  const T* getLocationAs() const { return llvm::dyn_cast<T>(&Location); }
145
146  static void Profile(llvm::FoldingSetNodeID &ID,
147                      const ProgramPoint& Loc, const GRState* state) {
148    ID.Add(Loc);
149    ID.AddPointer(state);
150  }
151
152  void Profile(llvm::FoldingSetNodeID& ID) const {
153    Profile(ID, getLocation(), getState());
154  }
155
156  /// addPredeccessor - Adds a predecessor to the current node, and
157  ///  in tandem add this node as a successor of the other node.
158  void addPredecessor(ExplodedNode* V, ExplodedGraph &G);
159
160  unsigned succ_size() const { return Succs.size(); }
161  unsigned pred_size() const { return Preds.size(); }
162  bool succ_empty() const { return Succs.empty(); }
163  bool pred_empty() const { return Preds.empty(); }
164
165  bool isSink() const { return Succs.getFlag(); }
166  void markAsSink() { Succs.setFlag(); }
167
168  ExplodedNode* getFirstPred() {
169    return pred_empty() ? NULL : *(pred_begin());
170  }
171
172  const ExplodedNode* getFirstPred() const {
173    return const_cast<ExplodedNode*>(this)->getFirstPred();
174  }
175
176  // Iterators over successor and predecessor vertices.
177  typedef ExplodedNode**       succ_iterator;
178  typedef const ExplodedNode* const * const_succ_iterator;
179  typedef ExplodedNode**       pred_iterator;
180  typedef const ExplodedNode* const * const_pred_iterator;
181
182  pred_iterator pred_begin() { return Preds.begin(); }
183  pred_iterator pred_end() { return Preds.end(); }
184
185  const_pred_iterator pred_begin() const {
186    return const_cast<ExplodedNode*>(this)->pred_begin();
187  }
188  const_pred_iterator pred_end() const {
189    return const_cast<ExplodedNode*>(this)->pred_end();
190  }
191
192  succ_iterator succ_begin() { return Succs.begin(); }
193  succ_iterator succ_end() { return Succs.end(); }
194
195  const_succ_iterator succ_begin() const {
196    return const_cast<ExplodedNode*>(this)->succ_begin();
197  }
198  const_succ_iterator succ_end() const {
199    return const_cast<ExplodedNode*>(this)->succ_end();
200  }
201
202  // For debugging.
203
204public:
205
206  class Auditor {
207  public:
208    virtual ~Auditor();
209    virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst) = 0;
210  };
211
212  static void SetAuditor(Auditor* A);
213
214private:
215  void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
216  void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }
217};
218
219// FIXME: Is this class necessary?
220class InterExplodedGraphMap {
221  llvm::DenseMap<const ExplodedNode*, ExplodedNode*> M;
222  friend class ExplodedGraph;
223
224public:
225  ExplodedNode* getMappedNode(const ExplodedNode* N) const;
226
227  InterExplodedGraphMap() {}
228  virtual ~InterExplodedGraphMap() {}
229};
230
231class ExplodedGraph {
232protected:
233  friend class CoreEngine;
234
235  // Type definitions.
236  typedef llvm::SmallVector<ExplodedNode*,2>    RootsTy;
237  typedef llvm::SmallVector<ExplodedNode*,10>   EndNodesTy;
238
239  /// Roots - The roots of the simulation graph. Usually there will be only
240  /// one, but clients are free to establish multiple subgraphs within a single
241  /// SimulGraph. Moreover, these subgraphs can often merge when paths from
242  /// different roots reach the same state at the same program location.
243  RootsTy Roots;
244
245  /// EndNodes - The nodes in the simulation graph which have been
246  ///  specially marked as the endpoint of an abstract simulation path.
247  EndNodesTy EndNodes;
248
249  /// Nodes - The nodes in the graph.
250  llvm::FoldingSet<ExplodedNode> Nodes;
251
252  /// BVC - Allocator and context for allocating nodes and their predecessor
253  /// and successor groups.
254  BumpVectorContext BVC;
255
256  /// NumNodes - The number of nodes in the graph.
257  unsigned NumNodes;
258
259  /// A list of recently allocated nodes that can potentially be recycled.
260  void *recentlyAllocatedNodes;
261
262  /// A list of nodes that can be reused.
263  void *freeNodes;
264
265  /// A flag that indicates whether nodes should be recycled.
266  bool reclaimNodes;
267
268public:
269  /// getNode - Retrieve the node associated with a (Location,State) pair,
270  ///  where the 'Location' is a ProgramPoint in the CFG.  If no node for
271  ///  this pair exists, it is created.  IsNew is set to true if
272  ///  the node was freshly created.
273
274  ExplodedNode* getNode(const ProgramPoint& L, const GRState *State,
275                        bool* IsNew = 0);
276
277  ExplodedGraph* MakeEmptyGraph() const {
278    return new ExplodedGraph();
279  }
280
281  /// addRoot - Add an untyped node to the set of roots.
282  ExplodedNode* addRoot(ExplodedNode* V) {
283    Roots.push_back(V);
284    return V;
285  }
286
287  /// addEndOfPath - Add an untyped node to the set of EOP nodes.
288  ExplodedNode* addEndOfPath(ExplodedNode* V) {
289    EndNodes.push_back(V);
290    return V;
291  }
292
293  ExplodedGraph()
294    : NumNodes(0), recentlyAllocatedNodes(0),
295      freeNodes(0), reclaimNodes(false) {}
296
297  ~ExplodedGraph();
298
299  unsigned num_roots() const { return Roots.size(); }
300  unsigned num_eops() const { return EndNodes.size(); }
301
302  bool empty() const { return NumNodes == 0; }
303  unsigned size() const { return NumNodes; }
304
305  // Iterators.
306  typedef ExplodedNode                        NodeTy;
307  typedef llvm::FoldingSet<ExplodedNode>      AllNodesTy;
308  typedef NodeTy**                            roots_iterator;
309  typedef NodeTy* const *                     const_roots_iterator;
310  typedef NodeTy**                            eop_iterator;
311  typedef NodeTy* const *                     const_eop_iterator;
312  typedef AllNodesTy::iterator                node_iterator;
313  typedef AllNodesTy::const_iterator          const_node_iterator;
314
315  node_iterator nodes_begin() { return Nodes.begin(); }
316
317  node_iterator nodes_end() { return Nodes.end(); }
318
319  const_node_iterator nodes_begin() const { return Nodes.begin(); }
320
321  const_node_iterator nodes_end() const { return Nodes.end(); }
322
323  roots_iterator roots_begin() { return Roots.begin(); }
324
325  roots_iterator roots_end() { return Roots.end(); }
326
327  const_roots_iterator roots_begin() const { return Roots.begin(); }
328
329  const_roots_iterator roots_end() const { return Roots.end(); }
330
331  eop_iterator eop_begin() { return EndNodes.begin(); }
332
333  eop_iterator eop_end() { return EndNodes.end(); }
334
335  const_eop_iterator eop_begin() const { return EndNodes.begin(); }
336
337  const_eop_iterator eop_end() const { return EndNodes.end(); }
338
339  llvm::BumpPtrAllocator & getAllocator() { return BVC.getAllocator(); }
340  BumpVectorContext &getNodeAllocator() { return BVC; }
341
342  typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> NodeMap;
343
344  std::pair<ExplodedGraph*, InterExplodedGraphMap*>
345  Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
346       llvm::DenseMap<const void*, const void*> *InverseMap = 0) const;
347
348  ExplodedGraph* TrimInternal(const ExplodedNode* const * NBeg,
349                              const ExplodedNode* const * NEnd,
350                              InterExplodedGraphMap *M,
351                    llvm::DenseMap<const void*, const void*> *InverseMap) const;
352
353  /// Enable tracking of recently allocated nodes for potential reclamation
354  /// when calling reclaimRecentlyAllocatedNodes().
355  void enableNodeReclamation() { reclaimNodes = true; }
356
357  /// Reclaim "uninteresting" nodes created since the last time this method
358  /// was called.
359  void reclaimRecentlyAllocatedNodes();
360};
361
362class ExplodedNodeSet {
363  typedef llvm::SmallPtrSet<ExplodedNode*,5> ImplTy;
364  ImplTy Impl;
365
366public:
367  ExplodedNodeSet(ExplodedNode* N) {
368    assert (N && !static_cast<ExplodedNode*>(N)->isSink());
369    Impl.insert(N);
370  }
371
372  ExplodedNodeSet() {}
373
374  inline void Add(ExplodedNode* N) {
375    if (N && !static_cast<ExplodedNode*>(N)->isSink()) Impl.insert(N);
376  }
377
378  ExplodedNodeSet& operator=(const ExplodedNodeSet &X) {
379    Impl = X.Impl;
380    return *this;
381  }
382
383  typedef ImplTy::iterator       iterator;
384  typedef ImplTy::const_iterator const_iterator;
385
386  unsigned size() const { return Impl.size();  }
387  bool empty()    const { return Impl.empty(); }
388
389  void clear() { Impl.clear(); }
390  void insert(const ExplodedNodeSet &S) {
391    if (empty())
392      Impl = S.Impl;
393    else
394      Impl.insert(S.begin(), S.end());
395  }
396
397  inline iterator begin() { return Impl.begin(); }
398  inline iterator end()   { return Impl.end();   }
399
400  inline const_iterator begin() const { return Impl.begin(); }
401  inline const_iterator end()   const { return Impl.end();   }
402};
403
404} // end GR namespace
405
406} // end clang namespace
407
408// GraphTraits
409
410namespace llvm {
411  template<> struct GraphTraits<clang::ento::ExplodedNode*> {
412    typedef clang::ento::ExplodedNode NodeType;
413    typedef NodeType::succ_iterator  ChildIteratorType;
414    typedef llvm::df_iterator<NodeType*>      nodes_iterator;
415
416    static inline NodeType* getEntryNode(NodeType* N) {
417      return N;
418    }
419
420    static inline ChildIteratorType child_begin(NodeType* N) {
421      return N->succ_begin();
422    }
423
424    static inline ChildIteratorType child_end(NodeType* N) {
425      return N->succ_end();
426    }
427
428    static inline nodes_iterator nodes_begin(NodeType* N) {
429      return df_begin(N);
430    }
431
432    static inline nodes_iterator nodes_end(NodeType* N) {
433      return df_end(N);
434    }
435  };
436
437  template<> struct GraphTraits<const clang::ento::ExplodedNode*> {
438    typedef const clang::ento::ExplodedNode NodeType;
439    typedef NodeType::const_succ_iterator   ChildIteratorType;
440    typedef llvm::df_iterator<NodeType*>       nodes_iterator;
441
442    static inline NodeType* getEntryNode(NodeType* N) {
443      return N;
444    }
445
446    static inline ChildIteratorType child_begin(NodeType* N) {
447      return N->succ_begin();
448    }
449
450    static inline ChildIteratorType child_end(NodeType* N) {
451      return N->succ_end();
452    }
453
454    static inline nodes_iterator nodes_begin(NodeType* N) {
455      return df_begin(N);
456    }
457
458    static inline nodes_iterator nodes_end(NodeType* N) {
459      return df_end(N);
460    }
461  };
462
463} // end llvm namespace
464
465#endif
466