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;
28 class ScheduleDAGInstrs;
30 class TargetLoweringBase;
31 class TargetRegisterClass;
33 struct MachineSchedContext;
35 // The old pass manager infrastructure is hidden in a legacy namespace now.
37 class PassManagerBase;
39 using legacy::PassManagerBase;
41 /// Discriminated union of Pass ID types.
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.
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.
54 /// AnalysisID is sadly char*, so PointerIntPair won't work.
55 class IdentifyingPassPtr {
62 IdentifyingPassPtr() : P(nullptr), IsInstance(false) {}
63 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
64 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
66 bool isValid() const { return P; }
67 bool isInstance() const { return IsInstance; }
69 AnalysisID getID() const {
70 assert(!IsInstance && "Not a Pass ID");
73 Pass *getInstance() const {
74 assert(IsInstance && "Not a Pass Instance");
79 template <> struct isPodLike<IdentifyingPassPtr> {
80 static const bool value = true;
83 /// Target-Independent Code Generator Pass Configuration Options.
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 {
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.
94 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
95 /// during codegen, on SSA form.
96 static char EarlyTailDuplicateID;
98 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
99 /// optimization after regalloc.
100 static char PostRAMachineLICMID;
104 AnalysisID StartAfter;
105 AnalysisID StopAfter;
111 PassConfigImpl *Impl; // Internal data structures
112 bool Initialized; // Flagged after all passes are configured.
114 // Target Pass Options
115 // Targets provide a default setting, user flags override.
119 /// Default setting for -enable-tail-merge on this target.
120 bool EnableTailMerge;
123 TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
124 // Dummy constructor.
127 virtual ~TargetPassConfig();
131 /// Get the right type of TargetMachine for this target.
132 template<typename TMC> TMC &getTM() const {
133 return *static_cast<TMC*>(TM);
137 void setInitialized() { Initialized = true; }
139 CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
141 /// setStartStopPasses - Set the StartAfter and StopAfter passes to allow
142 /// running only a portion of the normal code-gen pass sequence. If the
143 /// Start pass ID is zero, then compilation will begin at the normal point;
144 /// otherwise, clear the Started flag to indicate that passes should not be
145 /// added until the starting pass is seen. If the Stop pass ID is zero,
146 /// then compilation will continue to the end.
147 void setStartStopPasses(AnalysisID Start, AnalysisID Stop) {
150 Started = (StartAfter == nullptr);
153 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
155 bool getEnableTailMerge() const { return EnableTailMerge; }
156 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
158 /// Allow the target to override a specific pass without overriding the pass
159 /// pipeline. When passes are added to the standard pipeline at the
160 /// point where StandardID is expected, add TargetID in its place.
161 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
163 /// Insert InsertedPassID pass after TargetPassID pass.
164 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
166 /// Allow the target to enable a specific standard pass by default.
167 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
169 /// Allow the target to disable a specific standard pass by default.
170 void disablePass(AnalysisID PassID) {
171 substitutePass(PassID, IdentifyingPassPtr());
174 /// Return the pass substituted for StandardID by the target.
175 /// If no substitution exists, return StandardID.
176 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
178 /// Return true if the optimized regalloc pipeline is enabled.
179 bool getOptimizeRegAlloc() const;
181 /// Add common target configurable passes that perform LLVM IR to IR
182 /// transforms following machine independent optimization.
183 virtual void addIRPasses();
185 /// Add passes to lower exception handling for the code generator.
186 void addPassesToHandleExceptions();
188 /// Add pass to prepare the LLVM IR for code generation. This should be done
189 /// before exception handling preparation passes.
190 virtual void addCodeGenPrepare();
192 /// Add common passes that perform LLVM IR to IR transforms in preparation for
193 /// instruction selection.
194 virtual void addISelPrepare();
196 /// addInstSelector - This method should install an instruction selector pass,
197 /// which converts from LLVM code to machine instructions.
198 virtual bool addInstSelector() {
202 /// Add the complete, standard set of LLVM CodeGen passes.
203 /// Fully developed targets will not generally override this.
204 virtual void addMachinePasses();
206 /// Create an instance of ScheduleDAGInstrs to be run within the standard
207 /// MachineScheduler pass for this function and target at the current
208 /// optimization level.
210 /// This can also be used to plug a new MachineSchedStrategy into an instance
211 /// of the standard ScheduleDAGMI:
212 /// return new ScheduleDAGMI(C, new MyStrategy(C))
214 /// Return NULL to select the default (generic) machine scheduler.
215 virtual ScheduleDAGInstrs *
216 createMachineScheduler(MachineSchedContext *C) const {
220 /// Similar to createMachineScheduler but used when postRA machine scheduling
222 virtual ScheduleDAGInstrs *
223 createPostMachineScheduler(MachineSchedContext *C) const {
228 // Helper to verify the analysis is really immutable.
229 void setOpt(bool &Opt, bool Val);
231 /// Methods with trivial inline returns are convenient points in the common
232 /// codegen pass pipeline where targets may insert passes. Methods with
233 /// out-of-line standard implementations are major CodeGen stages called by
234 /// addMachinePasses. Some targets may override major stages when inserting
235 /// passes is insufficient, but maintaining overriden stages is more work.
238 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
239 /// passes (which are run just before instruction selector).
240 virtual bool addPreISel() {
244 /// addMachineSSAOptimization - Add standard passes that optimize machine
245 /// instructions in SSA form.
246 virtual void addMachineSSAOptimization();
248 /// Add passes that optimize instruction level parallelism for out-of-order
249 /// targets. These passes are run while the machine code is still in SSA
250 /// form, so they can use MachineTraceMetrics to control their heuristics.
252 /// All passes added here should preserve the MachineDominatorTree,
253 /// MachineLoopInfo, and MachineTraceMetrics analyses.
254 virtual bool addILPOpts() {
258 /// addPreRegAlloc - This method may be implemented by targets that want to
259 /// run passes immediately before register allocation. This should return
260 /// true if -print-machineinstrs should print after these passes.
261 virtual bool addPreRegAlloc() {
265 /// createTargetRegisterAllocator - Create the register allocator pass for
266 /// this target at the current optimization level.
267 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
269 /// addFastRegAlloc - Add the minimum set of target-independent passes that
270 /// are required for fast register allocation.
271 virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
273 /// addOptimizedRegAlloc - Add passes related to register allocation.
274 /// LLVMTargetMachine provides standard regalloc passes for most targets.
275 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
277 /// addPreRewrite - Add passes to the optimized register allocation pipeline
278 /// after register allocation is complete, but before virtual registers are
279 /// rewritten to physical registers.
281 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
282 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
283 /// When these passes run, VirtRegMap contains legal physreg assignments for
284 /// all virtual registers.
285 virtual bool addPreRewrite() {
289 /// addPostRegAlloc - This method may be implemented by targets that want to
290 /// run passes after register allocation pass pipeline but before
291 /// prolog-epilog insertion. This should return true if -print-machineinstrs
292 /// should print after these passes.
293 virtual bool addPostRegAlloc() {
297 /// Add passes that optimize machine instructions after register allocation.
298 virtual void addMachineLateOptimization();
300 /// addPreSched2 - This method may be implemented by targets that want to
301 /// run passes after prolog-epilog insertion and before the second instruction
302 /// scheduling pass. This should return true if -print-machineinstrs should
303 /// print after these passes.
304 virtual bool addPreSched2() {
308 /// addGCPasses - Add late codegen passes that analyze code for garbage
309 /// collection. This should return true if GC info should be printed after
311 virtual bool addGCPasses();
313 /// Add standard basic block placement passes.
314 virtual void addBlockPlacement();
316 /// addPreEmitPass - This pass may be implemented by targets that want to run
317 /// passes immediately before machine code is emitted. This should return
318 /// true if -print-machineinstrs should print out the code after the passes.
319 virtual bool addPreEmitPass() {
323 /// Utilities for targets to add passes to the pass manager.
326 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
327 /// Return the pass that was added, or zero if no pass was added.
328 AnalysisID addPass(AnalysisID PassID);
330 /// Add a pass to the PassManager if that pass is supposed to be run, as
331 /// determined by the StartAfter and StopAfter options. Takes ownership of the
333 void addPass(Pass *P);
335 /// addMachinePasses helper to create the target-selected or overriden
337 FunctionPass *createRegAllocPass(bool Optimized);
339 /// printAndVerify - Add a pass to dump then verify the machine function, if
340 /// those steps are enabled.
342 void printAndVerify(const char *Banner);
346 /// List of target independent CodeGen pass IDs.
348 FunctionPass *createAtomicExpandPass(const TargetMachine *TM);
350 /// \brief Create a basic TargetTransformInfo analysis pass.
352 /// This pass implements the target transform info analysis using the target
353 /// independent information available to the LLVM code generator.
355 createBasicTargetTransformInfoPass(const TargetMachine *TM);
357 /// createUnreachableBlockEliminationPass - The LLVM code generator does not
358 /// work well with unreachable basic blocks (what live ranges make sense for a
359 /// block that cannot be reached?). As such, a code generator should either
360 /// not instruction select unreachable blocks, or run this pass as its
361 /// last LLVM modifying pass to clean up blocks that are not reachable from
363 FunctionPass *createUnreachableBlockEliminationPass();
365 /// MachineFunctionPrinter pass - This pass prints out the machine function to
366 /// the given stream as a debugging tool.
367 MachineFunctionPass *
368 createMachineFunctionPrinterPass(raw_ostream &OS,
369 const std::string &Banner ="");
371 /// createCodeGenPreparePass - Transform the code to expose more pattern
372 /// matching during instruction selection.
373 FunctionPass *createCodeGenPreparePass(const TargetMachine *TM = nullptr);
375 /// AtomicExpandID -- Lowers atomic operations in terms of either cmpxchg
376 /// load-linked/store-conditional loops.
377 extern char &AtomicExpandID;
379 /// MachineLoopInfo - This pass is a loop analysis pass.
380 extern char &MachineLoopInfoID;
382 /// MachineDominators - This pass is a machine dominators analysis pass.
383 extern char &MachineDominatorsID;
385 /// MachineDominanaceFrontier - This pass is a machine dominators analysis pass.
386 extern char &MachineDominanceFrontierID;
388 /// EdgeBundles analysis - Bundle machine CFG edges.
389 extern char &EdgeBundlesID;
391 /// LiveVariables pass - This pass computes the set of blocks in which each
392 /// variable is life and sets machine operand kill flags.
393 extern char &LiveVariablesID;
395 /// PHIElimination - This pass eliminates machine instruction PHI nodes
396 /// by inserting copy instructions. This destroys SSA information, but is the
397 /// desired input for some register allocators. This pass is "required" by
398 /// these register allocator like this: AU.addRequiredID(PHIEliminationID);
399 extern char &PHIEliminationID;
401 /// LiveIntervals - This analysis keeps track of the live ranges of virtual
402 /// and physical registers.
403 extern char &LiveIntervalsID;
405 /// LiveStacks pass. An analysis keeping track of the liveness of stack slots.
406 extern char &LiveStacksID;
408 /// TwoAddressInstruction - This pass reduces two-address instructions to
409 /// use two operands. This destroys SSA information but it is desired by
410 /// register allocators.
411 extern char &TwoAddressInstructionPassID;
413 /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
414 extern char &ProcessImplicitDefsID;
416 /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
417 extern char &RegisterCoalescerID;
419 /// MachineScheduler - This pass schedules machine instructions.
420 extern char &MachineSchedulerID;
422 /// PostMachineScheduler - This pass schedules machine instructions postRA.
423 extern char &PostMachineSchedulerID;
425 /// SpillPlacement analysis. Suggest optimal placement of spill code between
427 extern char &SpillPlacementID;
429 /// VirtRegRewriter pass. Rewrite virtual registers to physical registers as
430 /// assigned in VirtRegMap.
431 extern char &VirtRegRewriterID;
433 /// UnreachableMachineBlockElimination - This pass removes unreachable
434 /// machine basic blocks.
435 extern char &UnreachableMachineBlockElimID;
437 /// DeadMachineInstructionElim - This pass removes dead machine instructions.
438 extern char &DeadMachineInstructionElimID;
440 /// FastRegisterAllocation Pass - This pass register allocates as fast as
441 /// possible. It is best suited for debug code where live ranges are short.
443 FunctionPass *createFastRegisterAllocator();
445 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
446 /// register allocator using the basic regalloc framework.
448 FunctionPass *createBasicRegisterAllocator();
450 /// Greedy register allocation pass - This pass implements a global register
451 /// allocator for optimized builds.
453 FunctionPass *createGreedyRegisterAllocator();
455 /// PBQPRegisterAllocation Pass - This pass implements the Partitioned Boolean
456 /// Quadratic Prograaming (PBQP) based register allocator.
458 FunctionPass *createDefaultPBQPRegisterAllocator();
460 /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
461 /// and eliminates abstract frame references.
462 extern char &PrologEpilogCodeInserterID;
464 /// ExpandPostRAPseudos - This pass expands pseudo instructions after
465 /// register allocation.
466 extern char &ExpandPostRAPseudosID;
468 /// createPostRAScheduler - This pass performs post register allocation
470 extern char &PostRASchedulerID;
472 /// BranchFolding - This pass performs machine code CFG based
473 /// optimizations to delete branches to branches, eliminate branches to
474 /// successor blocks (creating fall throughs), and eliminating branches over
476 extern char &BranchFolderPassID;
478 /// MachineFunctionPrinterPass - This pass prints out MachineInstr's.
479 extern char &MachineFunctionPrinterPassID;
481 /// TailDuplicate - Duplicate blocks with unconditional branches
482 /// into tails of their predecessors.
483 extern char &TailDuplicateID;
485 /// MachineTraceMetrics - This pass computes critical path and CPU resource
486 /// usage in an ensemble of traces.
487 extern char &MachineTraceMetricsID;
489 /// EarlyIfConverter - This pass performs if-conversion on SSA form by
490 /// inserting cmov instructions.
491 extern char &EarlyIfConverterID;
493 /// This pass performs instruction combining using trace metrics to estimate
494 /// critical-path and resource depth.
495 extern char &MachineCombinerID;
497 /// StackSlotColoring - This pass performs stack coloring and merging.
498 /// It merges disjoint allocas to reduce the stack size.
499 extern char &StackColoringID;
501 /// IfConverter - This pass performs machine code if conversion.
502 extern char &IfConverterID;
504 /// MachineBlockPlacement - This pass places basic blocks based on branch
506 extern char &MachineBlockPlacementID;
508 /// MachineBlockPlacementStats - This pass collects statistics about the
509 /// basic block placement using branch probabilities and block frequency
511 extern char &MachineBlockPlacementStatsID;
513 /// GCLowering Pass - Performs target-independent LLVM IR transformations for
514 /// highly portable strategies.
516 FunctionPass *createGCLoweringPass();
518 /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
519 /// in machine code. Must be added very late during code generation, just
520 /// prior to output, and importantly after all CFG transformations (such as
522 extern char &GCMachineCodeAnalysisID;
524 /// Creates a pass to print GC metadata.
526 FunctionPass *createGCInfoPrinter(raw_ostream &OS);
528 /// MachineCSE - This pass performs global CSE on machine instructions.
529 extern char &MachineCSEID;
531 /// MachineLICM - This pass performs LICM on machine instructions.
532 extern char &MachineLICMID;
534 /// MachineSinking - This pass performs sinking on machine instructions.
535 extern char &MachineSinkingID;
537 /// MachineCopyPropagation - This pass performs copy propagation on
538 /// machine instructions.
539 extern char &MachineCopyPropagationID;
541 /// PeepholeOptimizer - This pass performs peephole optimizations -
542 /// like extension and comparison eliminations.
543 extern char &PeepholeOptimizerID;
545 /// OptimizePHIs - This pass optimizes machine instruction PHIs
546 /// to take advantage of opportunities created during DAG legalization.
547 extern char &OptimizePHIsID;
549 /// StackSlotColoring - This pass performs stack slot coloring.
550 extern char &StackSlotColoringID;
552 /// createStackProtectorPass - This pass adds stack protectors to functions.
554 FunctionPass *createStackProtectorPass(const TargetMachine *TM);
556 /// createMachineVerifierPass - This pass verifies cenerated machine code
557 /// instructions for correctness.
559 FunctionPass *createMachineVerifierPass(const char *Banner = nullptr);
561 /// createDwarfEHPass - This pass mulches exception handling code into a form
562 /// adapted to code generation. Required if using dwarf exception handling.
563 FunctionPass *createDwarfEHPass(const TargetMachine *TM);
565 /// createSjLjEHPreparePass - This pass adapts exception handling code to use
566 /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control flow.
568 FunctionPass *createSjLjEHPreparePass(const TargetMachine *TM);
570 /// LocalStackSlotAllocation - This pass assigns local frame indices to stack
571 /// slots relative to one another and allocates base registers to access them
572 /// when it is estimated by the target to be out of range of normal frame
573 /// pointer or stack pointer index addressing.
574 extern char &LocalStackSlotAllocationID;
576 /// ExpandISelPseudos - This pass expands pseudo-instructions.
577 extern char &ExpandISelPseudosID;
579 /// createExecutionDependencyFixPass - This pass fixes execution time
580 /// problems with dependent instructions, such as switching execution
581 /// domains to match.
583 /// The pass will examine instructions using and defining registers in RC.
585 FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass *RC);
587 /// UnpackMachineBundles - This pass unpack machine instruction bundles.
588 extern char &UnpackMachineBundlesID;
590 /// FinalizeMachineBundles - This pass finalize machine instruction
591 /// bundles (created earlier, e.g. during pre-RA scheduling).
592 extern char &FinalizeMachineBundlesID;
594 /// StackMapLiveness - This pass analyses the register live-out set of
595 /// stackmap/patchpoint intrinsics and attaches the calculated information to
596 /// the intrinsic for later emission to the StackMap.
597 extern char &StackMapLivenessID;
599 /// createJumpInstrTables - This pass creates jump-instruction tables.
600 ModulePass *createJumpInstrTablesPass();
601 } // End llvm namespace
603 /// This initializer registers TargetMachine constructor, so the pass being
604 /// initialized can use target dependent interfaces. Please do not move this
605 /// macro to be together with INITIALIZE_PASS, which is a complete target
606 /// independent initializer, and we don't want to make libScalarOpts depend
608 #define INITIALIZE_TM_PASS(passName, arg, name, cfg, analysis) \
609 static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
610 PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
611 PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis, \
612 PassInfo::TargetMachineCtor_t(callTargetMachineCtor< passName >)); \
613 Registry.registerPass(*PI, true); \
616 void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
617 CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \