ExplodedGraph.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //=-- ExplodedGraph.cpp - 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. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  16. #include "clang/AST/Stmt.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include <vector>
  22. using namespace clang;
  23. using namespace ento;
  24. //===----------------------------------------------------------------------===//
  25. // Node auditing.
  26. //===----------------------------------------------------------------------===//
  27. // An out of line virtual method to provide a home for the class vtable.
  28. ExplodedNode::Auditor::~Auditor() {}
  29. #ifndef NDEBUG
  30. static ExplodedNode::Auditor* NodeAuditor = 0;
  31. #endif
  32. void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
  33. #ifndef NDEBUG
  34. NodeAuditor = A;
  35. #endif
  36. }
  37. //===----------------------------------------------------------------------===//
  38. // Cleanup.
  39. //===----------------------------------------------------------------------===//
  40. static const unsigned CounterTop = 1000;
  41. ExplodedGraph::ExplodedGraph()
  42. : NumNodes(0), reclaimNodes(false), reclaimCounter(CounterTop) {}
  43. ExplodedGraph::~ExplodedGraph() {}
  44. //===----------------------------------------------------------------------===//
  45. // Node reclamation.
  46. //===----------------------------------------------------------------------===//
  47. bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
  48. // Reclaimn all nodes that match *all* the following criteria:
  49. //
  50. // (1) 1 predecessor (that has one successor)
  51. // (2) 1 successor (that has one predecessor)
  52. // (3) The ProgramPoint is for a PostStmt.
  53. // (4) There is no 'tag' for the ProgramPoint.
  54. // (5) The 'store' is the same as the predecessor.
  55. // (6) The 'GDM' is the same as the predecessor.
  56. // (7) The LocationContext is the same as the predecessor.
  57. // (8) The PostStmt is for a non-consumed Stmt or Expr.
  58. // Conditions 1 and 2.
  59. if (node->pred_size() != 1 || node->succ_size() != 1)
  60. return false;
  61. const ExplodedNode *pred = *(node->pred_begin());
  62. if (pred->succ_size() != 1)
  63. return false;
  64. const ExplodedNode *succ = *(node->succ_begin());
  65. if (succ->pred_size() != 1)
  66. return false;
  67. // Condition 3.
  68. ProgramPoint progPoint = node->getLocation();
  69. if (!isa<PostStmt>(progPoint) ||
  70. (isa<CallEnter>(progPoint) || isa<CallExit>(progPoint)))
  71. return false;
  72. // Condition 4.
  73. PostStmt ps = cast<PostStmt>(progPoint);
  74. if (ps.getTag())
  75. return false;
  76. if (isa<BinaryOperator>(ps.getStmt()))
  77. return false;
  78. // Conditions 5, 6, and 7.
  79. ProgramStateRef state = node->getState();
  80. ProgramStateRef pred_state = pred->getState();
  81. if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
  82. progPoint.getLocationContext() != pred->getLocationContext())
  83. return false;
  84. // Condition 8.
  85. if (const Expr *Ex = dyn_cast<Expr>(ps.getStmt())) {
  86. ParentMap &PM = progPoint.getLocationContext()->getParentMap();
  87. if (!PM.isConsumedExpr(Ex))
  88. return false;
  89. }
  90. return true;
  91. }
  92. void ExplodedGraph::collectNode(ExplodedNode *node) {
  93. // Removing a node means:
  94. // (a) changing the predecessors successor to the successor of this node
  95. // (b) changing the successors predecessor to the predecessor of this node
  96. // (c) Putting 'node' onto freeNodes.
  97. assert(node->pred_size() == 1 || node->succ_size() == 1);
  98. ExplodedNode *pred = *(node->pred_begin());
  99. ExplodedNode *succ = *(node->succ_begin());
  100. pred->replaceSuccessor(succ);
  101. succ->replacePredecessor(pred);
  102. FreeNodes.push_back(node);
  103. Nodes.RemoveNode(node);
  104. --NumNodes;
  105. node->~ExplodedNode();
  106. }
  107. void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
  108. if (ChangedNodes.empty())
  109. return;
  110. // Only periodically relcaim nodes so that we can build up a set of
  111. // nodes that meet the reclamation criteria. Freshly created nodes
  112. // by definition have no successor, and thus cannot be reclaimed (see below).
  113. assert(reclaimCounter > 0);
  114. if (--reclaimCounter != 0)
  115. return;
  116. reclaimCounter = CounterTop;
  117. for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
  118. it != et; ++it) {
  119. ExplodedNode *node = *it;
  120. if (shouldCollect(node))
  121. collectNode(node);
  122. }
  123. ChangedNodes.clear();
  124. }
  125. //===----------------------------------------------------------------------===//
  126. // ExplodedNode.
  127. //===----------------------------------------------------------------------===//
  128. static inline BumpVector<ExplodedNode*>& getVector(void *P) {
  129. return *reinterpret_cast<BumpVector<ExplodedNode*>*>(P);
  130. }
  131. void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
  132. assert (!V->isSink());
  133. Preds.addNode(V, G);
  134. V->Succs.addNode(this, G);
  135. #ifndef NDEBUG
  136. if (NodeAuditor) NodeAuditor->AddEdge(V, this);
  137. #endif
  138. }
  139. void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
  140. assert(getKind() == Size1);
  141. P = reinterpret_cast<uintptr_t>(node);
  142. assert(getKind() == Size1);
  143. }
  144. void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
  145. assert((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0);
  146. assert(!getFlag());
  147. if (getKind() == Size1) {
  148. if (ExplodedNode *NOld = getNode()) {
  149. BumpVectorContext &Ctx = G.getNodeAllocator();
  150. BumpVector<ExplodedNode*> *V =
  151. G.getAllocator().Allocate<BumpVector<ExplodedNode*> >();
  152. new (V) BumpVector<ExplodedNode*>(Ctx, 4);
  153. assert((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0);
  154. V->push_back(NOld, Ctx);
  155. V->push_back(N, Ctx);
  156. P = reinterpret_cast<uintptr_t>(V) | SizeOther;
  157. assert(getPtr() == (void*) V);
  158. assert(getKind() == SizeOther);
  159. }
  160. else {
  161. P = reinterpret_cast<uintptr_t>(N);
  162. assert(getKind() == Size1);
  163. }
  164. }
  165. else {
  166. assert(getKind() == SizeOther);
  167. getVector(getPtr()).push_back(N, G.getNodeAllocator());
  168. }
  169. }
  170. unsigned ExplodedNode::NodeGroup::size() const {
  171. if (getFlag())
  172. return 0;
  173. if (getKind() == Size1)
  174. return getNode() ? 1 : 0;
  175. else
  176. return getVector(getPtr()).size();
  177. }
  178. ExplodedNode **ExplodedNode::NodeGroup::begin() const {
  179. if (getFlag())
  180. return NULL;
  181. if (getKind() == Size1)
  182. return (ExplodedNode**) (getPtr() ? &P : NULL);
  183. else
  184. return const_cast<ExplodedNode**>(&*(getVector(getPtr()).begin()));
  185. }
  186. ExplodedNode** ExplodedNode::NodeGroup::end() const {
  187. if (getFlag())
  188. return NULL;
  189. if (getKind() == Size1)
  190. return (ExplodedNode**) (getPtr() ? &P+1 : NULL);
  191. else {
  192. // Dereferencing end() is undefined behaviour. The vector is not empty, so
  193. // we can dereference the last elem and then add 1 to the result.
  194. return const_cast<ExplodedNode**>(getVector(getPtr()).end());
  195. }
  196. }
  197. ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
  198. ProgramStateRef State,
  199. bool IsSink,
  200. bool* IsNew) {
  201. // Profile 'State' to determine if we already have an existing node.
  202. llvm::FoldingSetNodeID profile;
  203. void *InsertPos = 0;
  204. NodeTy::Profile(profile, L, State, IsSink);
  205. NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
  206. if (!V) {
  207. if (!FreeNodes.empty()) {
  208. V = FreeNodes.back();
  209. FreeNodes.pop_back();
  210. }
  211. else {
  212. // Allocate a new node.
  213. V = (NodeTy*) getAllocator().Allocate<NodeTy>();
  214. }
  215. new (V) NodeTy(L, State, IsSink);
  216. if (reclaimNodes)
  217. ChangedNodes.push_back(V);
  218. // Insert the node into the node set and return it.
  219. Nodes.InsertNode(V, InsertPos);
  220. ++NumNodes;
  221. if (IsNew) *IsNew = true;
  222. }
  223. else
  224. if (IsNew) *IsNew = false;
  225. return V;
  226. }
  227. std::pair<ExplodedGraph*, InterExplodedGraphMap*>
  228. ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
  229. llvm::DenseMap<const void*, const void*> *InverseMap) const {
  230. if (NBeg == NEnd)
  231. return std::make_pair((ExplodedGraph*) 0,
  232. (InterExplodedGraphMap*) 0);
  233. assert (NBeg < NEnd);
  234. OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
  235. ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap);
  236. return std::make_pair(static_cast<ExplodedGraph*>(G), M.take());
  237. }
  238. ExplodedGraph*
  239. ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources,
  240. const ExplodedNode* const* EndSources,
  241. InterExplodedGraphMap* M,
  242. llvm::DenseMap<const void*, const void*> *InverseMap) const {
  243. typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
  244. Pass1Ty Pass1;
  245. typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty;
  246. Pass2Ty& Pass2 = M->M;
  247. SmallVector<const ExplodedNode*, 10> WL1, WL2;
  248. // ===- Pass 1 (reverse DFS) -===
  249. for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) {
  250. assert(*I);
  251. WL1.push_back(*I);
  252. }
  253. // Process the first worklist until it is empty. Because it is a std::list
  254. // it acts like a FIFO queue.
  255. while (!WL1.empty()) {
  256. const ExplodedNode *N = WL1.back();
  257. WL1.pop_back();
  258. // Have we already visited this node? If so, continue to the next one.
  259. if (Pass1.count(N))
  260. continue;
  261. // Otherwise, mark this node as visited.
  262. Pass1.insert(N);
  263. // If this is a root enqueue it to the second worklist.
  264. if (N->Preds.empty()) {
  265. WL2.push_back(N);
  266. continue;
  267. }
  268. // Visit our predecessors and enqueue them.
  269. for (ExplodedNode** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I)
  270. WL1.push_back(*I);
  271. }
  272. // We didn't hit a root? Return with a null pointer for the new graph.
  273. if (WL2.empty())
  274. return 0;
  275. // Create an empty graph.
  276. ExplodedGraph* G = MakeEmptyGraph();
  277. // ===- Pass 2 (forward DFS to construct the new graph) -===
  278. while (!WL2.empty()) {
  279. const ExplodedNode *N = WL2.back();
  280. WL2.pop_back();
  281. // Skip this node if we have already processed it.
  282. if (Pass2.find(N) != Pass2.end())
  283. continue;
  284. // Create the corresponding node in the new graph and record the mapping
  285. // from the old node to the new node.
  286. ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0);
  287. Pass2[N] = NewN;
  288. // Also record the reverse mapping from the new node to the old node.
  289. if (InverseMap) (*InverseMap)[NewN] = N;
  290. // If this node is a root, designate it as such in the graph.
  291. if (N->Preds.empty())
  292. G->addRoot(NewN);
  293. // In the case that some of the intended predecessors of NewN have already
  294. // been created, we should hook them up as predecessors.
  295. // Walk through the predecessors of 'N' and hook up their corresponding
  296. // nodes in the new graph (if any) to the freshly created node.
  297. for (ExplodedNode **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) {
  298. Pass2Ty::iterator PI = Pass2.find(*I);
  299. if (PI == Pass2.end())
  300. continue;
  301. NewN->addPredecessor(PI->second, *G);
  302. }
  303. // In the case that some of the intended successors of NewN have already
  304. // been created, we should hook them up as successors. Otherwise, enqueue
  305. // the new nodes from the original graph that should have nodes created
  306. // in the new graph.
  307. for (ExplodedNode **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) {
  308. Pass2Ty::iterator PI = Pass2.find(*I);
  309. if (PI != Pass2.end()) {
  310. PI->second->addPredecessor(NewN, *G);
  311. continue;
  312. }
  313. // Enqueue nodes to the worklist that were marked during pass 1.
  314. if (Pass1.count(*I))
  315. WL2.push_back(*I);
  316. }
  317. }
  318. return G;
  319. }
  320. void InterExplodedGraphMap::anchor() { }
  321. ExplodedNode*
  322. InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
  323. llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =
  324. M.find(N);
  325. return I == M.end() ? 0 : I->second;
  326. }