LLVM API Documentation

CodeGen/Passes.h
Go to the documentation of this file.
00001 //===-- Passes.h - Target independent code generation passes ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines interfaces to access the target independent code generation
00011 // passes provided by the LLVM backend.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CODEGEN_PASSES_H
00016 #define LLVM_CODEGEN_PASSES_H
00017 
00018 #include "llvm/Pass.h"
00019 #include "llvm/Target/TargetMachine.h"
00020 #include <string>
00021 
00022 namespace llvm {
00023 
00024   class FunctionPass;
00025   class MachineFunctionPass;
00026   class PassInfo;
00027   class PassManagerBase;
00028   class TargetLoweringBase;
00029   class TargetLowering;
00030   class TargetRegisterClass;
00031   class raw_ostream;
00032 }
00033 
00034 namespace llvm {
00035 
00036 class PassConfigImpl;
00037 
00038 /// Discriminated union of Pass ID types.
00039 ///
00040 /// The PassConfig API prefers dealing with IDs because they are safer and more
00041 /// efficient. IDs decouple configuration from instantiation. This way, when a
00042 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
00043 /// refer to a Pass pointer after adding it to a pass manager, which deletes
00044 /// redundant pass instances.
00045 ///
00046 /// However, it is convient to directly instantiate target passes with
00047 /// non-default ctors. These often don't have a registered PassInfo. Rather than
00048 /// force all target passes to implement the pass registry boilerplate, allow
00049 /// the PassConfig API to handle either type.
00050 ///
00051 /// AnalysisID is sadly char*, so PointerIntPair won't work.
00052 class IdentifyingPassPtr {
00053   union {
00054     AnalysisID ID;
00055     Pass *P;
00056   };
00057   bool IsInstance;
00058 public:
00059   IdentifyingPassPtr() : P(0), IsInstance(false) {}
00060   IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
00061   IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
00062 
00063   bool isValid() const { return P; }
00064   bool isInstance() const { return IsInstance; }
00065 
00066   AnalysisID getID() const {
00067     assert(!IsInstance && "Not a Pass ID");
00068     return ID;
00069   }
00070   Pass *getInstance() const {
00071     assert(IsInstance && "Not a Pass Instance");
00072     return P;
00073   }
00074 };
00075 
00076 template <> struct isPodLike<IdentifyingPassPtr> {
00077   static const bool value = true;
00078 };
00079 
00080 /// Target-Independent Code Generator Pass Configuration Options.
00081 ///
00082 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
00083 /// to the internals of other CodeGen passes.
00084 class TargetPassConfig : public ImmutablePass {
00085 public:
00086   /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
00087   /// are unregistered pass IDs. They are only useful for use with
00088   /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
00089   ///
00090 
00091   /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
00092   /// during codegen, on SSA form.
00093   static char EarlyTailDuplicateID;
00094 
00095   /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
00096   /// optimization after regalloc.
00097   static char PostRAMachineLICMID;
00098 
00099 private:
00100   PassManagerBase *PM;
00101   AnalysisID StartAfter;
00102   AnalysisID StopAfter;
00103   bool Started;
00104   bool Stopped;
00105 
00106 protected:
00107   TargetMachine *TM;
00108   PassConfigImpl *Impl; // Internal data structures
00109   bool Initialized;     // Flagged after all passes are configured.
00110 
00111   // Target Pass Options
00112   // Targets provide a default setting, user flags override.
00113   //
00114   bool DisableVerify;
00115 
00116   /// Default setting for -enable-tail-merge on this target.
00117   bool EnableTailMerge;
00118 
00119 public:
00120   TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
00121   // Dummy constructor.
00122   TargetPassConfig();
00123 
00124   virtual ~TargetPassConfig();
00125 
00126   static char ID;
00127 
00128   /// Get the right type of TargetMachine for this target.
00129   template<typename TMC> TMC &getTM() const {
00130     return *static_cast<TMC*>(TM);
00131   }
00132 
00133   const TargetLowering *getTargetLowering() const {
00134     return TM->getTargetLowering();
00135   }
00136 
00137   //
00138   void setInitialized() { Initialized = true; }
00139 
00140   CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
00141 
00142   /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
00143   /// running only a portion of the normal code-gen pass sequence.  If the
00144   /// Start pass ID is zero, then compilation will begin at the normal point;
00145   /// otherwise, clear the Started flag to indicate that passes should not be
00146   /// added until the starting pass is seen.  If the Stop pass ID is zero,
00147   /// then compilation will continue to the end.
00148   void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
00149     StartAfter = Start;
00150     StopAfter = Stop;
00151     Started = (StartAfter == 0);
00152   }
00153 
00154   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
00155 
00156   bool getEnableTailMerge() const { return EnableTailMerge; }
00157   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
00158 
00159   /// Allow the target to override a specific pass without overriding the pass
00160   /// pipeline. When passes are added to the standard pipeline at the
00161   /// point where StandardID is expected, add TargetID in its place.
00162   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
00163 
00164   /// Insert InsertedPassID pass after TargetPassID pass.
00165   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
00166 
00167   /// Allow the target to enable a specific standard pass by default.
00168   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
00169 
00170   /// Allow the target to disable a specific standard pass by default.
00171   void disablePass(AnalysisID PassID) {
00172     substitutePass(PassID, IdentifyingPassPtr());
00173   }
00174 
00175   /// Return the pass substituted for StandardID by the target.
00176   /// If no substitution exists, return StandardID.
00177   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
00178 
00179   /// Return true if the optimized regalloc pipeline is enabled.
00180   bool getOptimizeRegAlloc() const;
00181 
00182   /// Add common target configurable passes that perform LLVM IR to IR
00183   /// transforms following machine independent optimization.
00184   virtual void addIRPasses();
00185 
00186   /// Add passes to lower exception handling for the code generator.
00187   void addPassesToHandleExceptions();
00188 
00189   /// Add pass to prepare the LLVM IR for code generation. This should be done
00190   /// before exception handling preparation passes.
00191   virtual void addCodeGenPrepare();
00192 
00193   /// Add common passes that perform LLVM IR to IR transforms in preparation for
00194   /// instruction selection.
00195   virtual void addISelPrepare();
00196 
00197   /// addInstSelector - This method should install an instruction selector pass,
00198   /// which converts from LLVM code to machine instructions.
00199   virtual bool addInstSelector() {
00200     return true;
00201   }
00202 
00203   /// Add the complete, standard set of LLVM CodeGen passes.
00204   /// Fully developed targets will not generally override this.
00205   virtual void addMachinePasses();
00206 
00207 protected:
00208   // Helper to verify the analysis is really immutable.
00209   void setOpt(bool &Opt, bool Val);
00210 
00211   /// Methods with trivial inline returns are convenient points in the common
00212   /// codegen pass pipeline where targets may insert passes. Methods with
00213   /// out-of-line standard implementations are major CodeGen stages called by
00214   /// addMachinePasses. Some targets may override major stages when inserting
00215   /// passes is insufficient, but maintaining overriden stages is more work.
00216   ///
00217 
00218   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
00219   /// passes (which are run just before instruction selector).
00220   virtual bool addPreISel() {
00221     return true;
00222   }
00223 
00224   /// addMachineSSAOptimization - Add standard passes that optimize machine
00225   /// instructions in SSA form.
00226   virtual void addMachineSSAOptimization();
00227 
00228   /// Add passes that optimize instruction level parallelism for out-of-order
00229   /// targets. These passes are run while the machine code is still in SSA
00230   /// form, so they can use MachineTraceMetrics to control their heuristics.
00231   ///
00232   /// All passes added here should preserve the MachineDominatorTree,
00233   /// MachineLoopInfo, and MachineTraceMetrics analyses.
00234   virtual bool addILPOpts() {
00235     return false;
00236   }
00237 
00238   /// addPreRegAlloc - This method may be implemented by targets that want to
00239   /// run passes immediately before register allocation. This should return
00240   /// true if -print-machineinstrs should print after these passes.
00241   virtual bool addPreRegAlloc() {
00242     return false;
00243   }
00244 
00245   /// createTargetRegisterAllocator - Create the register allocator pass for
00246   /// this target at the current optimization level.
00247   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
00248 
00249   /// addFastRegAlloc - Add the minimum set of target-independent passes that
00250   /// are required for fast register allocation.
00251   virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
00252 
00253   /// addOptimizedRegAlloc - Add passes related to register allocation.
00254   /// LLVMTargetMachine provides standard regalloc passes for most targets.
00255   virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
00256 
00257   /// addPreRewrite - Add passes to the optimized register allocation pipeline
00258   /// after register allocation is complete, but before virtual registers are
00259   /// rewritten to physical registers.
00260   ///
00261   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
00262   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
00263   /// When these passes run, VirtRegMap contains legal physreg assignments for
00264   /// all virtual registers.
00265   virtual bool addPreRewrite() {
00266     return false;
00267   }
00268 
00269   /// addPostRegAlloc - This method may be implemented by targets that want to
00270   /// run passes after register allocation pass pipeline but before
00271   /// prolog-epilog insertion.  This should return true if -print-machineinstrs
00272   /// should print after these passes.
00273   virtual bool addPostRegAlloc() {
00274     return false;
00275   }
00276 
00277   /// Add passes that optimize machine instructions after register allocation.
00278   virtual void addMachineLateOptimization();
00279 
00280   /// addPreSched2 - This method may be implemented by targets that want to
00281   /// run passes after prolog-epilog insertion and before the second instruction
00282   /// scheduling pass.  This should return true if -print-machineinstrs should
00283   /// print after these passes.
00284   virtual bool addPreSched2() {
00285     return false;
00286   }
00287 
00288   /// addGCPasses - Add late codegen passes that analyze code for garbage
00289   /// collection. This should return true if GC info should be printed after
00290   /// these passes.
00291   virtual bool addGCPasses();
00292 
00293   /// Add standard basic block placement passes.
00294   virtual void addBlockPlacement();
00295 
00296   /// addPreEmitPass - This pass may be implemented by targets that want to run
00297   /// passes immediately before machine code is emitted.  This should return
00298   /// true if -print-machineinstrs should print out the code after the passes.
00299   virtual bool addPreEmitPass() {
00300     return false;
00301   }
00302 
00303   /// Utilities for targets to add passes to the pass manager.
00304   ///
00305 
00306   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
00307   /// Return the pass that was added, or zero if no pass was added.
00308   AnalysisID addPass(AnalysisID PassID);
00309 
00310   /// Add a pass to the PassManager if that pass is supposed to be run, as
00311   /// determined by the StartAfter and StopAfter options.
00312   void addPass(Pass *P);
00313 
00314   /// addMachinePasses helper to create the target-selected or overriden
00315   /// regalloc pass.
00316   FunctionPass *createRegAllocPass(bool Optimized);
00317 
00318   /// printAndVerify - Add a pass to dump then verify the machine function, if
00319   /// those steps are enabled.
00320   ///
00321   void printAndVerify(const char *Banner);
00322 };
00323 } // namespace llvm
00324 
00325 /// List of target independent CodeGen pass IDs.
00326 namespace llvm {
00327   /// \brief Create a basic TargetTransformInfo analysis pass.
00328   ///
00329   /// This pass implements the target transform info analysis using the target
00330   /// independent information available to the LLVM code generator.
00331   ImmutablePass *
00332   createBasicTargetTransformInfoPass(const TargetMachine *TM);
00333 
00334   /// createUnreachableBlockEliminationPass - The LLVM code generator does not
00335   /// work well with unreachable basic blocks (what live ranges make sense for a
00336   /// block that cannot be reached?).  As such, a code generator should either
00337   /// not instruction select unreachable blocks, or run this pass as its
00338   /// last LLVM modifying pass to clean up blocks that are not reachable from
00339   /// the entry block.
00340   FunctionPass *createUnreachableBlockEliminationPass();
00341 
00342   /// MachineFunctionPrinter pass - This pass prints out the machine function to
00343   /// the given stream as a debugging tool.
00344   MachineFunctionPass *
00345   createMachineFunctionPrinterPass(raw_ostream &OS,
00346                                    const std::string &Banner ="");
00347 
00348   /// MachineLoopInfo - This pass is a loop analysis pass.
00349   extern char &MachineLoopInfoID;
00350 
00351   /// MachineDominators - This pass is a machine dominators analysis pass.
00352   extern char &MachineDominatorsID;
00353 
00354   /// EdgeBundles analysis - Bundle machine CFG edges.
00355   extern char &EdgeBundlesID;
00356 
00357   /// LiveVariables pass - This pass computes the set of blocks in which each
00358   /// variable is life and sets machine operand kill flags.
00359   extern char &LiveVariablesID;
00360 
00361   /// PHIElimination - This pass eliminates machine instruction PHI nodes
00362   /// by inserting copy instructions.  This destroys SSA information, but is the
00363   /// desired input for some register allocators.  This pass is "required" by
00364   /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
00365   extern char &PHIEliminationID;
00366 
00367   /// StrongPHIElimination - This pass eliminates machine instruction PHI
00368   /// nodes by inserting copy instructions.  This destroys SSA information, but
00369   /// is the desired input for some register allocators.  This pass is
00370   /// "required" by these register allocator like this:
00371   ///    AU.addRequiredID(PHIEliminationID);
00372   ///  This pass is still in development
00373   extern char &StrongPHIEliminationID;
00374 
00375   /// LiveIntervals - This analysis keeps track of the live ranges of virtual
00376   /// and physical registers.
00377   extern char &LiveIntervalsID;
00378 
00379   /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
00380   extern char &LiveStacksID;
00381 
00382   /// TwoAddressInstruction - This pass reduces two-address instructions to
00383   /// use two operands. This destroys SSA information but it is desired by
00384   /// register allocators.
00385   extern char &TwoAddressInstructionPassID;
00386 
00387   /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
00388   extern char &ProcessImplicitDefsID;
00389 
00390   /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
00391   extern char &RegisterCoalescerID;
00392 
00393   /// MachineScheduler - This pass schedules machine instructions.
00394   extern char &MachineSchedulerID;
00395 
00396   /// SpillPlacement analysis. Suggest optimal placement of spill code between
00397   /// basic blocks.
00398   extern char &SpillPlacementID;
00399 
00400   /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
00401   /// assigned in VirtRegMap.
00402   extern char &VirtRegRewriterID;
00403 
00404   /// UnreachableMachineBlockElimination - This pass removes unreachable
00405   /// machine basic blocks.
00406   extern char &UnreachableMachineBlockElimID;
00407 
00408   /// DeadMachineInstructionElim - This pass removes dead machine instructions.
00409   extern char &DeadMachineInstructionElimID;
00410 
00411   /// FastRegisterAllocation Pass - This pass register allocates as fast as
00412   /// possible. It is best suited for debug code where live ranges are short.
00413   ///
00414   FunctionPass *createFastRegisterAllocator();
00415 
00416   /// BasicRegisterAllocation Pass - This pass implements a degenerate global
00417   /// register allocator using the basic regalloc framework.
00418   ///
00419   FunctionPass *createBasicRegisterAllocator();
00420 
00421   /// Greedy register allocation pass - This pass implements a global register
00422   /// allocator for optimized builds.
00423   ///
00424   FunctionPass *createGreedyRegisterAllocator();
00425 
00426   /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
00427   /// Quadratic Prograaming (PBQP) based register allocator.
00428   ///
00429   FunctionPass *createDefaultPBQPRegisterAllocator();
00430 
00431   /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
00432   /// and eliminates abstract frame references.
00433   extern char &PrologEpilogCodeInserterID;
00434 
00435   /// ExpandPostRAPseudos - This pass expands pseudo instructions after
00436   /// register allocation.
00437   extern char &ExpandPostRAPseudosID;
00438 
00439   /// createPostRAScheduler - This pass performs post register allocation
00440   /// scheduling.
00441   extern char &PostRASchedulerID;
00442 
00443   /// BranchFolding - This pass performs machine code CFG based
00444   /// optimizations to delete branches to branches, eliminate branches to
00445   /// successor blocks (creating fall throughs), and eliminating branches over
00446   /// branches.
00447   extern char &BranchFolderPassID;
00448 
00449   /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
00450   extern char &MachineFunctionPrinterPassID;
00451 
00452   /// TailDuplicate - Duplicate blocks with unconditional branches
00453   /// into tails of their predecessors.
00454   extern char &TailDuplicateID;
00455 
00456   /// MachineTraceMetrics - This pass computes critical path and CPU resource
00457   /// usage in an ensemble of traces.
00458   extern char &MachineTraceMetricsID;
00459 
00460   /// EarlyIfConverter - This pass performs if-conversion on SSA form by
00461   /// inserting cmov instructions.
00462   extern char &EarlyIfConverterID;
00463 
00464   /// StackSlotColoring - This pass performs stack coloring and merging.
00465   /// It merges disjoint allocas to reduce the stack size.
00466   extern char &StackColoringID;
00467 
00468   /// IfConverter - This pass performs machine code if conversion.
00469   extern char &IfConverterID;
00470 
00471   /// MachineBlockPlacement - This pass places basic blocks based on branch
00472   /// probabilities.
00473   extern char &MachineBlockPlacementID;
00474 
00475   /// MachineBlockPlacementStats - This pass collects statistics about the
00476   /// basic block placement using branch probabilities and block frequency
00477   /// information.
00478   extern char &MachineBlockPlacementStatsID;
00479 
00480   /// GCLowering Pass - Performs target-independent LLVM IR transformations for
00481   /// highly portable strategies.
00482   ///
00483   FunctionPass *createGCLoweringPass();
00484 
00485   /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
00486   /// in machine code. Must be added very late during code generation, just
00487   /// prior to output, and importantly after all CFG transformations (such as
00488   /// branch folding).
00489   extern char &GCMachineCodeAnalysisID;
00490 
00491   /// Creates a pass to print GC metadata.
00492   ///
00493   FunctionPass *createGCInfoPrinter(raw_ostream &OS);
00494 
00495   /// MachineCSE - This pass performs global CSE on machine instructions.
00496   extern char &MachineCSEID;
00497 
00498   /// MachineLICM - This pass performs LICM on machine instructions.
00499   extern char &MachineLICMID;
00500 
00501   /// MachineSinking - This pass performs sinking on machine instructions.
00502   extern char &MachineSinkingID;
00503 
00504   /// MachineCopyPropagation - This pass performs copy propagation on
00505   /// machine instructions.
00506   extern char &MachineCopyPropagationID;
00507 
00508   /// PeepholeOptimizer - This pass performs peephole optimizations -
00509   /// like extension and comparison eliminations.
00510   extern char &PeepholeOptimizerID;
00511 
00512   /// OptimizePHIs - This pass optimizes machine instruction PHIs
00513   /// to take advantage of opportunities created during DAG legalization.
00514   extern char &OptimizePHIsID;
00515 
00516   /// StackSlotColoring - This pass performs stack slot coloring.
00517   extern char &StackSlotColoringID;
00518 
00519   /// createStackProtectorPass - This pass adds stack protectors to functions.
00520   ///
00521   FunctionPass *createStackProtectorPass(const TargetMachine *TM);
00522 
00523   /// createMachineVerifierPass - This pass verifies cenerated machine code
00524   /// instructions for correctness.
00525   ///
00526   FunctionPass *createMachineVerifierPass(const char *Banner = 0);
00527 
00528   /// createDwarfEHPass - This pass mulches exception handling code into a form
00529   /// adapted to code generation.  Required if using dwarf exception handling.
00530   FunctionPass *createDwarfEHPass(const TargetMachine *TM);
00531 
00532   /// createSjLjEHPreparePass - This pass adapts exception handling code to use
00533   /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
00534   ///
00535   FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
00536 
00537   /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
00538   /// slots relative to one another and allocates base registers to access them
00539   /// when it is estimated by the target to be out of range of normal frame
00540   /// pointer or stack pointer index addressing.
00541   extern char &LocalStackSlotAllocationID;
00542 
00543   /// ExpandISelPseudos - This pass expands pseudo-instructions.
00544   extern char &ExpandISelPseudosID;
00545 
00546   /// createExecutionDependencyFixPass - This pass fixes execution time
00547   /// problems with dependent instructions, such as switching execution
00548   /// domains to match.
00549   ///
00550   /// The pass will examine instructions using and defining registers in RC.
00551   ///
00552   FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
00553 
00554   /// UnpackMachineBundles - This pass unpack machine instruction bundles.
00555   extern char &UnpackMachineBundlesID;
00556 
00557   /// FinalizeMachineBundles - This pass finalize machine instruction
00558   /// bundles (created earlier, e.g. during pre-RA scheduling).
00559   extern char &FinalizeMachineBundlesID;
00560 
00561 } // End llvm namespace
00562 
00563 #endif