clang API Documentation

ExplodedGraph.cpp
Go to the documentation of this file.
00001 //=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the template classes ExplodedNode and ExplodedGraph,
00011 //  which represent a path-sensitive, intra-procedural "exploded graph."
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
00016 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00017 #include "clang/AST/Stmt.h"
00018 #include "clang/AST/ParentMap.h"
00019 #include "llvm/ADT/DenseSet.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include <vector>
00023 
00024 using namespace clang;
00025 using namespace ento;
00026 
00027 //===----------------------------------------------------------------------===//
00028 // Node auditing.
00029 //===----------------------------------------------------------------------===//
00030 
00031 // An out of line virtual method to provide a home for the class vtable.
00032 ExplodedNode::Auditor::~Auditor() {}
00033 
00034 #ifndef NDEBUG
00035 static ExplodedNode::Auditor* NodeAuditor = 0;
00036 #endif
00037 
00038 void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
00039 #ifndef NDEBUG
00040   NodeAuditor = A;
00041 #endif
00042 }
00043 
00044 //===----------------------------------------------------------------------===//
00045 // Cleanup.
00046 //===----------------------------------------------------------------------===//
00047 
00048 static const unsigned CounterTop = 1000;
00049 
00050 ExplodedGraph::ExplodedGraph()
00051   : NumNodes(0), reclaimNodes(false), reclaimCounter(CounterTop) {}
00052 
00053 ExplodedGraph::~ExplodedGraph() {}
00054 
00055 //===----------------------------------------------------------------------===//
00056 // Node reclamation.
00057 //===----------------------------------------------------------------------===//
00058 
00059 bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
00060   // Reclaim all nodes that match *all* the following criteria:
00061   //
00062   // (1) 1 predecessor (that has one successor)
00063   // (2) 1 successor (that has one predecessor)
00064   // (3) The ProgramPoint is for a PostStmt.
00065   // (4) There is no 'tag' for the ProgramPoint.
00066   // (5) The 'store' is the same as the predecessor.
00067   // (6) The 'GDM' is the same as the predecessor.
00068   // (7) The LocationContext is the same as the predecessor.
00069   // (8) The PostStmt is for a non-consumed Stmt or Expr.
00070 
00071   // Conditions 1 and 2.
00072   if (node->pred_size() != 1 || node->succ_size() != 1)
00073     return false;
00074 
00075   const ExplodedNode *pred = *(node->pred_begin());
00076   if (pred->succ_size() != 1)
00077     return false;
00078   
00079   const ExplodedNode *succ = *(node->succ_begin());
00080   if (succ->pred_size() != 1)
00081     return false;
00082 
00083   // Condition 3.
00084   ProgramPoint progPoint = node->getLocation();
00085   if (!isa<PostStmt>(progPoint) ||
00086       (isa<CallEnter>(progPoint) ||
00087        isa<CallExitBegin>(progPoint) || isa<CallExitEnd>(progPoint)))
00088     return false;
00089 
00090   // Condition 4.
00091   PostStmt ps = cast<PostStmt>(progPoint);
00092   if (ps.getTag())
00093     return false;
00094   
00095   if (isa<BinaryOperator>(ps.getStmt()))
00096     return false;
00097 
00098   // Conditions 5, 6, and 7.
00099   ProgramStateRef state = node->getState();
00100   ProgramStateRef pred_state = pred->getState();    
00101   if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
00102       progPoint.getLocationContext() != pred->getLocationContext())
00103     return false;
00104   
00105   // Condition 8.
00106   if (const Expr *Ex = dyn_cast<Expr>(ps.getStmt())) {
00107     ParentMap &PM = progPoint.getLocationContext()->getParentMap();
00108     if (!PM.isConsumedExpr(Ex))
00109       return false;
00110   }
00111   
00112   return true; 
00113 }
00114 
00115 void ExplodedGraph::collectNode(ExplodedNode *node) {
00116   // Removing a node means:
00117   // (a) changing the predecessors successor to the successor of this node
00118   // (b) changing the successors predecessor to the predecessor of this node
00119   // (c) Putting 'node' onto freeNodes.
00120   assert(node->pred_size() == 1 || node->succ_size() == 1);
00121   ExplodedNode *pred = *(node->pred_begin());
00122   ExplodedNode *succ = *(node->succ_begin());
00123   pred->replaceSuccessor(succ);
00124   succ->replacePredecessor(pred);
00125   FreeNodes.push_back(node);
00126   Nodes.RemoveNode(node);
00127   --NumNodes;
00128   node->~ExplodedNode();  
00129 }
00130 
00131 void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
00132   if (ChangedNodes.empty())
00133     return;
00134 
00135   // Only periodically relcaim nodes so that we can build up a set of
00136   // nodes that meet the reclamation criteria.  Freshly created nodes
00137   // by definition have no successor, and thus cannot be reclaimed (see below).
00138   assert(reclaimCounter > 0);
00139   if (--reclaimCounter != 0)
00140     return;
00141   reclaimCounter = CounterTop;
00142 
00143   for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
00144        it != et; ++it) {
00145     ExplodedNode *node = *it;
00146     if (shouldCollect(node))
00147       collectNode(node);
00148   }
00149   ChangedNodes.clear();
00150 }
00151 
00152 //===----------------------------------------------------------------------===//
00153 // ExplodedNode.
00154 //===----------------------------------------------------------------------===//
00155 
00156 static inline BumpVector<ExplodedNode*>& getVector(void *P) {
00157   return *reinterpret_cast<BumpVector<ExplodedNode*>*>(P);
00158 }
00159 
00160 void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
00161   assert (!V->isSink());
00162   Preds.addNode(V, G);
00163   V->Succs.addNode(this, G);
00164 #ifndef NDEBUG
00165   if (NodeAuditor) NodeAuditor->AddEdge(V, this);
00166 #endif
00167 }
00168 
00169 void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
00170   assert(getKind() == Size1);
00171   P = reinterpret_cast<uintptr_t>(node);
00172   assert(getKind() == Size1);
00173 }
00174 
00175 void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
00176   assert((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0);
00177   assert(!getFlag());
00178 
00179   if (getKind() == Size1) {
00180     if (ExplodedNode *NOld = getNode()) {
00181       BumpVectorContext &Ctx = G.getNodeAllocator();
00182       BumpVector<ExplodedNode*> *V = 
00183         G.getAllocator().Allocate<BumpVector<ExplodedNode*> >();
00184       new (V) BumpVector<ExplodedNode*>(Ctx, 4);
00185       
00186       assert((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0);
00187       V->push_back(NOld, Ctx);
00188       V->push_back(N, Ctx);
00189       P = reinterpret_cast<uintptr_t>(V) | SizeOther;
00190       assert(getPtr() == (void*) V);
00191       assert(getKind() == SizeOther);
00192     }
00193     else {
00194       P = reinterpret_cast<uintptr_t>(N);
00195       assert(getKind() == Size1);
00196     }
00197   }
00198   else {
00199     assert(getKind() == SizeOther);
00200     getVector(getPtr()).push_back(N, G.getNodeAllocator());
00201   }
00202 }
00203 
00204 unsigned ExplodedNode::NodeGroup::size() const {
00205   if (getFlag())
00206     return 0;
00207 
00208   if (getKind() == Size1)
00209     return getNode() ? 1 : 0;
00210   else
00211     return getVector(getPtr()).size();
00212 }
00213 
00214 ExplodedNode **ExplodedNode::NodeGroup::begin() const {
00215   if (getFlag())
00216     return NULL;
00217 
00218   if (getKind() == Size1)
00219     return (ExplodedNode**) (getPtr() ? &P : NULL);
00220   else
00221     return const_cast<ExplodedNode**>(&*(getVector(getPtr()).begin()));
00222 }
00223 
00224 ExplodedNode** ExplodedNode::NodeGroup::end() const {
00225   if (getFlag())
00226     return NULL;
00227 
00228   if (getKind() == Size1)
00229     return (ExplodedNode**) (getPtr() ? &P+1 : NULL);
00230   else {
00231     // Dereferencing end() is undefined behaviour. The vector is not empty, so
00232     // we can dereference the last elem and then add 1 to the result.
00233     return const_cast<ExplodedNode**>(getVector(getPtr()).end());
00234   }
00235 }
00236 
00237 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
00238                                      ProgramStateRef State,
00239                                      bool IsSink,
00240                                      bool* IsNew) {
00241   // Profile 'State' to determine if we already have an existing node.
00242   llvm::FoldingSetNodeID profile;
00243   void *InsertPos = 0;
00244 
00245   NodeTy::Profile(profile, L, State, IsSink);
00246   NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
00247 
00248   if (!V) {
00249     if (!FreeNodes.empty()) {
00250       V = FreeNodes.back();
00251       FreeNodes.pop_back();
00252     }
00253     else {
00254       // Allocate a new node.
00255       V = (NodeTy*) getAllocator().Allocate<NodeTy>();
00256     }
00257 
00258     new (V) NodeTy(L, State, IsSink);
00259 
00260     if (reclaimNodes)
00261       ChangedNodes.push_back(V);
00262 
00263     // Insert the node into the node set and return it.
00264     Nodes.InsertNode(V, InsertPos);
00265     ++NumNodes;
00266 
00267     if (IsNew) *IsNew = true;
00268   }
00269   else
00270     if (IsNew) *IsNew = false;
00271 
00272   return V;
00273 }
00274 
00275 std::pair<ExplodedGraph*, InterExplodedGraphMap*>
00276 ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
00277                llvm::DenseMap<const void*, const void*> *InverseMap) const {
00278 
00279   if (NBeg == NEnd)
00280     return std::make_pair((ExplodedGraph*) 0,
00281                           (InterExplodedGraphMap*) 0);
00282 
00283   assert (NBeg < NEnd);
00284 
00285   OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
00286 
00287   ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap);
00288 
00289   return std::make_pair(static_cast<ExplodedGraph*>(G), M.take());
00290 }
00291 
00292 ExplodedGraph*
00293 ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources,
00294                             const ExplodedNode* const* EndSources,
00295                             InterExplodedGraphMap* M,
00296                    llvm::DenseMap<const void*, const void*> *InverseMap) const {
00297 
00298   typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
00299   Pass1Ty Pass1;
00300 
00301   typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty;
00302   Pass2Ty& Pass2 = M->M;
00303 
00304   SmallVector<const ExplodedNode*, 10> WL1, WL2;
00305 
00306   // ===- Pass 1 (reverse DFS) -===
00307   for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) {
00308     assert(*I);
00309     WL1.push_back(*I);
00310   }
00311 
00312   // Process the first worklist until it is empty.  Because it is a std::list
00313   // it acts like a FIFO queue.
00314   while (!WL1.empty()) {
00315     const ExplodedNode *N = WL1.back();
00316     WL1.pop_back();
00317 
00318     // Have we already visited this node?  If so, continue to the next one.
00319     if (Pass1.count(N))
00320       continue;
00321 
00322     // Otherwise, mark this node as visited.
00323     Pass1.insert(N);
00324 
00325     // If this is a root enqueue it to the second worklist.
00326     if (N->Preds.empty()) {
00327       WL2.push_back(N);
00328       continue;
00329     }
00330 
00331     // Visit our predecessors and enqueue them.
00332     for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I)
00333       WL1.push_back(*I);
00334   }
00335 
00336   // We didn't hit a root? Return with a null pointer for the new graph.
00337   if (WL2.empty())
00338     return 0;
00339 
00340   // Create an empty graph.
00341   ExplodedGraph* G = MakeEmptyGraph();
00342 
00343   // ===- Pass 2 (forward DFS to construct the new graph) -===
00344   while (!WL2.empty()) {
00345     const ExplodedNode *N = WL2.back();
00346     WL2.pop_back();
00347 
00348     // Skip this node if we have already processed it.
00349     if (Pass2.find(N) != Pass2.end())
00350       continue;
00351 
00352     // Create the corresponding node in the new graph and record the mapping
00353     // from the old node to the new node.
00354     ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0);
00355     Pass2[N] = NewN;
00356 
00357     // Also record the reverse mapping from the new node to the old node.
00358     if (InverseMap) (*InverseMap)[NewN] = N;
00359 
00360     // If this node is a root, designate it as such in the graph.
00361     if (N->Preds.empty())
00362       G->addRoot(NewN);
00363 
00364     // In the case that some of the intended predecessors of NewN have already
00365     // been created, we should hook them up as predecessors.
00366 
00367     // Walk through the predecessors of 'N' and hook up their corresponding
00368     // nodes in the new graph (if any) to the freshly created node.
00369     for (ExplodedNode **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) {
00370       Pass2Ty::iterator PI = Pass2.find(*I);
00371       if (PI == Pass2.end())
00372         continue;
00373 
00374       NewN->addPredecessor(PI->second, *G);
00375     }
00376 
00377     // In the case that some of the intended successors of NewN have already
00378     // been created, we should hook them up as successors.  Otherwise, enqueue
00379     // the new nodes from the original graph that should have nodes created
00380     // in the new graph.
00381     for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) {
00382       Pass2Ty::iterator PI = Pass2.find(*I);
00383       if (PI != Pass2.end()) {
00384         PI->second->addPredecessor(NewN, *G);
00385         continue;
00386       }
00387 
00388       // Enqueue nodes to the worklist that were marked during pass 1.
00389       if (Pass1.count(*I))
00390         WL2.push_back(*I);
00391     }
00392   }
00393 
00394   return G;
00395 }
00396 
00397 void InterExplodedGraphMap::anchor() { }
00398 
00399 ExplodedNode*
00400 InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
00401   llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =
00402     M.find(N);
00403 
00404   return I == M.end() ? 0 : I->second;
00405 }
00406