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