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