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