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