AnalysisDeclContext.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //== AnalysisDeclContext.cpp - Analysis context for Path Sens analysis -*- 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 AnalysisDeclContext, a class that manages the analysis context
  11. // data for path sensitive analysis.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/DeclTemplate.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "clang/AST/StmtVisitor.h"
  19. #include "clang/Analysis/Analyses/LiveVariables.h"
  20. #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
  21. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  22. #include "clang/Analysis/AnalysisContext.h"
  23. #include "clang/Analysis/CFG.h"
  24. #include "clang/Analysis/CFGStmtMap.h"
  25. #include "clang/Analysis/Support/BumpVector.h"
  26. #include "llvm/Support/SaveAndRestore.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. using namespace clang;
  30. typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap;
  31. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  32. const Decl *d,
  33. idx::TranslationUnit *tu,
  34. const CFG::BuildOptions &buildOptions)
  35. : Manager(Mgr),
  36. D(d),
  37. TU(tu),
  38. cfgBuildOptions(buildOptions),
  39. forcedBlkExprs(0),
  40. builtCFG(false),
  41. builtCompleteCFG(false),
  42. ReferencedBlockVars(0),
  43. ManagedAnalyses(0)
  44. {
  45. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  46. }
  47. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  48. const Decl *d,
  49. idx::TranslationUnit *tu)
  50. : Manager(Mgr),
  51. D(d),
  52. TU(tu),
  53. forcedBlkExprs(0),
  54. builtCFG(false),
  55. builtCompleteCFG(false),
  56. ReferencedBlockVars(0),
  57. ManagedAnalyses(0)
  58. {
  59. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  60. }
  61. AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
  62. bool addImplicitDtors,
  63. bool addInitializers) {
  64. cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
  65. cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
  66. cfgBuildOptions.AddInitializers = addInitializers;
  67. }
  68. void AnalysisDeclContextManager::clear() {
  69. for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
  70. delete I->second;
  71. Contexts.clear();
  72. }
  73. Stmt *AnalysisDeclContext::getBody() const {
  74. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  75. return FD->getBody();
  76. else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  77. return MD->getBody();
  78. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
  79. return BD->getBody();
  80. else if (const FunctionTemplateDecl *FunTmpl
  81. = dyn_cast_or_null<FunctionTemplateDecl>(D))
  82. return FunTmpl->getTemplatedDecl()->getBody();
  83. llvm_unreachable("unknown code decl");
  84. }
  85. const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
  86. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  87. return MD->getSelfDecl();
  88. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  89. // See if 'self' was captured by the block.
  90. for (BlockDecl::capture_const_iterator it = BD->capture_begin(),
  91. et = BD->capture_end(); it != et; ++it) {
  92. const VarDecl *VD = it->getVariable();
  93. if (VD->getName() == "self")
  94. return dyn_cast<ImplicitParamDecl>(VD);
  95. }
  96. }
  97. return NULL;
  98. }
  99. void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
  100. if (!forcedBlkExprs)
  101. forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
  102. // Default construct an entry for 'stmt'.
  103. if (const Expr *e = dyn_cast<Expr>(stmt))
  104. stmt = e->IgnoreParens();
  105. (void) (*forcedBlkExprs)[stmt];
  106. }
  107. const CFGBlock *
  108. AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
  109. assert(forcedBlkExprs);
  110. if (const Expr *e = dyn_cast<Expr>(stmt))
  111. stmt = e->IgnoreParens();
  112. CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
  113. forcedBlkExprs->find(stmt);
  114. assert(itr != forcedBlkExprs->end());
  115. return itr->second;
  116. }
  117. CFG *AnalysisDeclContext::getCFG() {
  118. if (!cfgBuildOptions.PruneTriviallyFalseEdges)
  119. return getUnoptimizedCFG();
  120. if (!builtCFG) {
  121. cfg.reset(CFG::buildCFG(D, getBody(),
  122. &D->getASTContext(), cfgBuildOptions));
  123. // Even when the cfg is not successfully built, we don't
  124. // want to try building it again.
  125. builtCFG = true;
  126. }
  127. return cfg.get();
  128. }
  129. CFG *AnalysisDeclContext::getUnoptimizedCFG() {
  130. if (!builtCompleteCFG) {
  131. SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
  132. false);
  133. completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(),
  134. cfgBuildOptions));
  135. // Even when the cfg is not successfully built, we don't
  136. // want to try building it again.
  137. builtCompleteCFG = true;
  138. }
  139. return completeCFG.get();
  140. }
  141. CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
  142. if (cfgStmtMap)
  143. return cfgStmtMap.get();
  144. if (CFG *c = getCFG()) {
  145. cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
  146. return cfgStmtMap.get();
  147. }
  148. return 0;
  149. }
  150. CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
  151. if (CFA)
  152. return CFA.get();
  153. if (CFG *c = getCFG()) {
  154. CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
  155. return CFA.get();
  156. }
  157. return 0;
  158. }
  159. void AnalysisDeclContext::dumpCFG(bool ShowColors) {
  160. getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
  161. }
  162. ParentMap &AnalysisDeclContext::getParentMap() {
  163. if (!PM)
  164. PM.reset(new ParentMap(getBody()));
  165. return *PM;
  166. }
  167. PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
  168. if (!PCA)
  169. PCA.reset(new PseudoConstantAnalysis(getBody()));
  170. return PCA.get();
  171. }
  172. AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D,
  173. idx::TranslationUnit *TU) {
  174. AnalysisDeclContext *&AC = Contexts[D];
  175. if (!AC)
  176. AC = new AnalysisDeclContext(this, D, TU, cfgBuildOptions);
  177. return AC;
  178. }
  179. const StackFrameContext *
  180. AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
  181. const CFGBlock *Blk, unsigned Idx) {
  182. return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
  183. }
  184. LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
  185. assert(Manager &&
  186. "Cannot create LocationContexts without an AnalysisDeclContextManager!");
  187. return Manager->getLocationContextManager();
  188. }
  189. //===----------------------------------------------------------------------===//
  190. // FoldingSet profiling.
  191. //===----------------------------------------------------------------------===//
  192. void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
  193. ContextKind ck,
  194. AnalysisDeclContext *ctx,
  195. const LocationContext *parent,
  196. const void *data) {
  197. ID.AddInteger(ck);
  198. ID.AddPointer(ctx);
  199. ID.AddPointer(parent);
  200. ID.AddPointer(data);
  201. }
  202. void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
  203. Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
  204. }
  205. void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
  206. Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
  207. }
  208. void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
  209. Profile(ID, getAnalysisDeclContext(), getParent(), BD);
  210. }
  211. //===----------------------------------------------------------------------===//
  212. // LocationContext creation.
  213. //===----------------------------------------------------------------------===//
  214. template <typename LOC, typename DATA>
  215. const LOC*
  216. LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
  217. const LocationContext *parent,
  218. const DATA *d) {
  219. llvm::FoldingSetNodeID ID;
  220. LOC::Profile(ID, ctx, parent, d);
  221. void *InsertPos;
  222. LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  223. if (!L) {
  224. L = new LOC(ctx, parent, d);
  225. Contexts.InsertNode(L, InsertPos);
  226. }
  227. return L;
  228. }
  229. const StackFrameContext*
  230. LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
  231. const LocationContext *parent,
  232. const Stmt *s,
  233. const CFGBlock *blk, unsigned idx) {
  234. llvm::FoldingSetNodeID ID;
  235. StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
  236. void *InsertPos;
  237. StackFrameContext *L =
  238. cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  239. if (!L) {
  240. L = new StackFrameContext(ctx, parent, s, blk, idx);
  241. Contexts.InsertNode(L, InsertPos);
  242. }
  243. return L;
  244. }
  245. const ScopeContext *
  246. LocationContextManager::getScope(AnalysisDeclContext *ctx,
  247. const LocationContext *parent,
  248. const Stmt *s) {
  249. return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
  250. }
  251. //===----------------------------------------------------------------------===//
  252. // LocationContext methods.
  253. //===----------------------------------------------------------------------===//
  254. const StackFrameContext *LocationContext::getCurrentStackFrame() const {
  255. const LocationContext *LC = this;
  256. while (LC) {
  257. if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
  258. return SFC;
  259. LC = LC->getParent();
  260. }
  261. return NULL;
  262. }
  263. const StackFrameContext *
  264. LocationContext::getStackFrameForDeclContext(const DeclContext *DC) const {
  265. const LocationContext *LC = this;
  266. while (LC) {
  267. if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) {
  268. if (cast<DeclContext>(SFC->getDecl()) == DC)
  269. return SFC;
  270. }
  271. LC = LC->getParent();
  272. }
  273. return NULL;
  274. }
  275. bool LocationContext::isParentOf(const LocationContext *LC) const {
  276. do {
  277. const LocationContext *Parent = LC->getParent();
  278. if (Parent == this)
  279. return true;
  280. else
  281. LC = Parent;
  282. } while (LC);
  283. return false;
  284. }
  285. //===----------------------------------------------------------------------===//
  286. // Lazily generated map to query the external variables referenced by a Block.
  287. //===----------------------------------------------------------------------===//
  288. namespace {
  289. class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
  290. BumpVector<const VarDecl*> &BEVals;
  291. BumpVectorContext &BC;
  292. llvm::SmallPtrSet<const VarDecl*, 4> Visited;
  293. llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
  294. public:
  295. FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
  296. BumpVectorContext &bc)
  297. : BEVals(bevals), BC(bc) {}
  298. bool IsTrackedDecl(const VarDecl *VD) {
  299. const DeclContext *DC = VD->getDeclContext();
  300. return IgnoredContexts.count(DC) == 0;
  301. }
  302. void VisitStmt(Stmt *S) {
  303. for (Stmt::child_range I = S->children(); I; ++I)
  304. if (Stmt *child = *I)
  305. Visit(child);
  306. }
  307. void VisitDeclRefExpr(DeclRefExpr *DR) {
  308. // Non-local variables are also directly modified.
  309. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  310. if (!VD->hasLocalStorage()) {
  311. if (Visited.insert(VD))
  312. BEVals.push_back(VD, BC);
  313. } else if (DR->refersToEnclosingLocal()) {
  314. if (Visited.insert(VD) && IsTrackedDecl(VD))
  315. BEVals.push_back(VD, BC);
  316. }
  317. }
  318. }
  319. void VisitBlockExpr(BlockExpr *BR) {
  320. // Blocks containing blocks can transitively capture more variables.
  321. IgnoredContexts.insert(BR->getBlockDecl());
  322. Visit(BR->getBlockDecl()->getBody());
  323. }
  324. void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
  325. for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
  326. et = PE->semantics_end(); it != et; ++it) {
  327. Expr *Semantic = *it;
  328. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  329. Semantic = OVE->getSourceExpr();
  330. Visit(Semantic);
  331. }
  332. }
  333. };
  334. } // end anonymous namespace
  335. typedef BumpVector<const VarDecl*> DeclVec;
  336. static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
  337. void *&Vec,
  338. llvm::BumpPtrAllocator &A) {
  339. if (Vec)
  340. return (DeclVec*) Vec;
  341. BumpVectorContext BC(A);
  342. DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
  343. new (BV) DeclVec(BC, 10);
  344. // Find the referenced variables.
  345. FindBlockDeclRefExprsVals F(*BV, BC);
  346. F.Visit(BD->getBody());
  347. Vec = BV;
  348. return BV;
  349. }
  350. std::pair<AnalysisDeclContext::referenced_decls_iterator,
  351. AnalysisDeclContext::referenced_decls_iterator>
  352. AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
  353. if (!ReferencedBlockVars)
  354. ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
  355. DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
  356. return std::make_pair(V->begin(), V->end());
  357. }
  358. ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
  359. if (!ManagedAnalyses)
  360. ManagedAnalyses = new ManagedAnalysisMap();
  361. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  362. return (*M)[tag];
  363. }
  364. //===----------------------------------------------------------------------===//
  365. // Cleanup.
  366. //===----------------------------------------------------------------------===//
  367. ManagedAnalysis::~ManagedAnalysis() {}
  368. AnalysisDeclContext::~AnalysisDeclContext() {
  369. delete forcedBlkExprs;
  370. delete ReferencedBlockVars;
  371. // Release the managed analyses.
  372. if (ManagedAnalyses) {
  373. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  374. for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I)
  375. delete I->second;
  376. delete M;
  377. }
  378. }
  379. AnalysisDeclContextManager::~AnalysisDeclContextManager() {
  380. for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
  381. delete I->second;
  382. }
  383. LocationContext::~LocationContext() {}
  384. LocationContextManager::~LocationContextManager() {
  385. clear();
  386. }
  387. void LocationContextManager::clear() {
  388. for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
  389. E = Contexts.end(); I != E; ) {
  390. LocationContext *LC = &*I;
  391. ++I;
  392. delete LC;
  393. }
  394. Contexts.clear();
  395. }