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