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