ExplodedGraph.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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/AST/ParentMap.h"
  16. #include "clang/AST/Stmt.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include <vector>
  24. using namespace clang;
  25. using namespace ento;
  26. //===----------------------------------------------------------------------===//
  27. // Node auditing.
  28. //===----------------------------------------------------------------------===//
  29. // An out of line virtual method to provide a home for the class vtable.
  30. ExplodedNode::Auditor::~Auditor() {}
  31. #ifndef NDEBUG
  32. static ExplodedNode::Auditor* NodeAuditor = 0;
  33. #endif
  34. void ExplodedNode::SetAuditor(ExplodedNode::Auditor* A) {
  35. #ifndef NDEBUG
  36. NodeAuditor = A;
  37. #endif
  38. }
  39. //===----------------------------------------------------------------------===//
  40. // Cleanup.
  41. //===----------------------------------------------------------------------===//
  42. ExplodedGraph::ExplodedGraph()
  43. : NumNodes(0), ReclaimNodeInterval(0) {}
  44. ExplodedGraph::~ExplodedGraph() {}
  45. //===----------------------------------------------------------------------===//
  46. // Node reclamation.
  47. //===----------------------------------------------------------------------===//
  48. bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
  49. // Reclaim all nodes that match *all* the following criteria:
  50. //
  51. // (1) 1 predecessor (that has one successor)
  52. // (2) 1 successor (that has one predecessor)
  53. // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
  54. // (4) There is no 'tag' for the ProgramPoint.
  55. // (5) The 'store' is the same as the predecessor.
  56. // (6) The 'GDM' is the same as the predecessor.
  57. // (7) The LocationContext is the same as the predecessor.
  58. // (8) Expressions that are *not* lvalue expressions.
  59. // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
  60. // (10) The successor is not a CallExpr StmtPoint (so that we would
  61. // be able to find it when retrying a call with no inlining).
  62. // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
  63. // Conditions 1 and 2.
  64. if (node->pred_size() != 1 || node->succ_size() != 1)
  65. return false;
  66. const ExplodedNode *pred = *(node->pred_begin());
  67. if (pred->succ_size() != 1)
  68. return false;
  69. const ExplodedNode *succ = *(node->succ_begin());
  70. if (succ->pred_size() != 1)
  71. return false;
  72. // Condition 3.
  73. ProgramPoint progPoint = node->getLocation();
  74. if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
  75. return false;
  76. // Condition 4.
  77. PostStmt ps = progPoint.castAs<PostStmt>();
  78. if (ps.getTag())
  79. return false;
  80. // Conditions 5, 6, and 7.
  81. ProgramStateRef state = node->getState();
  82. ProgramStateRef pred_state = pred->getState();
  83. if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
  84. progPoint.getLocationContext() != pred->getLocationContext())
  85. return false;
  86. // Condition 8.
  87. // Do not collect nodes for lvalue expressions since they are
  88. // used extensively for generating path diagnostics.
  89. const Expr *Ex = dyn_cast<Expr>(ps.getStmt());
  90. if (!Ex || Ex->isLValue())
  91. return false;
  92. // Condition 9.
  93. // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
  94. // diagnostic generation; specifically, so that we could anchor arrows
  95. // pointing to the beginning of statements (as written in code).
  96. ParentMap &PM = progPoint.getLocationContext()->getParentMap();
  97. if (!PM.isConsumedExpr(Ex))
  98. return false;
  99. // Condition 10.
  100. const ProgramPoint SuccLoc = succ->getLocation();
  101. if (Optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
  102. if (CallEvent::isCallStmt(SP->getStmt()))
  103. return false;
  104. return true;
  105. }
  106. void ExplodedGraph::collectNode(ExplodedNode *node) {
  107. // Removing a node means:
  108. // (a) changing the predecessors successor to the successor of this node
  109. // (b) changing the successors predecessor to the predecessor of this node
  110. // (c) Putting 'node' onto freeNodes.
  111. assert(node->pred_size() == 1 || node->succ_size() == 1);
  112. ExplodedNode *pred = *(node->pred_begin());
  113. ExplodedNode *succ = *(node->succ_begin());
  114. pred->replaceSuccessor(succ);
  115. succ->replacePredecessor(pred);
  116. FreeNodes.push_back(node);
  117. Nodes.RemoveNode(node);
  118. --NumNodes;
  119. node->~ExplodedNode();
  120. }
  121. void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
  122. if (ChangedNodes.empty())
  123. return;
  124. // Only periodically reclaim nodes so that we can build up a set of
  125. // nodes that meet the reclamation criteria. Freshly created nodes
  126. // by definition have no successor, and thus cannot be reclaimed (see below).
  127. assert(ReclaimCounter > 0);
  128. if (--ReclaimCounter != 0)
  129. return;
  130. ReclaimCounter = ReclaimNodeInterval;
  131. for (NodeVector::iterator it = ChangedNodes.begin(), et = ChangedNodes.end();
  132. it != et; ++it) {
  133. ExplodedNode *node = *it;
  134. if (shouldCollect(node))
  135. collectNode(node);
  136. }
  137. ChangedNodes.clear();
  138. }
  139. //===----------------------------------------------------------------------===//
  140. // ExplodedNode.
  141. //===----------------------------------------------------------------------===//
  142. // An NodeGroup's storage type is actually very much like a TinyPtrVector:
  143. // it can be either a pointer to a single ExplodedNode, or a pointer to a
  144. // BumpVector allocated with the ExplodedGraph's allocator. This allows the
  145. // common case of single-node NodeGroups to be implemented with no extra memory.
  146. //
  147. // Consequently, each of the NodeGroup methods have up to four cases to handle:
  148. // 1. The flag is set and this group does not actually contain any nodes.
  149. // 2. The group is empty, in which case the storage value is null.
  150. // 3. The group contains a single node.
  151. // 4. The group contains more than one node.
  152. typedef BumpVector<ExplodedNode *> ExplodedNodeVector;
  153. typedef llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *> GroupStorage;
  154. void ExplodedNode::addPredecessor(ExplodedNode *V, ExplodedGraph &G) {
  155. assert (!V->isSink());
  156. Preds.addNode(V, G);
  157. V->Succs.addNode(this, G);
  158. #ifndef NDEBUG
  159. if (NodeAuditor) NodeAuditor->AddEdge(V, this);
  160. #endif
  161. }
  162. void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
  163. assert(!getFlag());
  164. GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
  165. assert(Storage.is<ExplodedNode *>());
  166. Storage = node;
  167. assert(Storage.is<ExplodedNode *>());
  168. }
  169. void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
  170. assert(!getFlag());
  171. GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
  172. if (Storage.isNull()) {
  173. Storage = N;
  174. assert(Storage.is<ExplodedNode *>());
  175. return;
  176. }
  177. ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>();
  178. if (!V) {
  179. // Switch from single-node to multi-node representation.
  180. ExplodedNode *Old = Storage.get<ExplodedNode *>();
  181. BumpVectorContext &Ctx = G.getNodeAllocator();
  182. V = G.getAllocator().Allocate<ExplodedNodeVector>();
  183. new (V) ExplodedNodeVector(Ctx, 4);
  184. V->push_back(Old, Ctx);
  185. Storage = V;
  186. assert(!getFlag());
  187. assert(Storage.is<ExplodedNodeVector *>());
  188. }
  189. V->push_back(N, G.getNodeAllocator());
  190. }
  191. unsigned ExplodedNode::NodeGroup::size() const {
  192. if (getFlag())
  193. return 0;
  194. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  195. if (Storage.isNull())
  196. return 0;
  197. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  198. return V->size();
  199. return 1;
  200. }
  201. ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
  202. if (getFlag())
  203. return 0;
  204. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  205. if (Storage.isNull())
  206. return 0;
  207. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  208. return V->begin();
  209. return Storage.getAddrOfPtr1();
  210. }
  211. ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
  212. if (getFlag())
  213. return 0;
  214. const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
  215. if (Storage.isNull())
  216. return 0;
  217. if (ExplodedNodeVector *V = Storage.dyn_cast<ExplodedNodeVector *>())
  218. return V->end();
  219. return Storage.getAddrOfPtr1() + 1;
  220. }
  221. ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
  222. ProgramStateRef State,
  223. bool IsSink,
  224. bool* IsNew) {
  225. // Profile 'State' to determine if we already have an existing node.
  226. llvm::FoldingSetNodeID profile;
  227. void *InsertPos = 0;
  228. NodeTy::Profile(profile, L, State, IsSink);
  229. NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos);
  230. if (!V) {
  231. if (!FreeNodes.empty()) {
  232. V = FreeNodes.back();
  233. FreeNodes.pop_back();
  234. }
  235. else {
  236. // Allocate a new node.
  237. V = (NodeTy*) getAllocator().Allocate<NodeTy>();
  238. }
  239. new (V) NodeTy(L, State, IsSink);
  240. if (ReclaimNodeInterval)
  241. ChangedNodes.push_back(V);
  242. // Insert the node into the node set and return it.
  243. Nodes.InsertNode(V, InsertPos);
  244. ++NumNodes;
  245. if (IsNew) *IsNew = true;
  246. }
  247. else
  248. if (IsNew) *IsNew = false;
  249. return V;
  250. }
  251. std::pair<ExplodedGraph*, InterExplodedGraphMap*>
  252. ExplodedGraph::Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd,
  253. llvm::DenseMap<const void*, const void*> *InverseMap) const {
  254. if (NBeg == NEnd)
  255. return std::make_pair((ExplodedGraph*) 0,
  256. (InterExplodedGraphMap*) 0);
  257. assert (NBeg < NEnd);
  258. OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
  259. ExplodedGraph* G = TrimInternal(NBeg, NEnd, M.get(), InverseMap);
  260. return std::make_pair(static_cast<ExplodedGraph*>(G), M.take());
  261. }
  262. ExplodedGraph*
  263. ExplodedGraph::TrimInternal(const ExplodedNode* const* BeginSources,
  264. const ExplodedNode* const* EndSources,
  265. InterExplodedGraphMap* M,
  266. llvm::DenseMap<const void*, const void*> *InverseMap) const {
  267. typedef llvm::DenseSet<const ExplodedNode*> Pass1Ty;
  268. Pass1Ty Pass1;
  269. typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> Pass2Ty;
  270. Pass2Ty& Pass2 = M->M;
  271. SmallVector<const ExplodedNode*, 10> WL1, WL2;
  272. // ===- Pass 1 (reverse DFS) -===
  273. for (const ExplodedNode* const* I = BeginSources; I != EndSources; ++I) {
  274. if (*I)
  275. WL1.push_back(*I);
  276. }
  277. // Process the first worklist until it is empty. Because it is a std::list
  278. // it acts like a FIFO queue.
  279. while (!WL1.empty()) {
  280. const ExplodedNode *N = WL1.back();
  281. WL1.pop_back();
  282. // Have we already visited this node? If so, continue to the next one.
  283. if (Pass1.count(N))
  284. continue;
  285. // Otherwise, mark this node as visited.
  286. Pass1.insert(N);
  287. // If this is a root enqueue it to the second worklist.
  288. if (N->Preds.empty()) {
  289. WL2.push_back(N);
  290. continue;
  291. }
  292. // Visit our predecessors and enqueue them.
  293. for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
  294. I != E; ++I)
  295. WL1.push_back(*I);
  296. }
  297. // We didn't hit a root? Return with a null pointer for the new graph.
  298. if (WL2.empty())
  299. return 0;
  300. // Create an empty graph.
  301. ExplodedGraph* G = MakeEmptyGraph();
  302. // ===- Pass 2 (forward DFS to construct the new graph) -===
  303. while (!WL2.empty()) {
  304. const ExplodedNode *N = WL2.back();
  305. WL2.pop_back();
  306. // Skip this node if we have already processed it.
  307. if (Pass2.find(N) != Pass2.end())
  308. continue;
  309. // Create the corresponding node in the new graph and record the mapping
  310. // from the old node to the new node.
  311. ExplodedNode *NewN = G->getNode(N->getLocation(), N->State, N->isSink(), 0);
  312. Pass2[N] = NewN;
  313. // Also record the reverse mapping from the new node to the old node.
  314. if (InverseMap) (*InverseMap)[NewN] = N;
  315. // If this node is a root, designate it as such in the graph.
  316. if (N->Preds.empty())
  317. G->addRoot(NewN);
  318. // In the case that some of the intended predecessors of NewN have already
  319. // been created, we should hook them up as predecessors.
  320. // Walk through the predecessors of 'N' and hook up their corresponding
  321. // nodes in the new graph (if any) to the freshly created node.
  322. for (ExplodedNode::pred_iterator I = N->Preds.begin(), E = N->Preds.end();
  323. I != E; ++I) {
  324. Pass2Ty::iterator PI = Pass2.find(*I);
  325. if (PI == Pass2.end())
  326. continue;
  327. NewN->addPredecessor(PI->second, *G);
  328. }
  329. // In the case that some of the intended successors of NewN have already
  330. // been created, we should hook them up as successors. Otherwise, enqueue
  331. // the new nodes from the original graph that should have nodes created
  332. // in the new graph.
  333. for (ExplodedNode::succ_iterator I = N->Succs.begin(), E = N->Succs.end();
  334. I != E; ++I) {
  335. Pass2Ty::iterator PI = Pass2.find(*I);
  336. if (PI != Pass2.end()) {
  337. PI->second->addPredecessor(NewN, *G);
  338. continue;
  339. }
  340. // Enqueue nodes to the worklist that were marked during pass 1.
  341. if (Pass1.count(*I))
  342. WL2.push_back(*I);
  343. }
  344. }
  345. return G;
  346. }
  347. void InterExplodedGraphMap::anchor() { }
  348. ExplodedNode*
  349. InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
  350. llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =
  351. M.find(N);
  352. return I == M.end() ? 0 : I->second;
  353. }