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