Keep track of analysis usage information for passes. Avoid invoking
[oota-llvm.git] / include / llvm / PassManagers.h
1 //===- llvm/PassManager.h - Pass Inftrastructre classes  --------*- 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 declares the LLVM Pass Manager infrastructure. 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/PassManager.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include <deque>
18 #include <map>
19
20 //===----------------------------------------------------------------------===//
21 // Overview:
22 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
23 // 
24 //   o Manage optimization pass execution order
25 //   o Make required Analysis information available before pass P is run
26 //   o Release memory occupied by dead passes
27 //   o If Analysis information is dirtied by a pass then regenerate Analysis 
28 //     information before it is consumed by another pass.
29 //
30 // Pass Manager Infrastructure uses multiple pass managers.  They are
31 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
32 // This class hierarchy uses multiple inheritance but pass managers do not
33 // derive from another pass manager.
34 //
35 // PassManager and FunctionPassManager are two top-level pass manager that
36 // represents the external interface of this entire pass manager infrastucture.
37 //
38 // Important classes :
39 //
40 // [o] class PMTopLevelManager;
41 //
42 // Two top level managers, PassManager and FunctionPassManager, derive from 
43 // PMTopLevelManager. PMTopLevelManager manages information used by top level 
44 // managers such as last user info.
45 //
46 // [o] class PMDataManager;
47 //
48 // PMDataManager manages information, e.g. list of available analysis info, 
49 // used by a pass manager to manage execution order of passes. It also provides
50 // a place to implement common pass manager APIs. All pass managers derive from
51 // PMDataManager.
52 //
53 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
54 //
55 // BBPassManager manages BasicBlockPasses.
56 //
57 // [o] class FunctionPassManager;
58 //
59 // This is a external interface used by JIT to manage FunctionPasses. This
60 // interface relies on FunctionPassManagerImpl to do all the tasks.
61 //
62 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
63 //                                     public PMTopLevelManager;
64 //
65 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
66 //
67 // [o] class FPPassManager : public ModulePass, public PMDataManager;
68 //
69 // FPPassManager manages FunctionPasses and BBPassManagers
70 //
71 // [o] class MPPassManager : public Pass, public PMDataManager;
72 //
73 // MPPassManager manages ModulePasses and FPPassManagers
74 //
75 // [o] class PassManager;
76 //
77 // This is a external interface used by various tools to manages passes. It
78 // relies on PassManagerImpl to do all the tasks.
79 //
80 // [o] class PassManagerImpl : public Pass, public PMDataManager,
81 //                             public PMDTopLevelManager
82 //
83 // PassManagerImpl is a top level pass manager responsible for managing
84 // MPPassManagers.
85 //===----------------------------------------------------------------------===//
86
87 #ifndef PASSMANAGERS_H
88 #define PASSMANAGERS_H
89
90 #include "llvm/Pass.h"
91 #include <deque>
92
93 namespace llvm {
94
95 /// FunctionPassManager and PassManager, two top level managers, serve 
96 /// as the public interface of pass manager infrastructure.
97 enum TopLevelManagerType {
98   TLM_Function,  // FunctionPassManager
99   TLM_Pass       // PassManager
100 };
101     
102 // enums for debugging strings
103 enum PassDebuggingString {
104   EXECUTION_MSG, // "Executing Pass '"
105   MODIFICATION_MSG, // "' Made Modification '"
106   FREEING_MSG, // " Freeing Pass '"
107   ON_BASICBLOCK_MSG, // "'  on BasicBlock '" + PassName + "'...\n"
108   ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
109   ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
110   ON_LOOP_MSG, // " 'on Loop ...\n'"
111   ON_CG_MSG // "' on Call Graph ...\n'"
112 };  
113
114 //===----------------------------------------------------------------------===//
115 // PMStack
116 //
117 /// PMStack
118 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers 
119 /// using PMStack. Each Pass implements assignPassManager() to connect itself
120 /// with appropriate manager. assignPassManager() walks PMStack to find
121 /// suitable manager.
122 ///
123 /// PMStack is just a wrapper around standard deque that overrides pop() and
124 /// push() methods.
125 class PMStack {
126 public:
127   typedef std::deque<PMDataManager *>::reverse_iterator iterator;
128   iterator begin() { return S.rbegin(); }
129   iterator end() { return S.rend(); }
130
131   void handleLastUserOverflow();
132
133   void pop();
134   inline PMDataManager *top() { return S.back(); }
135   void push(PMDataManager *PM);
136   inline bool empty() { return S.empty(); }
137
138   void dump();
139 private:
140   std::deque<PMDataManager *> S;
141 };
142
143
144 //===----------------------------------------------------------------------===//
145 // PMTopLevelManager
146 //
147 /// PMTopLevelManager manages LastUser info and collects common APIs used by
148 /// top level pass managers.
149 class PMTopLevelManager {
150 public:
151
152   virtual unsigned getNumContainedManagers() const {
153     return (unsigned)PassManagers.size();
154   }
155
156   /// Schedule pass P for execution. Make sure that passes required by
157   /// P are run before P is run. Update analysis info maintained by
158   /// the manager. Remove dead passes. This is a recursive function.
159   void schedulePass(Pass *P);
160
161   /// This is implemented by top level pass manager and used by 
162   /// schedulePass() to add analysis info passes that are not available.
163   virtual void addTopLevelPass(Pass  *P) = 0;
164
165   /// Set pass P as the last user of the given analysis passes.
166   void setLastUser(SmallVector<Pass *, 12> &AnalysisPasses, Pass *P);
167
168   /// Collect passes whose last user is P
169   void collectLastUses(SmallVector<Pass *, 12> &LastUses, Pass *P);
170
171   /// Find the pass that implements Analysis AID. Search immutable
172   /// passes and all pass managers. If desired pass is not found
173   /// then return NULL.
174   Pass *findAnalysisPass(AnalysisID AID);
175
176   /// Find analysis usage information for the pass P.
177   AnalysisUsage *findAnalysisUsage(Pass *P);
178
179   explicit PMTopLevelManager(enum TopLevelManagerType t);
180   virtual ~PMTopLevelManager(); 
181
182   /// Add immutable pass and initialize it.
183   inline void addImmutablePass(ImmutablePass *P) {
184     P->initializePass();
185     ImmutablePasses.push_back(P);
186   }
187
188   inline std::vector<ImmutablePass *>& getImmutablePasses() {
189     return ImmutablePasses;
190   }
191
192   void addPassManager(PMDataManager *Manager) {
193     PassManagers.push_back(Manager);
194   }
195
196   // Add Manager into the list of managers that are not directly
197   // maintained by this top level pass manager
198   inline void addIndirectPassManager(PMDataManager *Manager) {
199     IndirectPassManagers.push_back(Manager);
200   }
201
202   // Print passes managed by this top level manager.
203   void dumpPasses() const;
204   void dumpArguments() const;
205
206   void initializeAllAnalysisInfo();
207
208   // Active Pass Managers
209   PMStack activeStack;
210
211 protected:
212   
213   /// Collection of pass managers
214   std::vector<PMDataManager *> PassManagers;
215
216 private:
217
218   /// Collection of pass managers that are not directly maintained
219   /// by this pass manager
220   std::vector<PMDataManager *> IndirectPassManagers;
221
222   // Map to keep track of last user of the analysis pass.
223   // LastUser->second is the last user of Lastuser->first.
224   std::map<Pass *, Pass *> LastUser;
225
226   /// Immutable passes are managed by top level manager.
227   std::vector<ImmutablePass *> ImmutablePasses;
228
229   DenseMap<Pass *, AnalysisUsage *> AnUsageMap;
230 };
231
232
233   
234 //===----------------------------------------------------------------------===//
235 // PMDataManager
236
237 /// PMDataManager provides the common place to manage the analysis data
238 /// used by pass managers.
239 class PMDataManager {
240 public:
241
242   explicit PMDataManager(int Depth) : TPM(NULL), Depth(Depth) {
243     initializeAnalysisInfo();
244   }
245
246   virtual ~PMDataManager();
247
248   /// Augment AvailableAnalysis by adding analysis made available by pass P.
249   void recordAvailableAnalysis(Pass *P);
250
251   /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
252   void verifyPreservedAnalysis(Pass *P);
253
254   /// verifyDomInfo -- Verify dominator information if it is available.
255   void verifyDomInfo(Pass &P, Function &F);
256
257   /// Remove Analysis that is not preserved by the pass
258   void removeNotPreservedAnalysis(Pass *P);
259   
260   /// Remove dead passes
261   void removeDeadPasses(Pass *P, const char *Msg, enum PassDebuggingString);
262
263   /// Add pass P into the PassVector. Update 
264   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
265   void add(Pass *P, bool ProcessAnalysis = true);
266
267   /// Add RequiredPass into list of lower level passes required by pass P.
268   /// RequiredPass is run on the fly by Pass Manager when P requests it
269   /// through getAnalysis interface.
270   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
271
272   virtual Pass * getOnTheFlyPass(Pass *P, const PassInfo *PI, Function &F) {
273     assert (0 && "Unable to find on the fly pass");
274     return NULL;
275   }
276
277   /// Initialize available analysis information.
278   void initializeAnalysisInfo() { 
279     AvailableAnalysis.clear();
280     for (unsigned i = 0; i < PMT_Last; ++i)
281       InheritedAnalysis[i] = NULL;
282   }
283
284   // Return true if P preserves high level analysis used by other
285   // passes that are managed by this manager.
286   bool preserveHigherLevelAnalysis(Pass *P);
287
288
289   /// Populate RequiredPasses with analysis pass that are required by
290   /// pass P and are available. Populate ReqPassNotAvailable with analysis
291   /// pass that are required by pass P but are not available.
292   void collectRequiredAnalysis(SmallVector<Pass *, 8> &RequiredPasses,
293                                SmallVector<AnalysisID, 8> &ReqPassNotAvailable,
294                                Pass *P);
295
296   /// All Required analyses should be available to the pass as it runs!  Here
297   /// we fill in the AnalysisImpls member of the pass so that it can
298   /// successfully use the getAnalysis() method to retrieve the
299   /// implementations it needs.
300   void initializeAnalysisImpl(Pass *P);
301
302   /// Find the pass that implements Analysis AID. If desired pass is not found
303   /// then return NULL.
304   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
305
306   // Access toplevel manager
307   PMTopLevelManager *getTopLevelManager() { return TPM; }
308   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
309
310   unsigned getDepth() const { return Depth; }
311
312   // Print routines used by debug-pass
313   void dumpLastUses(Pass *P, unsigned Offset) const;
314   void dumpPassArguments() const;
315   void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
316                     enum PassDebuggingString S2, const char *Msg);
317   void dumpRequiredSet(const Pass *P) const;
318   void dumpPreservedSet(const Pass *P) const;
319
320   virtual unsigned getNumContainedPasses() const {
321     return (unsigned)PassVector.size();
322   }
323
324   virtual PassManagerType getPassManagerType() const { 
325     assert ( 0 && "Invalid use of getPassManagerType");
326     return PMT_Unknown; 
327   }
328
329   std::map<AnalysisID, Pass*> *getAvailableAnalysis() {
330     return &AvailableAnalysis;
331   }
332
333   // Collect AvailableAnalysis from all the active Pass Managers.
334   void populateInheritedAnalysis(PMStack &PMS) {
335     unsigned Index = 0;
336     for (PMStack::iterator I = PMS.begin(), E = PMS.end();
337          I != E; ++I)
338       InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
339   }
340
341 protected:
342
343   // Top level manager.
344   PMTopLevelManager *TPM;
345
346   // Collection of pass that are managed by this manager
347   std::vector<Pass *> PassVector;
348
349   // Collection of Analysis provided by Parent pass manager and
350   // used by current pass manager. At at time there can not be more
351   // then PMT_Last active pass mangers.
352   std::map<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
353
354 private:
355   void dumpAnalysisUsage(const char *Msg, const Pass *P,
356                            const AnalysisUsage::VectorType &Set) const;
357
358   // Set of available Analysis. This information is used while scheduling 
359   // pass. If a pass requires an analysis which is not not available then 
360   // equired analysis pass is scheduled to run before the pass itself is 
361   // scheduled to run.
362   std::map<AnalysisID, Pass*> AvailableAnalysis;
363
364   // Collection of higher level analysis used by the pass managed by
365   // this manager.
366   std::vector<Pass *> HigherLevelAnalysis;
367
368   unsigned Depth;
369 };
370
371 //===----------------------------------------------------------------------===//
372 // FPPassManager
373 //
374 /// FPPassManager manages BBPassManagers and FunctionPasses.
375 /// It batches all function passes and basic block pass managers together and 
376 /// sequence them to process one function at a time before processing next 
377 /// function.
378
379 class FPPassManager : public ModulePass, public PMDataManager {
380  
381 public:
382   static char ID;
383   explicit FPPassManager(int Depth) 
384   : ModulePass(intptr_t(&ID)), PMDataManager(Depth) { }
385   
386   /// run - Execute all of the passes scheduled for execution.  Keep track of
387   /// whether any of the passes modifies the module, and if so, return true.
388   bool runOnFunction(Function &F);
389   bool runOnModule(Module &M);
390
391   /// doInitialization - Run all of the initializers for the function passes.
392   ///
393   bool doInitialization(Module &M);
394   
395   /// doFinalization - Run all of the finalizers for the function passes.
396   ///
397   bool doFinalization(Module &M);
398
399   /// Pass Manager itself does not invalidate any analysis info.
400   void getAnalysisUsage(AnalysisUsage &Info) const {
401     Info.setPreservesAll();
402   }
403
404   // Print passes managed by this manager
405   void dumpPassStructure(unsigned Offset);
406
407   virtual const char *getPassName() const {
408     return "Function Pass Manager";
409   }
410
411   FunctionPass *getContainedPass(unsigned N) {
412     assert ( N < PassVector.size() && "Pass number out of range!");
413     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
414     return FP;
415   }
416
417   virtual PassManagerType getPassManagerType() const { 
418     return PMT_FunctionPassManager; 
419   }
420 };
421
422 }
423
424 extern void StartPassTimer(llvm::Pass *);
425 extern void StopPassTimer(llvm::Pass *);
426
427 #endif
428