1 //===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 /// Target-Independent Code Generator Pass Configuration Options pass.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
14 #define LLVM_CODEGEN_TARGETPASSCONFIG_H
16 #include "llvm/Pass.h"
17 #include "llvm/Support/CodeGen.h"
23 class LLVMTargetMachine
;
24 struct MachineSchedContext
;
26 class ScheduleDAGInstrs
;
29 // The old pass manager infrastructure is hidden in a legacy namespace now.
32 class PassManagerBase
;
34 } // end namespace legacy
36 using legacy::PassManagerBase
;
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
{
57 bool IsInstance
= false;
60 IdentifyingPassPtr() : P(nullptr) {}
61 IdentifyingPassPtr(AnalysisID IDPtr
) : ID(IDPtr
) {}
62 IdentifyingPassPtr(Pass
*InstancePtr
) : P(InstancePtr
), IsInstance(true) {}
64 bool isValid() const { return P
; }
65 bool isInstance() const { return IsInstance
; }
67 AnalysisID
getID() const {
68 assert(!IsInstance
&& "Not a Pass ID");
72 Pass
*getInstance() const {
73 assert(IsInstance
&& "Not a Pass Instance");
79 /// Target-Independent Code Generator Pass Configuration Options.
81 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
82 /// to the internals of other CodeGen passes.
83 class TargetPassConfig
: public ImmutablePass
{
85 PassManagerBase
*PM
= nullptr;
86 AnalysisID StartBefore
= nullptr;
87 AnalysisID StartAfter
= nullptr;
88 AnalysisID StopBefore
= nullptr;
89 AnalysisID StopAfter
= nullptr;
91 unsigned StartBeforeInstanceNum
= 0;
92 unsigned StartBeforeCount
= 0;
94 unsigned StartAfterInstanceNum
= 0;
95 unsigned StartAfterCount
= 0;
97 unsigned StopBeforeInstanceNum
= 0;
98 unsigned StopBeforeCount
= 0;
100 unsigned StopAfterInstanceNum
= 0;
101 unsigned StopAfterCount
= 0;
104 bool Stopped
= false;
105 bool AddingMachinePasses
= false;
107 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
108 /// a portion of the normal code-gen pass sequence.
110 /// If the StartAfter and StartBefore pass ID is zero, then compilation will
111 /// begin at the normal point; otherwise, clear the Started flag to indicate
112 /// that passes should not be added until the starting pass is seen. If the
113 /// Stop pass ID is zero, then compilation will continue to the end.
115 /// This function expects that at least one of the StartAfter or the
116 /// StartBefore pass IDs is null.
117 void setStartStopPasses();
120 LLVMTargetMachine
*TM
;
121 PassConfigImpl
*Impl
= nullptr; // Internal data structures
122 bool Initialized
= false; // Flagged after all passes are configured.
124 // Target Pass Options
125 // Targets provide a default setting, user flags override.
126 bool DisableVerify
= false;
128 /// Default setting for -enable-tail-merge on this target.
129 bool EnableTailMerge
= true;
131 /// Require processing of functions such that callees are generated before
133 bool RequireCodeGenSCCOrder
= false;
135 /// Add the actual instruction selection passes. This does not include
136 /// preparation passes on IR.
137 bool addCoreISelPasses();
140 TargetPassConfig(LLVMTargetMachine
&TM
, PassManagerBase
&pm
);
141 // Dummy constructor.
144 ~TargetPassConfig() override
;
148 /// Get the right type of TargetMachine for this target.
149 template<typename TMC
> TMC
&getTM() const {
150 return *static_cast<TMC
*>(TM
);
154 void setInitialized() { Initialized
= true; }
156 CodeGenOpt::Level
getOptLevel() const;
158 /// Returns true if one of the `-start-after`, `-start-before`, `-stop-after`
159 /// or `-stop-before` options is set.
160 static bool hasLimitedCodeGenPipeline();
162 /// Returns true if none of the `-stop-before` and `-stop-after` options is
164 static bool willCompleteCodeGenPipeline();
166 /// If hasLimitedCodeGenPipeline is true, this method
167 /// returns a string with the name of the options, separated
168 /// by \p Separator that caused this pipeline to be limited.
170 getLimitedCodeGenPipelineReason(const char *Separator
= "/") const;
172 void setDisableVerify(bool Disable
) { setOpt(DisableVerify
, Disable
); }
174 bool getEnableTailMerge() const { return EnableTailMerge
; }
175 void setEnableTailMerge(bool Enable
) { setOpt(EnableTailMerge
, Enable
); }
177 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder
; }
178 void setRequiresCodeGenSCCOrder(bool Enable
= true) {
179 setOpt(RequireCodeGenSCCOrder
, Enable
);
182 /// Allow the target to override a specific pass without overriding the pass
183 /// pipeline. When passes are added to the standard pipeline at the
184 /// point where StandardID is expected, add TargetID in its place.
185 void substitutePass(AnalysisID StandardID
, IdentifyingPassPtr TargetID
);
187 /// Insert InsertedPassID pass after TargetPassID pass.
188 void insertPass(AnalysisID TargetPassID
, IdentifyingPassPtr InsertedPassID
,
189 bool VerifyAfter
= true, bool PrintAfter
= true);
191 /// Allow the target to enable a specific standard pass by default.
192 void enablePass(AnalysisID PassID
) { substitutePass(PassID
, PassID
); }
194 /// Allow the target to disable a specific standard pass by default.
195 void disablePass(AnalysisID PassID
) {
196 substitutePass(PassID
, IdentifyingPassPtr());
199 /// Return the pass substituted for StandardID by the target.
200 /// If no substitution exists, return StandardID.
201 IdentifyingPassPtr
getPassSubstitution(AnalysisID StandardID
) const;
203 /// Return true if the pass has been substituted by the target or
204 /// overridden on the command line.
205 bool isPassSubstitutedOrOverridden(AnalysisID ID
) const;
207 /// Return true if the optimized regalloc pipeline is enabled.
208 bool getOptimizeRegAlloc() const;
210 /// Return true if the default global register allocator is in use and
211 /// has not be overriden on the command line with '-regalloc=...'
212 bool usingDefaultRegAlloc() const;
214 /// High level function that adds all passes necessary to go from llvm IR
215 /// representation to the MI representation.
216 /// Adds IR based lowering and target specific optimization passes and finally
217 /// the core instruction selection passes.
218 /// \returns true if an error occurred, false otherwise.
219 bool addISelPasses();
221 /// Add common target configurable passes that perform LLVM IR to IR
222 /// transforms following machine independent optimization.
223 virtual void addIRPasses();
225 /// Add passes to lower exception handling for the code generator.
226 void addPassesToHandleExceptions();
228 /// Add pass to prepare the LLVM IR for code generation. This should be done
229 /// before exception handling preparation passes.
230 virtual void addCodeGenPrepare();
232 /// Add common passes that perform LLVM IR to IR transforms in preparation for
233 /// instruction selection.
234 virtual void addISelPrepare();
236 /// addInstSelector - This method should install an instruction selector pass,
237 /// which converts from LLVM code to machine instructions.
238 virtual bool addInstSelector() {
242 /// This method should install an IR translator pass, which converts from
243 /// LLVM code to machine instructions with possibly generic opcodes.
244 virtual bool addIRTranslator() { return true; }
246 /// This method may be implemented by targets that want to run passes
247 /// immediately before legalization.
248 virtual void addPreLegalizeMachineIR() {}
250 /// This method should install a legalize pass, which converts the instruction
251 /// sequence into one that can be selected by the target.
252 virtual bool addLegalizeMachineIR() { return true; }
254 /// This method may be implemented by targets that want to run passes
255 /// immediately before the register bank selection.
256 virtual void addPreRegBankSelect() {}
258 /// This method should install a register bank selector pass, which
259 /// assigns register banks to virtual registers without a register
260 /// class or register banks.
261 virtual bool addRegBankSelect() { return true; }
263 /// This method may be implemented by targets that want to run passes
264 /// immediately before the (global) instruction selection.
265 virtual void addPreGlobalInstructionSelect() {}
267 /// This method should install a (global) instruction selector pass, which
268 /// converts possibly generic instructions to fully target-specific
269 /// instructions, thereby constraining all generic virtual registers to
270 /// register classes.
271 virtual bool addGlobalInstructionSelect() { return true; }
273 /// Add the complete, standard set of LLVM CodeGen passes.
274 /// Fully developed targets will not generally override this.
275 virtual void addMachinePasses();
277 /// Create an instance of ScheduleDAGInstrs to be run within the standard
278 /// MachineScheduler pass for this function and target at the current
279 /// optimization level.
281 /// This can also be used to plug a new MachineSchedStrategy into an instance
282 /// of the standard ScheduleDAGMI:
283 /// return new ScheduleDAGMI(C, std::make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false)
285 /// Return NULL to select the default (generic) machine scheduler.
286 virtual ScheduleDAGInstrs
*
287 createMachineScheduler(MachineSchedContext
*C
) const {
291 /// Similar to createMachineScheduler but used when postRA machine scheduling
293 virtual ScheduleDAGInstrs
*
294 createPostMachineScheduler(MachineSchedContext
*C
) const {
298 /// printAndVerify - Add a pass to dump then verify the machine function, if
299 /// those steps are enabled.
300 void printAndVerify(const std::string
&Banner
);
302 /// Add a pass to print the machine function if printing is enabled.
303 void addPrintPass(const std::string
&Banner
);
305 /// Add a pass to perform basic verification of the machine function if
306 /// verification is enabled.
307 void addVerifyPass(const std::string
&Banner
);
309 /// Check whether or not GlobalISel should abort on error.
310 /// When this is disabled, GlobalISel will fall back on SDISel instead of
312 bool isGlobalISelAbortEnabled() const;
314 /// Check whether or not a diagnostic should be emitted when GlobalISel
315 /// uses the fallback path. In other words, it will emit a diagnostic
316 /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
317 virtual bool reportDiagnosticWhenGlobalISelFallback() const;
319 /// Check whether continuous CSE should be enabled in GISel passes.
320 /// By default, it's enabled for non O0 levels.
321 virtual bool isGISelCSEEnabled() const;
323 /// Returns the CSEConfig object to use for the current optimization level.
324 virtual std::unique_ptr
<CSEConfigBase
> getCSEConfig() const;
327 // Helper to verify the analysis is really immutable.
328 void setOpt(bool &Opt
, bool Val
);
330 /// Methods with trivial inline returns are convenient points in the common
331 /// codegen pass pipeline where targets may insert passes. Methods with
332 /// out-of-line standard implementations are major CodeGen stages called by
333 /// addMachinePasses. Some targets may override major stages when inserting
334 /// passes is insufficient, but maintaining overriden stages is more work.
337 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
338 /// passes (which are run just before instruction selector).
339 virtual bool addPreISel() {
343 /// addMachineSSAOptimization - Add standard passes that optimize machine
344 /// instructions in SSA form.
345 virtual void addMachineSSAOptimization();
347 /// Add passes that optimize instruction level parallelism for out-of-order
348 /// targets. These passes are run while the machine code is still in SSA
349 /// form, so they can use MachineTraceMetrics to control their heuristics.
351 /// All passes added here should preserve the MachineDominatorTree,
352 /// MachineLoopInfo, and MachineTraceMetrics analyses.
353 virtual bool addILPOpts() {
357 /// This method may be implemented by targets that want to run passes
358 /// immediately before register allocation.
359 virtual void addPreRegAlloc() { }
361 /// createTargetRegisterAllocator - Create the register allocator pass for
362 /// this target at the current optimization level.
363 virtual FunctionPass
*createTargetRegisterAllocator(bool Optimized
);
365 /// addFastRegAlloc - Add the minimum set of target-independent passes that
366 /// are required for fast register allocation.
367 virtual void addFastRegAlloc();
369 /// addOptimizedRegAlloc - Add passes related to register allocation.
370 /// LLVMTargetMachine provides standard regalloc passes for most targets.
371 virtual void addOptimizedRegAlloc();
373 /// addPreRewrite - Add passes to the optimized register allocation pipeline
374 /// after register allocation is complete, but before virtual registers are
375 /// rewritten to physical registers.
377 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
378 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
379 /// When these passes run, VirtRegMap contains legal physreg assignments for
380 /// all virtual registers.
382 /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
383 /// be honored. This is also not generally used for the the fast variant,
384 /// where the allocation and rewriting are done in one pass.
385 virtual bool addPreRewrite() {
389 /// Add passes to be run immediately after virtual registers are rewritten
390 /// to physical registers.
391 virtual void addPostRewrite() { }
393 /// This method may be implemented by targets that want to run passes after
394 /// register allocation pass pipeline but before prolog-epilog insertion.
395 virtual void addPostRegAlloc() { }
397 /// Add passes that optimize machine instructions after register allocation.
398 virtual void addMachineLateOptimization();
400 /// This method may be implemented by targets that want to run passes after
401 /// prolog-epilog insertion and before the second instruction scheduling pass.
402 virtual void addPreSched2() { }
404 /// addGCPasses - Add late codegen passes that analyze code for garbage
405 /// collection. This should return true if GC info should be printed after
407 virtual bool addGCPasses();
409 /// Add standard basic block placement passes.
410 virtual void addBlockPlacement();
412 /// This pass may be implemented by targets that want to run passes
413 /// immediately before machine code is emitted.
414 virtual void addPreEmitPass() { }
416 /// Targets may add passes immediately before machine code is emitted in this
417 /// callback. This is called even later than `addPreEmitPass`.
418 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
419 // position and remove the `2` suffix here as this callback is what
420 // `addPreEmitPass` *should* be but in reality isn't.
421 virtual void addPreEmitPass2() {}
423 /// Utilities for targets to add passes to the pass manager.
426 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
427 /// Return the pass that was added, or zero if no pass was added.
428 /// @p printAfter if true and adding a machine function pass add an extra
429 /// machine printer pass afterwards
430 /// @p verifyAfter if true and adding a machine function pass add an extra
431 /// machine verification pass afterwards.
432 AnalysisID
addPass(AnalysisID PassID
, bool verifyAfter
= true,
433 bool printAfter
= true);
435 /// Add a pass to the PassManager if that pass is supposed to be run, as
436 /// determined by the StartAfter and StopAfter options. Takes ownership of the
438 /// @p printAfter if true and adding a machine function pass add an extra
439 /// machine printer pass afterwards
440 /// @p verifyAfter if true and adding a machine function pass add an extra
441 /// machine verification pass afterwards.
442 void addPass(Pass
*P
, bool verifyAfter
= true, bool printAfter
= true);
444 /// addMachinePasses helper to create the target-selected or overriden
446 virtual FunctionPass
*createRegAllocPass(bool Optimized
);
448 /// Add core register alloator passes which do the actual register assignment
449 /// and rewriting. \returns true if any passes were added.
450 virtual bool addRegAssignmentFast();
451 virtual bool addRegAssignmentOptimized();
454 } // end namespace llvm
456 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H