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