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