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;
27 class PassManagerBase;
28 class TargetLoweringBase;
30 class TargetRegisterClass;
38 /// Discriminated union of Pass ID types.
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.
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.
51 /// AnalysisID is sadly char*, so PointerIntPair won't work.
52 class IdentifyingPassPtr {
59 IdentifyingPassPtr() : P(0), IsInstance(false) {}
60 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
61 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
63 bool isValid() const { return P; }
64 bool isInstance() const { return IsInstance; }
66 AnalysisID getID() const {
67 assert(!IsInstance && "Not a Pass ID");
70 Pass *getInstance() const {
71 assert(IsInstance && "Not a Pass Instance");
76 template <> struct isPodLike<IdentifyingPassPtr> {
77 static const bool value = true;
80 /// Target-Independent Code Generator Pass Configuration Options.
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 {
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.
91 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
92 /// during codegen, on SSA form.
93 static char EarlyTailDuplicateID;
95 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
96 /// optimization after regalloc.
97 static char PostRAMachineLICMID;
101 AnalysisID StartAfter;
102 AnalysisID StopAfter;
108 PassConfigImpl *Impl; // Internal data structures
109 bool Initialized; // Flagged after all passes are configured.
111 // Target Pass Options
112 // Targets provide a default setting, user flags override.
116 /// Default setting for -enable-tail-merge on this target.
117 bool EnableTailMerge;
120 TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
121 // Dummy constructor.
124 virtual ~TargetPassConfig();
128 /// Get the right type of TargetMachine for this target.
129 template<typename TMC> TMC &getTM() const {
130 return *static_cast<TMC*>(TM);
133 const TargetLowering *getTargetLowering() const {
134 return TM->getTargetLowering();
138 void setInitialized() { Initialized = true; }
140 CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
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) {
151 Started = (StartAfter == 0);
154 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
156 bool getEnableTailMerge() const { return EnableTailMerge; }
157 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
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);
164 /// Insert InsertedPassID pass after TargetPassID pass.
165 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
167 /// Allow the target to enable a specific standard pass by default.
168 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
170 /// Allow the target to disable a specific standard pass by default.
171 void disablePass(AnalysisID PassID) {
172 substitutePass(PassID, IdentifyingPassPtr());
175 /// Return the pass substituted for StandardID by the target.
176 /// If no substitution exists, return StandardID.
177 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
179 /// Return true if the optimized regalloc pipeline is enabled.
180 bool getOptimizeRegAlloc() const;
182 /// Add common target configurable passes that perform LLVM IR to IR
183 /// transforms following machine independent optimization.
184 virtual void addIRPasses();
186 /// Add passes to lower exception handling for the code generator.
187 void addPassesToHandleExceptions();
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();
193 /// Add common passes that perform LLVM IR to IR transforms in preparation for
194 /// instruction selection.
195 virtual void addISelPrepare();
197 /// addInstSelector - This method should install an instruction selector pass,
198 /// which converts from LLVM code to machine instructions.
199 virtual bool addInstSelector() {
203 /// Add the complete, standard set of LLVM CodeGen passes.
204 /// Fully developed targets will not generally override this.
205 virtual void addMachinePasses();
208 // Helper to verify the analysis is really immutable.
209 void setOpt(bool &Opt, bool Val);
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.
218 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
219 /// passes (which are run just before instruction selector).
220 virtual bool addPreISel() {
224 /// addMachineSSAOptimization - Add standard passes that optimize machine
225 /// instructions in SSA form.
226 virtual void addMachineSSAOptimization();
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.
232 /// All passes added here should preserve the MachineDominatorTree,
233 /// MachineLoopInfo, and MachineTraceMetrics analyses.
234 virtual bool addILPOpts() {
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() {
245 /// createTargetRegisterAllocator - Create the register allocator pass for
246 /// this target at the current optimization level.
247 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
249 /// addFastRegAlloc - Add the minimum set of target-independent passes that
250 /// are required for fast register allocation.
251 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
253 /// addOptimizedRegAlloc - Add passes related to register allocation.
254 /// LLVMTargetMachine provides standard regalloc passes for most targets.
255 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
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.
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() {
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() {
277 /// Add passes that optimize machine instructions after register allocation.
278 virtual void addMachineLateOptimization();
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() {
288 /// addGCPasses - Add late codegen passes that analyze code for garbage
289 /// collection. This should return true if GC info should be printed after
291 virtual bool addGCPasses();
293 /// Add standard basic block placement passes.
294 virtual void addBlockPlacement();
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() {
303 /// Utilities for targets to add passes to the pass manager.
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);
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);
314 /// addMachinePasses helper to create the target-selected or overriden
316 FunctionPass *createRegAllocPass(bool Optimized);
318 /// printAndVerify - Add a pass to dump then verify the machine function, if
319 /// those steps are enabled.
321 void printAndVerify(const char *Banner);
325 /// List of target independent CodeGen pass IDs.
327 /// \brief Create a basic TargetTransformInfo analysis pass.
329 /// This pass implements the target transform info analysis using the target
330 /// independent information available to the LLVM code generator.
332 createBasicTargetTransformInfoPass(const TargetLoweringBase *TLI);
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
340 FunctionPass *createUnreachableBlockEliminationPass();
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 ="");
348 /// MachineLoopInfo - This pass is a loop analysis pass.
349 extern char &MachineLoopInfoID;
351 /// MachineDominators - This pass is a machine dominators analysis pass.
352 extern char &MachineDominatorsID;
354 /// EdgeBundles analysis - Bundle machine CFG edges.
355 extern char &EdgeBundlesID;
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;
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;
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;
375 /// LiveIntervals - This analysis keeps track of the live ranges of virtual
376 /// and physical registers.
377 extern char &LiveIntervalsID;
379 /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
380 extern char &LiveStacksID;
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;
387 /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
388 extern char &ProcessImplicitDefsID;
390 /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
391 extern char &RegisterCoalescerID;
393 /// MachineScheduler - This pass schedules machine instructions.
394 extern char &MachineSchedulerID;
396 /// SpillPlacement analysis. Suggest optimal placement of spill code between
398 extern char &SpillPlacementID;
400 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
401 /// assigned in VirtRegMap.
402 extern char &VirtRegRewriterID;
404 /// UnreachableMachineBlockElimination - This pass removes unreachable
405 /// machine basic blocks.
406 extern char &UnreachableMachineBlockElimID;
408 /// DeadMachineInstructionElim - This pass removes dead machine instructions.
409 extern char &DeadMachineInstructionElimID;
411 /// FastRegisterAllocation Pass - This pass register allocates as fast as
412 /// possible. It is best suited for debug code where live ranges are short.
414 FunctionPass *createFastRegisterAllocator();
416 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
417 /// register allocator using the basic regalloc framework.
419 FunctionPass *createBasicRegisterAllocator();
421 /// Greedy register allocation pass - This pass implements a global register
422 /// allocator for optimized builds.
424 FunctionPass *createGreedyRegisterAllocator();
426 /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
427 /// Quadratic Prograaming (PBQP) based register allocator.
429 FunctionPass *createDefaultPBQPRegisterAllocator();
431 /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
432 /// and eliminates abstract frame references.
433 extern char &PrologEpilogCodeInserterID;
435 /// ExpandPostRAPseudos - This pass expands pseudo instructions after
436 /// register allocation.
437 extern char &ExpandPostRAPseudosID;
439 /// createPostRAScheduler - This pass performs post register allocation
441 extern char &PostRASchedulerID;
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
447 extern char &BranchFolderPassID;
449 /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
450 extern char &MachineFunctionPrinterPassID;
452 /// TailDuplicate - Duplicate blocks with unconditional branches
453 /// into tails of their predecessors.
454 extern char &TailDuplicateID;
456 /// MachineTraceMetrics - This pass computes critical path and CPU resource
457 /// usage in an ensemble of traces.
458 extern char &MachineTraceMetricsID;
460 /// EarlyIfConverter - This pass performs if-conversion on SSA form by
461 /// inserting cmov instructions.
462 extern char &EarlyIfConverterID;
464 /// StackSlotColoring - This pass performs stack coloring and merging.
465 /// It merges disjoint allocas to reduce the stack size.
466 extern char &StackColoringID;
468 /// IfConverter - This pass performs machine code if conversion.
469 extern char &IfConverterID;
471 /// MachineBlockPlacement - This pass places basic blocks based on branch
473 extern char &MachineBlockPlacementID;
475 /// MachineBlockPlacementStats - This pass collects statistics about the
476 /// basic block placement using branch probabilities and block frequency
478 extern char &MachineBlockPlacementStatsID;
480 /// GCLowering Pass - Performs target-independent LLVM IR transformations for
481 /// highly portable strategies.
483 FunctionPass *createGCLoweringPass();
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
489 extern char &GCMachineCodeAnalysisID;
491 /// Creates a pass to print GC metadata.
493 FunctionPass *createGCInfoPrinter(raw_ostream &OS);
495 /// MachineCSE - This pass performs global CSE on machine instructions.
496 extern char &MachineCSEID;
498 /// MachineLICM - This pass performs LICM on machine instructions.
499 extern char &MachineLICMID;
501 /// MachineSinking - This pass performs sinking on machine instructions.
502 extern char &MachineSinkingID;
504 /// MachineCopyPropagation - This pass performs copy propagation on
505 /// machine instructions.
506 extern char &MachineCopyPropagationID;
508 /// PeepholeOptimizer - This pass performs peephole optimizations -
509 /// like extension and comparison eliminations.
510 extern char &PeepholeOptimizerID;
512 /// OptimizePHIs - This pass optimizes machine instruction PHIs
513 /// to take advantage of opportunities created during DAG legalization.
514 extern char &OptimizePHIsID;
516 /// StackSlotColoring - This pass performs stack slot coloring.
517 extern char &StackSlotColoringID;
519 /// createStackProtectorPass - This pass adds stack protectors to functions.
521 FunctionPass *createStackProtectorPass(const TargetLoweringBase *tli);
523 /// createMachineVerifierPass - This pass verifies cenerated machine code
524 /// instructions for correctness.
526 FunctionPass *createMachineVerifierPass(const char *Banner = 0);
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 TargetLoweringBase *tli);
532 /// createSjLjEHPreparePass - This pass adapts exception handling code to use
533 /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
535 FunctionPass *createSjLjEHPreparePass(const TargetLoweringBase *tli);
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;
543 /// ExpandISelPseudos - This pass expands pseudo-instructions.
544 extern char &ExpandISelPseudosID;
546 /// createExecutionDependencyFixPass - This pass fixes execution time
547 /// problems with dependent instructions, such as switching execution
548 /// domains to match.
550 /// The pass will examine instructions using and defining registers in RC.
552 FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
554 /// UnpackMachineBundles - This pass unpack machine instruction bundles.
555 extern char &UnpackMachineBundlesID;
557 /// FinalizeMachineBundles - This pass finalize machine instruction
558 /// bundles (created earlier, e.g. during pre-RA scheduling).
559 extern char &FinalizeMachineBundlesID;
561 } // End llvm namespace