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