Generalize the PassConfig API and remove addFinalizeRegAlloc().
[oota-llvm.git] / include / llvm / CodeGen / Passes.h
1 //===-- Passes.h - Target independent code generation passes ----*- 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 defines interfaces to access the target independent code generation
11 // passes provided by the LLVM backend.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_PASSES_H
16 #define LLVM_CODEGEN_PASSES_H
17
18 #include "llvm/Pass.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include <string>
21
22 namespace llvm {
23
24   class FunctionPass;
25   class MachineFunctionPass;
26   class PassInfo;
27   class PassManagerBase;
28   class TargetLoweringBase;
29   class TargetLowering;
30   class TargetRegisterClass;
31   class raw_ostream;
32 }
33
34 namespace llvm {
35
36 class PassConfigImpl;
37
38 /// Discriminated union of Pass ID types.
39 ///
40 /// The PassConfig API prefers dealing with IDs because they are safer and more
41 /// efficient. IDs decouple configuration from instantiation. This way, when a
42 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
43 /// refer to a Pass pointer after adding it to a pass manager, which deletes
44 /// redundant pass instances.
45 ///
46 /// However, it is convient to directly instantiate target passes with
47 /// non-default ctors. These often don't have a registered PassInfo. Rather than
48 /// force all target passes to implement the pass registry boilerplate, allow
49 /// the PassConfig API to handle either type.
50 ///
51 /// AnalysisID is sadly char*, so PointerIntPair won't work.
52 class IdentifyingPassPtr {
53   void *P;
54   bool IsInstance;
55 public:
56   IdentifyingPassPtr(): P(0), IsInstance(false) {}
57   IdentifyingPassPtr(AnalysisID IDPtr): P((void*)IDPtr), IsInstance(false) {}
58   IdentifyingPassPtr(Pass *InstancePtr)
59     : P((void*)InstancePtr), IsInstance(true) {}
60
61   bool isValid() const { return P; }
62   bool isInstance() const { return IsInstance; }
63
64   AnalysisID getID() const {
65     assert(!IsInstance && "Not a Pass ID");
66     return (AnalysisID)P;
67   }
68   Pass *getInstance() const {
69     assert(IsInstance && "Not a Pass Instance");
70     return (Pass *)P;
71   }
72 };
73
74 template <> struct isPodLike<IdentifyingPassPtr> {
75   static const bool value = true;
76 };
77
78 /// Target-Independent Code Generator Pass Configuration Options.
79 ///
80 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
81 /// to the internals of other CodeGen passes.
82 class TargetPassConfig : public ImmutablePass {
83 public:
84   /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
85   /// are unregistered pass IDs. They are only useful for use with
86   /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
87   ///
88
89   /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
90   /// during codegen, on SSA form.
91   static char EarlyTailDuplicateID;
92
93   /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
94   /// optimization after regalloc.
95   static char PostRAMachineLICMID;
96
97 private:
98   PassManagerBase *PM;
99   AnalysisID StartAfter;
100   AnalysisID StopAfter;
101   bool Started;
102   bool Stopped;
103
104 protected:
105   TargetMachine *TM;
106   PassConfigImpl *Impl; // Internal data structures
107   bool Initialized;     // Flagged after all passes are configured.
108
109   // Target Pass Options
110   // Targets provide a default setting, user flags override.
111   //
112   bool DisableVerify;
113
114   /// Default setting for -enable-tail-merge on this target.
115   bool EnableTailMerge;
116
117 public:
118   TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
119   // Dummy constructor.
120   TargetPassConfig();
121
122   virtual ~TargetPassConfig();
123
124   static char ID;
125
126   /// Get the right type of TargetMachine for this target.
127   template<typename TMC> TMC &getTM() const {
128     return *static_cast<TMC*>(TM);
129   }
130
131   const TargetLowering *getTargetLowering() const {
132     return TM->getTargetLowering();
133   }
134
135   //
136   void setInitialized() { Initialized = true; }
137
138   CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
139
140   /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
141   /// running only a portion of the normal code-gen pass sequence.  If the
142   /// Start pass ID is zero, then compilation will begin at the normal point;
143   /// otherwise, clear the Started flag to indicate that passes should not be
144   /// added until the starting pass is seen.  If the Stop pass ID is zero,
145   /// then compilation will continue to the end.
146   void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
147     StartAfter = Start;
148     StopAfter = Stop;
149     Started = (StartAfter == 0);
150   }
151
152   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
153
154   bool getEnableTailMerge() const { return EnableTailMerge; }
155   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
156
157   /// Allow the target to override a specific pass without overriding the pass
158   /// pipeline. When passes are added to the standard pipeline at the
159   /// point where StandardID is expected, add TargetID in its place.
160   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
161
162   /// Insert InsertedPassID pass after TargetPassID pass.
163   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
164
165   /// Allow the target to enable a specific standard pass by default.
166   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
167
168   /// Allow the target to disable a specific standard pass by default.
169   void disablePass(AnalysisID PassID) {
170     substitutePass(PassID, IdentifyingPassPtr());
171   }
172
173   /// Return the pass substituted for StandardID by the target.
174   /// If no substitution exists, return StandardID.
175   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
176
177   /// Return true if the optimized regalloc pipeline is enabled.
178   bool getOptimizeRegAlloc() const;
179
180   /// Add common target configurable passes that perform LLVM IR to IR
181   /// transforms following machine independent optimization.
182   virtual void addIRPasses();
183
184   /// Add passes to lower exception handling for the code generator.
185   void addPassesToHandleExceptions();
186
187   /// Add pass to prepare the LLVM IR for code generation. This should be done
188   /// before exception handling preparation passes.
189   virtual void addCodeGenPrepare();
190
191   /// Add common passes that perform LLVM IR to IR transforms in preparation for
192   /// instruction selection.
193   virtual void addISelPrepare();
194
195   /// addInstSelector - This method should install an instruction selector pass,
196   /// which converts from LLVM code to machine instructions.
197   virtual bool addInstSelector() {
198     return true;
199   }
200
201   /// Add the complete, standard set of LLVM CodeGen passes.
202   /// Fully developed targets will not generally override this.
203   virtual void addMachinePasses();
204
205 protected:
206   // Helper to verify the analysis is really immutable.
207   void setOpt(bool &Opt, bool Val);
208
209   /// Methods with trivial inline returns are convenient points in the common
210   /// codegen pass pipeline where targets may insert passes. Methods with
211   /// out-of-line standard implementations are major CodeGen stages called by
212   /// addMachinePasses. Some targets may override major stages when inserting
213   /// passes is insufficient, but maintaining overriden stages is more work.
214   ///
215
216   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
217   /// passes (which are run just before instruction selector).
218   virtual bool addPreISel() {
219     return true;
220   }
221
222   /// addMachineSSAOptimization - Add standard passes that optimize machine
223   /// instructions in SSA form.
224   virtual void addMachineSSAOptimization();
225
226   /// Add passes that optimize instruction level parallelism for out-of-order
227   /// targets. These passes are run while the machine code is still in SSA
228   /// form, so they can use MachineTraceMetrics to control their heuristics.
229   ///
230   /// All passes added here should preserve the MachineDominatorTree,
231   /// MachineLoopInfo, and MachineTraceMetrics analyses.
232   virtual bool addILPOpts() {
233     return false;
234   }
235
236   /// addPreRegAlloc - This method may be implemented by targets that want to
237   /// run passes immediately before register allocation. This should return
238   /// true if -print-machineinstrs should print after these passes.
239   virtual bool addPreRegAlloc() {
240     return false;
241   }
242
243   /// createTargetRegisterAllocator - Create the register allocator pass for
244   /// this target at the current optimization level.
245   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
246
247   /// addFastRegAlloc - Add the minimum set of target-independent passes that
248   /// are required for fast register allocation.
249   virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
250
251   /// addOptimizedRegAlloc - Add passes related to register allocation.
252   /// LLVMTargetMachine provides standard regalloc passes for most targets.
253   virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
254
255   /// addPreRewrite - Add passes to the optimized register allocation pipeline
256   /// after register allocation is complete, but before virtual registers are
257   /// rewritten to physical registers.
258   ///
259   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
260   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
261   /// When these passes run, VirtRegMap contains legal physreg assignments for
262   /// all virtual registers.
263   virtual bool addPreRewrite() {
264     return false;
265   }
266
267   /// addPostRegAlloc - This method may be implemented by targets that want to
268   /// run passes after register allocation pass pipeline but before
269   /// prolog-epilog insertion.  This should return true if -print-machineinstrs
270   /// should print after these passes.
271   virtual bool addPostRegAlloc() {
272     return false;
273   }
274
275   /// Add passes that optimize machine instructions after register allocation.
276   virtual void addMachineLateOptimization();
277
278   /// addPreSched2 - This method may be implemented by targets that want to
279   /// run passes after prolog-epilog insertion and before the second instruction
280   /// scheduling pass.  This should return true if -print-machineinstrs should
281   /// print after these passes.
282   virtual bool addPreSched2() {
283     return false;
284   }
285
286   /// addGCPasses - Add late codegen passes that analyze code for garbage
287   /// collection. This should return true if GC info should be printed after
288   /// these passes.
289   virtual bool addGCPasses();
290
291   /// Add standard basic block placement passes.
292   virtual void addBlockPlacement();
293
294   /// addPreEmitPass - This pass may be implemented by targets that want to run
295   /// passes immediately before machine code is emitted.  This should return
296   /// true if -print-machineinstrs should print out the code after the passes.
297   virtual bool addPreEmitPass() {
298     return false;
299   }
300
301   /// Utilities for targets to add passes to the pass manager.
302   ///
303
304   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
305   /// Return the pass that was added, or zero if no pass was added.
306   AnalysisID addPass(AnalysisID PassID);
307
308   /// Add a pass to the PassManager if that pass is supposed to be run, as
309   /// determined by the StartAfter and StopAfter options.
310   void addPass(Pass *P);
311
312   /// addMachinePasses helper to create the target-selected or overriden
313   /// regalloc pass.
314   FunctionPass *createRegAllocPass(bool Optimized);
315
316   /// printAndVerify - Add a pass to dump then verify the machine function, if
317   /// those steps are enabled.
318   ///
319   void printAndVerify(const char *Banner);
320 };
321 } // namespace llvm
322
323 /// List of target independent CodeGen pass IDs.
324 namespace llvm {
325   /// \brief Create a basic TargetTransformInfo analysis pass.
326   ///
327   /// This pass implements the target transform info analysis using the target
328   /// independent information available to the LLVM code generator.
329   ImmutablePass *
330   createBasicTargetTransformInfoPass(const TargetLoweringBase *TLI);
331
332   /// createUnreachableBlockEliminationPass - The LLVM code generator does not
333   /// work well with unreachable basic blocks (what live ranges make sense for a
334   /// block that cannot be reached?).  As such, a code generator should either
335   /// not instruction select unreachable blocks, or run this pass as its
336   /// last LLVM modifying pass to clean up blocks that are not reachable from
337   /// the entry block.
338   FunctionPass *createUnreachableBlockEliminationPass();
339
340   /// MachineFunctionPrinter pass - This pass prints out the machine function to
341   /// the given stream as a debugging tool.
342   MachineFunctionPass *
343   createMachineFunctionPrinterPass(raw_ostream &OS,
344                                    const std::string &Banner ="");
345
346   /// MachineLoopInfo - This pass is a loop analysis pass.
347   extern char &MachineLoopInfoID;
348
349   /// MachineDominators - This pass is a machine dominators analysis pass.
350   extern char &MachineDominatorsID;
351
352   /// EdgeBundles analysis - Bundle machine CFG edges.
353   extern char &EdgeBundlesID;
354
355   /// LiveVariables pass - This pass computes the set of blocks in which each
356   /// variable is life and sets machine operand kill flags.
357   extern char &LiveVariablesID;
358
359   /// PHIElimination - This pass eliminates machine instruction PHI nodes
360   /// by inserting copy instructions.  This destroys SSA information, but is the
361   /// desired input for some register allocators.  This pass is "required" by
362   /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
363   extern char &PHIEliminationID;
364
365   /// StrongPHIElimination - This pass eliminates machine instruction PHI
366   /// nodes by inserting copy instructions.  This destroys SSA information, but
367   /// is the desired input for some register allocators.  This pass is
368   /// "required" by these register allocator like this:
369   ///    AU.addRequiredID(PHIEliminationID);
370   ///  This pass is still in development
371   extern char &StrongPHIEliminationID;
372
373   /// LiveIntervals - This analysis keeps track of the live ranges of virtual
374   /// and physical registers.
375   extern char &LiveIntervalsID;
376
377   /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
378   extern char &LiveStacksID;
379
380   /// TwoAddressInstruction - This pass reduces two-address instructions to
381   /// use two operands. This destroys SSA information but it is desired by
382   /// register allocators.
383   extern char &TwoAddressInstructionPassID;
384
385   /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
386   extern char &ProcessImplicitDefsID;
387
388   /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
389   extern char &RegisterCoalescerID;
390
391   /// MachineScheduler - This pass schedules machine instructions.
392   extern char &MachineSchedulerID;
393
394   /// SpillPlacement analysis. Suggest optimal placement of spill code between
395   /// basic blocks.
396   extern char &SpillPlacementID;
397
398   /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
399   /// assigned in VirtRegMap.
400   extern char &VirtRegRewriterID;
401
402   /// UnreachableMachineBlockElimination - This pass removes unreachable
403   /// machine basic blocks.
404   extern char &UnreachableMachineBlockElimID;
405
406   /// DeadMachineInstructionElim - This pass removes dead machine instructions.
407   extern char &DeadMachineInstructionElimID;
408
409   /// FastRegisterAllocation Pass - This pass register allocates as fast as
410   /// possible. It is best suited for debug code where live ranges are short.
411   ///
412   FunctionPass *createFastRegisterAllocator();
413
414   /// BasicRegisterAllocation Pass - This pass implements a degenerate global
415   /// register allocator using the basic regalloc framework.
416   ///
417   FunctionPass *createBasicRegisterAllocator();
418
419   /// Greedy register allocation pass - This pass implements a global register
420   /// allocator for optimized builds.
421   ///
422   FunctionPass *createGreedyRegisterAllocator();
423
424   /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
425   /// Quadratic Prograaming (PBQP) based register allocator.
426   ///
427   FunctionPass *createDefaultPBQPRegisterAllocator();
428
429   /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
430   /// and eliminates abstract frame references.
431   extern char &PrologEpilogCodeInserterID;
432
433   /// ExpandPostRAPseudos - This pass expands pseudo instructions after
434   /// register allocation.
435   extern char &ExpandPostRAPseudosID;
436
437   /// createPostRAScheduler - This pass performs post register allocation
438   /// scheduling.
439   extern char &PostRASchedulerID;
440
441   /// BranchFolding - This pass performs machine code CFG based
442   /// optimizations to delete branches to branches, eliminate branches to
443   /// successor blocks (creating fall throughs), and eliminating branches over
444   /// branches.
445   extern char &BranchFolderPassID;
446
447   /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
448   extern char &MachineFunctionPrinterPassID;
449
450   /// TailDuplicate - Duplicate blocks with unconditional branches
451   /// into tails of their predecessors.
452   extern char &TailDuplicateID;
453
454   /// MachineTraceMetrics - This pass computes critical path and CPU resource
455   /// usage in an ensemble of traces.
456   extern char &MachineTraceMetricsID;
457
458   /// EarlyIfConverter - This pass performs if-conversion on SSA form by
459   /// inserting cmov instructions.
460   extern char &EarlyIfConverterID;
461
462   /// StackSlotColoring - This pass performs stack coloring and merging.
463   /// It merges disjoint allocas to reduce the stack size.
464   extern char &StackColoringID;
465
466   /// IfConverter - This pass performs machine code if conversion.
467   extern char &IfConverterID;
468
469   /// MachineBlockPlacement - This pass places basic blocks based on branch
470   /// probabilities.
471   extern char &MachineBlockPlacementID;
472
473   /// MachineBlockPlacementStats - This pass collects statistics about the
474   /// basic block placement using branch probabilities and block frequency
475   /// information.
476   extern char &MachineBlockPlacementStatsID;
477
478   /// GCLowering Pass - Performs target-independent LLVM IR transformations for
479   /// highly portable strategies.
480   ///
481   FunctionPass *createGCLoweringPass();
482
483   /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
484   /// in machine code. Must be added very late during code generation, just
485   /// prior to output, and importantly after all CFG transformations (such as
486   /// branch folding).
487   extern char &GCMachineCodeAnalysisID;
488
489   /// Creates a pass to print GC metadata.
490   ///
491   FunctionPass *createGCInfoPrinter(raw_ostream &OS);
492
493   /// MachineCSE - This pass performs global CSE on machine instructions.
494   extern char &MachineCSEID;
495
496   /// MachineLICM - This pass performs LICM on machine instructions.
497   extern char &MachineLICMID;
498
499   /// MachineSinking - This pass performs sinking on machine instructions.
500   extern char &MachineSinkingID;
501
502   /// MachineCopyPropagation - This pass performs copy propagation on
503   /// machine instructions.
504   extern char &MachineCopyPropagationID;
505
506   /// PeepholeOptimizer - This pass performs peephole optimizations -
507   /// like extension and comparison eliminations.
508   extern char &PeepholeOptimizerID;
509
510   /// OptimizePHIs - This pass optimizes machine instruction PHIs
511   /// to take advantage of opportunities created during DAG legalization.
512   extern char &OptimizePHIsID;
513
514   /// StackSlotColoring - This pass performs stack slot coloring.
515   extern char &StackSlotColoringID;
516
517   /// createStackProtectorPass - This pass adds stack protectors to functions.
518   ///
519   FunctionPass *createStackProtectorPass(const TargetLoweringBase *tli);
520
521   /// createMachineVerifierPass - This pass verifies cenerated machine code
522   /// instructions for correctness.
523   ///
524   FunctionPass *createMachineVerifierPass(const char *Banner = 0);
525
526   /// createDwarfEHPass - This pass mulches exception handling code into a form
527   /// adapted to code generation.  Required if using dwarf exception handling.
528   FunctionPass *createDwarfEHPass(const TargetMachine *tm);
529
530   /// createSjLjEHPreparePass - This pass adapts exception handling code to use
531   /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
532   ///
533   FunctionPass *createSjLjEHPreparePass(const TargetLoweringBase *tli);
534
535   /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
536   /// slots relative to one another and allocates base registers to access them
537   /// when it is estimated by the target to be out of range of normal frame
538   /// pointer or stack pointer index addressing.
539   extern char &LocalStackSlotAllocationID;
540
541   /// ExpandISelPseudos - This pass expands pseudo-instructions.
542   extern char &ExpandISelPseudosID;
543
544   /// createExecutionDependencyFixPass - This pass fixes execution time
545   /// problems with dependent instructions, such as switching execution
546   /// domains to match.
547   ///
548   /// The pass will examine instructions using and defining registers in RC.
549   ///
550   FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
551
552   /// UnpackMachineBundles - This pass unpack machine instruction bundles.
553   extern char &UnpackMachineBundlesID;
554
555   /// FinalizeMachineBundles - This pass finalize machine instruction
556   /// bundles (created earlier, e.g. during pre-RA scheduling).
557   extern char &FinalizeMachineBundlesID;
558
559 } // End llvm namespace
560
561 #endif