AnalysisDeclContext.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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/Analysis/AnalysisContext.h"
  15. #include "BodyFarm.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/ParentMap.h"
  21. #include "clang/AST/StmtVisitor.h"
  22. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  23. #include "clang/Analysis/Analyses/LiveVariables.h"
  24. #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
  25. #include "clang/Analysis/CFG.h"
  26. #include "clang/Analysis/CFGStmtMap.h"
  27. #include "clang/Analysis/Support/BumpVector.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/SaveAndRestore.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. using namespace clang;
  33. typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap;
  34. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  35. const Decl *d,
  36. const CFG::BuildOptions &buildOptions)
  37. : Manager(Mgr),
  38. D(d),
  39. cfgBuildOptions(buildOptions),
  40. forcedBlkExprs(nullptr),
  41. builtCFG(false),
  42. builtCompleteCFG(false),
  43. ReferencedBlockVars(nullptr),
  44. ManagedAnalyses(nullptr)
  45. {
  46. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  47. }
  48. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  49. const Decl *d)
  50. : Manager(Mgr),
  51. D(d),
  52. forcedBlkExprs(nullptr),
  53. builtCFG(false),
  54. builtCompleteCFG(false),
  55. ReferencedBlockVars(nullptr),
  56. ManagedAnalyses(nullptr)
  57. {
  58. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  59. }
  60. AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
  61. bool addImplicitDtors,
  62. bool addInitializers,
  63. bool addTemporaryDtors,
  64. bool synthesizeBodies,
  65. bool addStaticInitBranch,
  66. bool addCXXNewAllocator,
  67. CodeInjector *injector)
  68. : Injector(injector), SynthesizeBodies(synthesizeBodies)
  69. {
  70. cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
  71. cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
  72. cfgBuildOptions.AddInitializers = addInitializers;
  73. cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
  74. cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
  75. cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
  76. }
  77. void AnalysisDeclContextManager::clear() {
  78. llvm::DeleteContainerSeconds(Contexts);
  79. }
  80. static BodyFarm &getBodyFarm(ASTContext &C, CodeInjector *injector = nullptr) {
  81. static BodyFarm *BF = new BodyFarm(C, injector);
  82. return *BF;
  83. }
  84. Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
  85. IsAutosynthesized = false;
  86. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  87. Stmt *Body = FD->getBody();
  88. if (!Body && Manager && Manager->synthesizeBodies()) {
  89. Body = getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(FD);
  90. if (Body)
  91. IsAutosynthesized = true;
  92. }
  93. return Body;
  94. }
  95. else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  96. Stmt *Body = MD->getBody();
  97. if (!Body && Manager && Manager->synthesizeBodies()) {
  98. Body = getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(MD);
  99. if (Body)
  100. IsAutosynthesized = true;
  101. }
  102. return Body;
  103. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
  104. return BD->getBody();
  105. else if (const FunctionTemplateDecl *FunTmpl
  106. = dyn_cast_or_null<FunctionTemplateDecl>(D))
  107. return FunTmpl->getTemplatedDecl()->getBody();
  108. llvm_unreachable("unknown code decl");
  109. }
  110. Stmt *AnalysisDeclContext::getBody() const {
  111. bool Tmp;
  112. return getBody(Tmp);
  113. }
  114. bool AnalysisDeclContext::isBodyAutosynthesized() const {
  115. bool Tmp;
  116. getBody(Tmp);
  117. return Tmp;
  118. }
  119. bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
  120. bool Tmp;
  121. Stmt *Body = getBody(Tmp);
  122. return Tmp && Body->getLocStart().isValid();
  123. }
  124. const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
  125. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  126. return MD->getSelfDecl();
  127. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  128. // See if 'self' was captured by the block.
  129. for (const auto &I : BD->captures()) {
  130. const VarDecl *VD = I.getVariable();
  131. if (VD->getName() == "self")
  132. return dyn_cast<ImplicitParamDecl>(VD);
  133. }
  134. }
  135. return nullptr;
  136. }
  137. void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
  138. if (!forcedBlkExprs)
  139. forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
  140. // Default construct an entry for 'stmt'.
  141. if (const Expr *e = dyn_cast<Expr>(stmt))
  142. stmt = e->IgnoreParens();
  143. (void) (*forcedBlkExprs)[stmt];
  144. }
  145. const CFGBlock *
  146. AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
  147. assert(forcedBlkExprs);
  148. if (const Expr *e = dyn_cast<Expr>(stmt))
  149. stmt = e->IgnoreParens();
  150. CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
  151. forcedBlkExprs->find(stmt);
  152. assert(itr != forcedBlkExprs->end());
  153. return itr->second;
  154. }
  155. /// Add each synthetic statement in the CFG to the parent map, using the
  156. /// source statement's parent.
  157. static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
  158. if (!TheCFG)
  159. return;
  160. for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
  161. E = TheCFG->synthetic_stmt_end();
  162. I != E; ++I) {
  163. PM.setParent(I->first, PM.getParent(I->second));
  164. }
  165. }
  166. CFG *AnalysisDeclContext::getCFG() {
  167. if (!cfgBuildOptions.PruneTriviallyFalseEdges)
  168. return getUnoptimizedCFG();
  169. if (!builtCFG) {
  170. cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
  171. // Even when the cfg is not successfully built, we don't
  172. // want to try building it again.
  173. builtCFG = true;
  174. if (PM)
  175. addParentsForSyntheticStmts(cfg.get(), *PM);
  176. // The Observer should only observe one build of the CFG.
  177. getCFGBuildOptions().Observer = nullptr;
  178. }
  179. return cfg.get();
  180. }
  181. CFG *AnalysisDeclContext::getUnoptimizedCFG() {
  182. if (!builtCompleteCFG) {
  183. SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
  184. false);
  185. completeCFG =
  186. CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
  187. // Even when the cfg is not successfully built, we don't
  188. // want to try building it again.
  189. builtCompleteCFG = true;
  190. if (PM)
  191. addParentsForSyntheticStmts(completeCFG.get(), *PM);
  192. // The Observer should only observe one build of the CFG.
  193. getCFGBuildOptions().Observer = nullptr;
  194. }
  195. return completeCFG.get();
  196. }
  197. CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
  198. if (cfgStmtMap)
  199. return cfgStmtMap.get();
  200. if (CFG *c = getCFG()) {
  201. cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
  202. return cfgStmtMap.get();
  203. }
  204. return nullptr;
  205. }
  206. CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
  207. if (CFA)
  208. return CFA.get();
  209. if (CFG *c = getCFG()) {
  210. CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
  211. return CFA.get();
  212. }
  213. return nullptr;
  214. }
  215. void AnalysisDeclContext::dumpCFG(bool ShowColors) {
  216. getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
  217. }
  218. ParentMap &AnalysisDeclContext::getParentMap() {
  219. if (!PM) {
  220. PM.reset(new ParentMap(getBody()));
  221. if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
  222. for (const auto *I : C->inits()) {
  223. PM->addStmt(I->getInit());
  224. }
  225. }
  226. if (builtCFG)
  227. addParentsForSyntheticStmts(getCFG(), *PM);
  228. if (builtCompleteCFG)
  229. addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
  230. }
  231. return *PM;
  232. }
  233. PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
  234. if (!PCA)
  235. PCA.reset(new PseudoConstantAnalysis(getBody()));
  236. return PCA.get();
  237. }
  238. AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
  239. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  240. // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
  241. // that has the body.
  242. FD->hasBody(FD);
  243. D = FD;
  244. }
  245. AnalysisDeclContext *&AC = Contexts[D];
  246. if (!AC)
  247. AC = new AnalysisDeclContext(this, D, cfgBuildOptions);
  248. return AC;
  249. }
  250. const StackFrameContext *
  251. AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
  252. const CFGBlock *Blk, unsigned Idx) {
  253. return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
  254. }
  255. const BlockInvocationContext *
  256. AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
  257. const clang::BlockDecl *BD,
  258. const void *ContextData) {
  259. return getLocationContextManager().getBlockInvocationContext(this, parent,
  260. BD, ContextData);
  261. }
  262. LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
  263. assert(Manager &&
  264. "Cannot create LocationContexts without an AnalysisDeclContextManager!");
  265. return Manager->getLocationContextManager();
  266. }
  267. //===----------------------------------------------------------------------===//
  268. // FoldingSet profiling.
  269. //===----------------------------------------------------------------------===//
  270. void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
  271. ContextKind ck,
  272. AnalysisDeclContext *ctx,
  273. const LocationContext *parent,
  274. const void *data) {
  275. ID.AddInteger(ck);
  276. ID.AddPointer(ctx);
  277. ID.AddPointer(parent);
  278. ID.AddPointer(data);
  279. }
  280. void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
  281. Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
  282. }
  283. void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
  284. Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
  285. }
  286. void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
  287. Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
  288. }
  289. //===----------------------------------------------------------------------===//
  290. // LocationContext creation.
  291. //===----------------------------------------------------------------------===//
  292. template <typename LOC, typename DATA>
  293. const LOC*
  294. LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
  295. const LocationContext *parent,
  296. const DATA *d) {
  297. llvm::FoldingSetNodeID ID;
  298. LOC::Profile(ID, ctx, parent, d);
  299. void *InsertPos;
  300. LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  301. if (!L) {
  302. L = new LOC(ctx, parent, d);
  303. Contexts.InsertNode(L, InsertPos);
  304. }
  305. return L;
  306. }
  307. const StackFrameContext*
  308. LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
  309. const LocationContext *parent,
  310. const Stmt *s,
  311. const CFGBlock *blk, unsigned idx) {
  312. llvm::FoldingSetNodeID ID;
  313. StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
  314. void *InsertPos;
  315. StackFrameContext *L =
  316. cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  317. if (!L) {
  318. L = new StackFrameContext(ctx, parent, s, blk, idx);
  319. Contexts.InsertNode(L, InsertPos);
  320. }
  321. return L;
  322. }
  323. const ScopeContext *
  324. LocationContextManager::getScope(AnalysisDeclContext *ctx,
  325. const LocationContext *parent,
  326. const Stmt *s) {
  327. return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
  328. }
  329. const BlockInvocationContext *
  330. LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
  331. const LocationContext *parent,
  332. const BlockDecl *BD,
  333. const void *ContextData) {
  334. llvm::FoldingSetNodeID ID;
  335. BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
  336. void *InsertPos;
  337. BlockInvocationContext *L =
  338. cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
  339. InsertPos));
  340. if (!L) {
  341. L = new BlockInvocationContext(ctx, parent, BD, ContextData);
  342. Contexts.InsertNode(L, InsertPos);
  343. }
  344. return L;
  345. }
  346. //===----------------------------------------------------------------------===//
  347. // LocationContext methods.
  348. //===----------------------------------------------------------------------===//
  349. const StackFrameContext *LocationContext::getCurrentStackFrame() const {
  350. const LocationContext *LC = this;
  351. while (LC) {
  352. if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
  353. return SFC;
  354. LC = LC->getParent();
  355. }
  356. return nullptr;
  357. }
  358. bool LocationContext::inTopFrame() const {
  359. return getCurrentStackFrame()->inTopFrame();
  360. }
  361. bool LocationContext::isParentOf(const LocationContext *LC) const {
  362. do {
  363. const LocationContext *Parent = LC->getParent();
  364. if (Parent == this)
  365. return true;
  366. else
  367. LC = Parent;
  368. } while (LC);
  369. return false;
  370. }
  371. void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
  372. ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
  373. PrintingPolicy PP(Ctx.getLangOpts());
  374. PP.TerseOutput = 1;
  375. unsigned Frame = 0;
  376. for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
  377. switch (LCtx->getKind()) {
  378. case StackFrame:
  379. OS << Indent << '#' << Frame++ << ' ';
  380. cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
  381. OS << '\n';
  382. break;
  383. case Scope:
  384. OS << Indent << " (scope)\n";
  385. break;
  386. case Block:
  387. OS << Indent << " (block context: "
  388. << cast<BlockInvocationContext>(LCtx)->getContextData()
  389. << ")\n";
  390. break;
  391. }
  392. }
  393. }
  394. LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
  395. dumpStack(llvm::errs());
  396. }
  397. //===----------------------------------------------------------------------===//
  398. // Lazily generated map to query the external variables referenced by a Block.
  399. //===----------------------------------------------------------------------===//
  400. namespace {
  401. class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
  402. BumpVector<const VarDecl*> &BEVals;
  403. BumpVectorContext &BC;
  404. llvm::SmallPtrSet<const VarDecl*, 4> Visited;
  405. llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
  406. public:
  407. FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
  408. BumpVectorContext &bc)
  409. : BEVals(bevals), BC(bc) {}
  410. void VisitStmt(Stmt *S) {
  411. for (Stmt *Child : S->children())
  412. if (Child)
  413. Visit(Child);
  414. }
  415. void VisitDeclRefExpr(DeclRefExpr *DR) {
  416. // Non-local variables are also directly modified.
  417. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  418. if (!VD->hasLocalStorage()) {
  419. if (Visited.insert(VD).second)
  420. BEVals.push_back(VD, BC);
  421. }
  422. }
  423. }
  424. void VisitBlockExpr(BlockExpr *BR) {
  425. // Blocks containing blocks can transitively capture more variables.
  426. IgnoredContexts.insert(BR->getBlockDecl());
  427. Visit(BR->getBlockDecl()->getBody());
  428. }
  429. void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
  430. for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
  431. et = PE->semantics_end(); it != et; ++it) {
  432. Expr *Semantic = *it;
  433. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  434. Semantic = OVE->getSourceExpr();
  435. Visit(Semantic);
  436. }
  437. }
  438. };
  439. } // end anonymous namespace
  440. typedef BumpVector<const VarDecl*> DeclVec;
  441. static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
  442. void *&Vec,
  443. llvm::BumpPtrAllocator &A) {
  444. if (Vec)
  445. return (DeclVec*) Vec;
  446. BumpVectorContext BC(A);
  447. DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
  448. new (BV) DeclVec(BC, 10);
  449. // Go through the capture list.
  450. for (const auto &CI : BD->captures()) {
  451. BV->push_back(CI.getVariable(), BC);
  452. }
  453. // Find the referenced global/static variables.
  454. FindBlockDeclRefExprsVals F(*BV, BC);
  455. F.Visit(BD->getBody());
  456. Vec = BV;
  457. return BV;
  458. }
  459. llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
  460. AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
  461. if (!ReferencedBlockVars)
  462. ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
  463. const DeclVec *V =
  464. LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
  465. return llvm::make_range(V->begin(), V->end());
  466. }
  467. ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
  468. if (!ManagedAnalyses)
  469. ManagedAnalyses = new ManagedAnalysisMap();
  470. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  471. return (*M)[tag];
  472. }
  473. //===----------------------------------------------------------------------===//
  474. // Cleanup.
  475. //===----------------------------------------------------------------------===//
  476. ManagedAnalysis::~ManagedAnalysis() {}
  477. AnalysisDeclContext::~AnalysisDeclContext() {
  478. delete forcedBlkExprs;
  479. delete ReferencedBlockVars;
  480. // Release the managed analyses.
  481. if (ManagedAnalyses) {
  482. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  483. llvm::DeleteContainerSeconds(*M);
  484. delete M;
  485. }
  486. }
  487. AnalysisDeclContextManager::~AnalysisDeclContextManager() {
  488. llvm::DeleteContainerSeconds(Contexts);
  489. }
  490. LocationContext::~LocationContext() {}
  491. LocationContextManager::~LocationContextManager() {
  492. clear();
  493. }
  494. void LocationContextManager::clear() {
  495. for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
  496. E = Contexts.end(); I != E; ) {
  497. LocationContext *LC = &*I;
  498. ++I;
  499. delete LC;
  500. }
  501. Contexts.clear();
  502. }