Reformat blank lines.
[oota-llvm.git] / include / llvm / IR / LegacyPassManagers.h
1 //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- 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_IR_LEGACYPASSMANAGERS_H
15 #define LLVM_IR_LEGACYPASSMANAGERS_H
16
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Pass.h"
22 #include <map>
23 #include <vector>
24
25 //===----------------------------------------------------------------------===//
26 // Overview:
27 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
28 //
29 //   o Manage optimization pass execution order
30 //   o Make required Analysis information available before pass P is run
31 //   o Release memory occupied by dead passes
32 //   o If Analysis information is dirtied by a pass then regenerate Analysis
33 //     information before it is consumed by another pass.
34 //
35 // Pass Manager Infrastructure uses multiple pass managers.  They are
36 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
37 // This class hierarchy uses multiple inheritance but pass managers do not
38 // derive from another pass manager.
39 //
40 // PassManager and FunctionPassManager are two top-level pass manager that
41 // represents the external interface of this entire pass manager infrastucture.
42 //
43 // Important classes :
44 //
45 // [o] class PMTopLevelManager;
46 //
47 // Two top level managers, PassManager and FunctionPassManager, derive from
48 // PMTopLevelManager. PMTopLevelManager manages information used by top level
49 // managers such as last user info.
50 //
51 // [o] class PMDataManager;
52 //
53 // PMDataManager manages information, e.g. list of available analysis info,
54 // used by a pass manager to manage execution order of passes. It also provides
55 // a place to implement common pass manager APIs. All pass managers derive from
56 // PMDataManager.
57 //
58 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
59 //
60 // BBPassManager manages BasicBlockPasses.
61 //
62 // [o] class FunctionPassManager;
63 //
64 // This is a external interface used to manage FunctionPasses. This
65 // interface relies on FunctionPassManagerImpl to do all the tasks.
66 //
67 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
68 //                                     public PMTopLevelManager;
69 //
70 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
71 //
72 // [o] class FPPassManager : public ModulePass, public PMDataManager;
73 //
74 // FPPassManager manages FunctionPasses and BBPassManagers
75 //
76 // [o] class MPPassManager : public Pass, public PMDataManager;
77 //
78 // MPPassManager manages ModulePasses and FPPassManagers
79 //
80 // [o] class PassManager;
81 //
82 // This is a external interface used by various tools to manages passes. It
83 // relies on PassManagerImpl to do all the tasks.
84 //
85 // [o] class PassManagerImpl : public Pass, public PMDataManager,
86 //                             public PMTopLevelManager
87 //
88 // PassManagerImpl is a top level pass manager responsible for managing
89 // MPPassManagers.
90 //===----------------------------------------------------------------------===//
91
92 #include "llvm/Support/PrettyStackTrace.h"
93
94 namespace llvm {
95   class Module;
96   class Pass;
97   class StringRef;
98   class Value;
99   class Timer;
100   class PMDataManager;
101
102 // enums for debugging strings
103 enum PassDebuggingString {
104   EXECUTION_MSG, // "Executing Pass '" + PassName
105   MODIFICATION_MSG, // "Made Modification '" + PassName
106   FREEING_MSG, // " Freeing Pass '" + PassName
107   ON_BASICBLOCK_MSG, // "' on BasicBlock '" + InstructionName + "'...\n"
108   ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
109   ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
110   ON_REGION_MSG, // "' on Region '" + Msg + "'...\n'"
111   ON_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'"
112   ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'"
113 };
114
115 /// PassManagerPrettyStackEntry - This is used to print informative information
116 /// about what pass is running when/if a stack trace is generated.
117 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
118   Pass *P;
119   Value *V;
120   Module *M;
121
122 public:
123   explicit PassManagerPrettyStackEntry(Pass *p)
124     : P(p), V(nullptr), M(nullptr) {}  // When P is releaseMemory'd.
125   PassManagerPrettyStackEntry(Pass *p, Value &v)
126     : P(p), V(&v), M(nullptr) {} // When P is run on V
127   PassManagerPrettyStackEntry(Pass *p, Module &m)
128     : P(p), V(nullptr), M(&m) {} // When P is run on M
129
130   /// print - Emit information about this stack frame to OS.
131   void print(raw_ostream &OS) const override;
132 };
133
134 //===----------------------------------------------------------------------===//
135 // PMStack
136 //
137 /// PMStack - This class implements a stack data structure of PMDataManager
138 /// pointers.
139 ///
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 class PMStack {
145 public:
146   typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
147   iterator begin() const { return S.rbegin(); }
148   iterator end() const { return S.rend(); }
149
150   void pop();
151   PMDataManager *top() const { return S.back(); }
152   void push(PMDataManager *PM);
153   bool empty() const { return S.empty(); }
154
155   void dump() const;
156
157 private:
158   std::vector<PMDataManager *> S;
159 };
160
161 //===----------------------------------------------------------------------===//
162 // PMTopLevelManager
163 //
164 /// PMTopLevelManager manages LastUser info and collects common APIs used by
165 /// top level pass managers.
166 class PMTopLevelManager {
167 protected:
168   explicit PMTopLevelManager(PMDataManager *PMDM);
169
170   unsigned getNumContainedManagers() const {
171     return (unsigned)PassManagers.size();
172   }
173
174   void initializeAllAnalysisInfo();
175
176 private:
177   virtual PMDataManager *getAsPMDataManager() = 0;
178   virtual PassManagerType getTopLevelPassManagerType() = 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(ArrayRef<Pass*> AnalysisPasses, Pass *P);
188
189   /// Collect passes whose last user is P
190   void collectLastUses(SmallVectorImpl<Pass *> &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   /// Retrieve the PassInfo for an analysis.
198   const PassInfo *findAnalysisPassInfo(AnalysisID AID) const;
199
200   /// Find analysis usage information for the pass P.
201   AnalysisUsage *findAnalysisUsage(Pass *P);
202
203   virtual ~PMTopLevelManager();
204
205   /// Add immutable pass and initialize it.
206   void addImmutablePass(ImmutablePass *P);
207
208   inline SmallVectorImpl<ImmutablePass *>& 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   /// Collection of pass managers
231   SmallVector<PMDataManager *, 8> PassManagers;
232
233 private:
234   /// Collection of pass managers that are not directly maintained
235   /// by this pass manager
236   SmallVector<PMDataManager *, 8> IndirectPassManagers;
237
238   // Map to keep track of last user of the analysis pass.
239   // LastUser->second is the last user of Lastuser->first.
240   DenseMap<Pass *, Pass *> LastUser;
241
242   // Map to keep track of passes that are last used by a pass.
243   // This inverse map is initialized at PM->run() based on
244   // LastUser map.
245   DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser;
246
247   /// Immutable passes are managed by top level manager.
248   SmallVector<ImmutablePass *, 16> ImmutablePasses;
249
250   /// Map from ID to immutable passes.
251   SmallDenseMap<AnalysisID, ImmutablePass *, 8> ImmutablePassMap;
252
253   DenseMap<Pass *, AnalysisUsage *> AnUsageMap;
254
255   /// Collection of PassInfo objects found via analysis IDs and in this top
256   /// level manager. This is used to memoize queries to the pass registry.
257   /// FIXME: This is an egregious hack because querying the pass registry is
258   /// either slow or racy.
259   mutable DenseMap<AnalysisID, const PassInfo *> AnalysisPassInfos;
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   explicit PMDataManager() : TPM(nullptr), Depth(0) {
270     initializeAnalysisInfo();
271   }
272
273   virtual ~PMDataManager();
274
275   virtual Pass *getAsPass() = 0;
276
277   /// Augment AvailableAnalysis by adding analysis made available by pass P.
278   void recordAvailableAnalysis(Pass *P);
279
280   /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
281   void verifyPreservedAnalysis(Pass *P);
282
283   /// Remove Analysis that is not preserved by the pass
284   void removeNotPreservedAnalysis(Pass *P);
285
286   /// Remove dead passes used by P.
287   void removeDeadPasses(Pass *P, StringRef Msg,
288                         enum PassDebuggingString);
289
290   /// Remove P.
291   void freePass(Pass *P, StringRef Msg,
292                 enum PassDebuggingString);
293
294   /// Add pass P into the PassVector. Update
295   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
296   void add(Pass *P, bool ProcessAnalysis = true);
297
298   /// Add RequiredPass into list of lower level passes required by pass P.
299   /// RequiredPass is run on the fly by Pass Manager when P requests it
300   /// through getAnalysis interface.
301   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
302
303   virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
304
305   /// Initialize available analysis information.
306   void initializeAnalysisInfo() {
307     AvailableAnalysis.clear();
308     for (unsigned i = 0; i < PMT_Last; ++i)
309       InheritedAnalysis[i] = nullptr;
310   }
311
312   // Return true if P preserves high level analysis used by other
313   // passes that are managed by this manager.
314   bool preserveHigherLevelAnalysis(Pass *P);
315
316   /// Populate UsedPasses with analysis pass that are used or required by pass
317   /// P and are available. Populate ReqPassNotAvailable with analysis pass that
318   /// are required by pass P but are not available.
319   void collectRequiredAndUsedAnalyses(
320       SmallVectorImpl<Pass *> &UsedPasses,
321       SmallVectorImpl<AnalysisID> &ReqPassNotAvailable, 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   void setDepth(unsigned newDepth) { Depth = newDepth; }
339
340   // Print routines used by debug-pass
341   void dumpLastUses(Pass *P, unsigned Offset) const;
342   void dumpPassArguments() const;
343   void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
344                     enum PassDebuggingString S2, StringRef Msg);
345   void dumpRequiredSet(const Pass *P) const;
346   void dumpPreservedSet(const Pass *P) const;
347   void dumpUsedSet(const Pass *P) const;
348
349   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   DenseMap<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   // Top level manager.
372   PMTopLevelManager *TPM;
373
374   // Collection of pass that are managed by this manager
375   SmallVector<Pass *, 16> PassVector;
376
377   // Collection of Analysis provided by Parent pass manager and
378   // used by current pass manager. At at time there can not be more
379   // then PMT_Last active pass mangers.
380   DenseMap<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
381
382   /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
383   /// or higher is specified.
384   bool isPassDebuggingExecutionsOrMore() const;
385
386 private:
387   void dumpAnalysisUsage(StringRef Msg, const Pass *P,
388                          const AnalysisUsage::VectorType &Set) const;
389
390   // Set of available Analysis. This information is used while scheduling
391   // pass. If a pass requires an analysis which is not available then
392   // the required analysis pass is scheduled to run before the pass itself is
393   // scheduled to run.
394   DenseMap<AnalysisID, Pass*> AvailableAnalysis;
395
396   // Collection of higher level analysis used by the pass managed by
397   // this manager.
398   SmallVector<Pass *, 16> HigherLevelAnalysis;
399
400   unsigned Depth;
401 };
402
403 //===----------------------------------------------------------------------===//
404 // FPPassManager
405 //
406 /// FPPassManager manages BBPassManagers and FunctionPasses.
407 /// It batches all function passes and basic block pass managers together and
408 /// sequence them to process one function at a time before processing next
409 /// function.
410 class FPPassManager : public ModulePass, public PMDataManager {
411 public:
412   static char ID;
413   explicit FPPassManager()
414   : ModulePass(ID), PMDataManager() { }
415
416   /// run - Execute all of the passes scheduled for execution.  Keep track of
417   /// whether any of the passes modifies the module, and if so, return true.
418   bool runOnFunction(Function &F);
419   bool runOnModule(Module &M) override;
420
421   /// cleanup - After running all passes, clean up pass manager cache.
422   void cleanup();
423
424   /// doInitialization - Overrides ModulePass doInitialization for global
425   /// initialization tasks
426   ///
427   using ModulePass::doInitialization;
428
429   /// doInitialization - Run all of the initializers for the function passes.
430   ///
431   bool doInitialization(Module &M) override;
432
433   /// doFinalization - Overrides ModulePass doFinalization for global
434   /// finalization tasks
435   ///
436   using ModulePass::doFinalization;
437
438   /// doFinalization - Run all of the finalizers for the function passes.
439   ///
440   bool doFinalization(Module &M) override;
441
442   PMDataManager *getAsPMDataManager() override { return this; }
443   Pass *getAsPass() override { return this; }
444
445   /// Pass Manager itself does not invalidate any analysis info.
446   void getAnalysisUsage(AnalysisUsage &Info) const override {
447     Info.setPreservesAll();
448   }
449
450   // Print passes managed by this manager
451   void dumpPassStructure(unsigned Offset) override;
452
453   const char *getPassName() const override {
454     return "Function Pass Manager";
455   }
456
457   FunctionPass *getContainedPass(unsigned N) {
458     assert ( N < PassVector.size() && "Pass number out of range!");
459     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
460     return FP;
461   }
462
463   PassManagerType getPassManagerType() const override {
464     return PMT_FunctionPassManager;
465   }
466 };
467
468 Timer *getPassTimer(Pass *);
469 }
470
471 #endif