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