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