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