Extend the ValuesAtScope cache to cover all expressions, not just
[oota-llvm.git] / lib / Analysis / IPA / CallGraphSCCPass.cpp
1 //===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
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 implements the CallGraphSCCPass class, which is used for passes
11 // which are implemented as bottom-up traversals on the call graph.  Because
12 // there may be cycles in the call graph, passes of this type operate on the
13 // call-graph in SCC order: that is, they process function bottom-up, except for
14 // recursive functions, which they process all at once.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "cgscc-passmgr"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/ADT/SCCIterator.h"
22 #include "llvm/PassManagers.h"
23 #include "llvm/Function.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // CGPassManager
30 //
31 /// CGPassManager manages FPPassManagers and CalLGraphSCCPasses.
32
33 namespace {
34
35 class CGPassManager : public ModulePass, public PMDataManager {
36 public:
37   static char ID;
38   explicit CGPassManager(int Depth) 
39     : ModulePass(&ID), PMDataManager(Depth) { }
40
41   /// run - Execute all of the passes scheduled for execution.  Keep track of
42   /// whether any of the passes modifies the module, and if so, return true.
43   bool runOnModule(Module &M);
44
45   bool doInitialization(CallGraph &CG);
46   bool doFinalization(CallGraph &CG);
47
48   /// Pass Manager itself does not invalidate any analysis info.
49   void getAnalysisUsage(AnalysisUsage &Info) const {
50     // CGPassManager walks SCC and it needs CallGraph.
51     Info.addRequired<CallGraph>();
52     Info.setPreservesAll();
53   }
54
55   virtual const char *getPassName() const {
56     return "CallGraph Pass Manager";
57   }
58
59   // Print passes managed by this manager
60   void dumpPassStructure(unsigned Offset) {
61     errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
62     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
63       Pass *P = getContainedPass(Index);
64       P->dumpPassStructure(Offset + 1);
65       dumpLastUses(P, Offset+1);
66     }
67   }
68
69   Pass *getContainedPass(unsigned N) {
70     assert(N < PassVector.size() && "Pass number out of range!");
71     return static_cast<Pass *>(PassVector[N]);
72   }
73
74   virtual PassManagerType getPassManagerType() const { 
75     return PMT_CallGraphPassManager; 
76   }
77   
78 private:
79   bool RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,
80                     CallGraph &CG, bool &CallGraphUpToDate);
81   void RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC, CallGraph &CG);
82 };
83
84 } // end anonymous namespace.
85
86 char CGPassManager::ID = 0;
87
88 bool CGPassManager::RunPassOnSCC(Pass *P, std::vector<CallGraphNode*> &CurSCC,
89                                  CallGraph &CG, bool &CallGraphUpToDate) {
90   bool Changed = false;
91   if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass*>(P)) {
92     if (!CallGraphUpToDate) {
93       RefreshCallGraph(CurSCC, CG);
94       CallGraphUpToDate = true;
95     }
96     
97     StartPassTimer(P);
98     Changed = CGSP->runOnSCC(CurSCC);
99     StopPassTimer(P);
100     return Changed;
101   }
102   
103   StartPassTimer(P);
104   FPPassManager *FPP = dynamic_cast<FPPassManager *>(P);
105   assert(FPP && "Invalid CGPassManager member");
106   
107   // Run pass P on all functions in the current SCC.
108   for (unsigned i = 0, e = CurSCC.size(); i != e; ++i) {
109     if (Function *F = CurSCC[i]->getFunction()) {
110       dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
111       Changed |= FPP->runOnFunction(*F);
112     }
113   }
114   StopPassTimer(P);
115   
116   // The function pass(es) modified the IR, they may have clobbered the
117   // callgraph.
118   if (Changed && CallGraphUpToDate) {
119     DEBUG(errs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
120                  << P->getPassName() << '\n');
121     CallGraphUpToDate = false;
122   }
123   return Changed;
124 }
125
126 void CGPassManager::RefreshCallGraph(std::vector<CallGraphNode*> &CurSCC,
127                                      CallGraph &CG) {
128   DenseMap<Instruction*, CallGraphNode*> CallSites;
129   
130   DEBUG(errs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
131                << " nodes:\n";
132         for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)
133           CurSCC[i]->dump();
134         );
135
136   bool MadeChange = false;
137   
138   // Scan all functions in the SCC.
139   for (unsigned sccidx = 0, e = CurSCC.size(); sccidx != e; ++sccidx) {
140     CallGraphNode *CGN = CurSCC[sccidx];
141     Function *F = CGN->getFunction();
142     if (F == 0 || F->isDeclaration()) continue;
143     
144     // Walk the function body looking for call sites.  Sync up the call sites in
145     // CGN with those actually in the function.
146     
147     // Get the set of call sites currently in the function.
148     for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ++I){
149       assert(I->first.getInstruction() &&
150              "Call site record in function should not be abstract");
151       assert(!CallSites.count(I->first.getInstruction()) &&
152              "Call site occurs in node multiple times");
153       CallSites.insert(std::make_pair(I->first.getInstruction(),
154                                       I->second));
155     }
156     
157     // Loop over all of the instructions in the function, getting the callsites.
158     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
159       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
160         CallSite CS = CallSite::get(I);
161         if (!CS.getInstruction()) continue;
162         
163         // If this call site already existed in the callgraph, just verify it
164         // matches up to expectations and remove it from CallSites.
165         DenseMap<Instruction*, CallGraphNode*>::iterator ExistingIt =
166           CallSites.find(CS.getInstruction());
167         if (ExistingIt != CallSites.end()) {
168           CallGraphNode *ExistingNode = ExistingIt->second;
169
170           // Remove from CallSites since we have now seen it.
171           CallSites.erase(ExistingIt);
172           
173           // Verify that the callee is right.
174           if (ExistingNode->getFunction() == CS.getCalledFunction())
175             continue;
176           
177           // If not, we either went from a direct call to indirect, indirect to
178           // direct, or direct to different direct.
179           CallGraphNode *CalleeNode;
180           if (Function *Callee = CS.getCalledFunction())
181             CalleeNode = CG.getOrInsertFunction(Callee);
182           else
183             CalleeNode = CG.getCallsExternalNode();
184           
185           CGN->replaceCallSite(CS, CS, CalleeNode);
186           MadeChange = true;
187           continue;
188         }
189         
190         // If the call site didn't exist in the CGN yet, add it.  We assume that
191         // newly introduced call sites won't be indirect.  This could be fixed
192         // in the future.
193         CallGraphNode *CalleeNode;
194         if (Function *Callee = CS.getCalledFunction())
195           CalleeNode = CG.getOrInsertFunction(Callee);
196         else
197           CalleeNode = CG.getCallsExternalNode();
198         
199         CGN->addCalledFunction(CS, CalleeNode);
200         MadeChange = true;
201       }
202     
203     // After scanning this function, if we still have entries in callsites, then
204     // they are dangling pointers.  Crap.  Well, until we change CallGraph to
205     // use CallbackVH, we'll just zap them here.  When we have that, this should
206     // turn into an assertion.
207     if (CallSites.empty()) continue;
208     
209     for (DenseMap<Instruction*, CallGraphNode*>::iterator I = CallSites.begin(),
210          E = CallSites.end(); I != E; ++I)
211       // FIXME: I had to add a special horrible form of removeCallEdgeFor to
212       // support this.  Remove the Instruction* version of it when we can.
213       CGN->removeCallEdgeFor(I->first);
214     MadeChange = true;
215     CallSites.clear();
216   }
217
218   DEBUG(if (MadeChange) {
219           errs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
220           for (unsigned i = 0, e = CurSCC.size(); i != e; ++i)
221             CurSCC[i]->dump();
222          } else {
223            errs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
224          }
225         );
226 }
227
228 /// run - Execute all of the passes scheduled for execution.  Keep track of
229 /// whether any of the passes modifies the module, and if so, return true.
230 bool CGPassManager::runOnModule(Module &M) {
231   CallGraph &CG = getAnalysis<CallGraph>();
232   bool Changed = doInitialization(CG);
233
234   std::vector<CallGraphNode*> CurSCC;
235   
236   // Walk the callgraph in bottom-up SCC order.
237   for (scc_iterator<CallGraph*> CGI = scc_begin(&CG), E = scc_end(&CG);
238        CGI != E;) {
239     // Copy the current SCC and increment past it so that the pass can hack
240     // on the SCC if it wants to without invalidating our iterator.
241     CurSCC = *CGI;
242     ++CGI;
243     
244     
245     // CallGraphUpToDate - Keep track of whether the callgraph is known to be
246     // up-to-date or not.  The CGSSC pass manager runs two types of passes:
247     // CallGraphSCC Passes and other random function passes.  Because other
248     // random function passes are not CallGraph aware, they may clobber the
249     // call graph by introducing new calls or deleting other ones.  This flag
250     // is set to false when we run a function pass so that we know to clean up
251     // the callgraph when we need to run a CGSCCPass again.
252     bool CallGraphUpToDate = true;
253     
254     // Run all passes on current SCC.
255     for (unsigned PassNo = 0, e = getNumContainedPasses();
256          PassNo != e; ++PassNo) {
257       Pass *P = getContainedPass(PassNo);
258
259       dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, "");
260       dumpRequiredSet(P);
261
262       initializeAnalysisImpl(P);
263
264       // Actually run this pass on the current SCC.
265       Changed |= RunPassOnSCC(P, CurSCC, CG, CallGraphUpToDate);
266
267       if (Changed)
268         dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
269       dumpPreservedSet(P);
270
271       verifyPreservedAnalysis(P);      
272       removeNotPreservedAnalysis(P);
273       recordAvailableAnalysis(P);
274       removeDeadPasses(P, "", ON_CG_MSG);
275     }
276     
277     // If the callgraph was left out of date (because the last pass run was a
278     // functionpass), refresh it before we move on to the next SCC.
279     if (!CallGraphUpToDate)
280       RefreshCallGraph(CurSCC, CG);
281   }
282   Changed |= doFinalization(CG);
283   return Changed;
284 }
285
286 /// Initialize CG
287 bool CGPassManager::doInitialization(CallGraph &CG) {
288   bool Changed = false;
289   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
290     Pass *P = getContainedPass(Index);
291     if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {
292       Changed |= CGSP->doInitialization(CG);
293     } else {
294       FPPassManager *FP = dynamic_cast<FPPassManager *>(P);
295       assert (FP && "Invalid CGPassManager member");
296       Changed |= FP->doInitialization(CG.getModule());
297     }
298   }
299   return Changed;
300 }
301
302 /// Finalize CG
303 bool CGPassManager::doFinalization(CallGraph &CG) {
304   bool Changed = false;
305   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
306     Pass *P = getContainedPass(Index);
307     if (CallGraphSCCPass *CGSP = dynamic_cast<CallGraphSCCPass *>(P)) {
308       Changed |= CGSP->doFinalization(CG);
309     } else {
310       FPPassManager *FP = dynamic_cast<FPPassManager *>(P);
311       assert (FP && "Invalid CGPassManager member");
312       Changed |= FP->doFinalization(CG.getModule());
313     }
314   }
315   return Changed;
316 }
317
318 /// Assign pass manager to manage this pass.
319 void CallGraphSCCPass::assignPassManager(PMStack &PMS,
320                                          PassManagerType PreferredType) {
321   // Find CGPassManager 
322   while (!PMS.empty() &&
323          PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
324     PMS.pop();
325
326   assert (!PMS.empty() && "Unable to handle Call Graph Pass");
327   CGPassManager *CGP = dynamic_cast<CGPassManager *>(PMS.top());
328
329   // Create new Call Graph SCC Pass Manager if it does not exist. 
330   if (!CGP) {
331
332     assert (!PMS.empty() && "Unable to create Call Graph Pass Manager");
333     PMDataManager *PMD = PMS.top();
334
335     // [1] Create new Call Graph Pass Manager
336     CGP = new CGPassManager(PMD->getDepth() + 1);
337
338     // [2] Set up new manager's top level manager
339     PMTopLevelManager *TPM = PMD->getTopLevelManager();
340     TPM->addIndirectPassManager(CGP);
341
342     // [3] Assign manager to manage this new manager. This may create
343     // and push new managers into PMS
344     Pass *P = dynamic_cast<Pass *>(CGP);
345     TPM->schedulePass(P);
346
347     // [4] Push new manager into PMS
348     PMS.push(CGP);
349   }
350
351   CGP->add(this);
352 }
353
354 /// getAnalysisUsage - For this class, we declare that we require and preserve
355 /// the call graph.  If the derived class implements this method, it should
356 /// always explicitly call the implementation here.
357 void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
358   AU.addRequired<CallGraph>();
359   AU.addPreserved<CallGraph>();
360 }