1//===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// Target-Independent Code Generator Pass Configuration Options pass.
10///
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
14#define LLVM_CODEGEN_TARGETPASSCONFIG_H
15
16#include "llvm/Pass.h"
17#include "llvm/Support/CodeGen.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/Error.h"
20#include <cassert>
21#include <string>
22
23namespace llvm {
24
25class TargetMachine;
26class PassConfigImpl;
27struct CodeGenOptions;
28class CSEConfigBase;
29class PassInstrumentationCallbacks;
30
31// The old pass manager infrastructure is hidden in a legacy namespace now.
32namespace legacy {
33
34class PassManagerBase;
35
36} // end namespace legacy
37
38using legacy::PassManagerBase;
39
40/// Discriminated union of Pass ID types.
41///
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.
47///
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.
52///
53/// AnalysisID is sadly char*, so PointerIntPair won't work.
54class IdentifyingPassPtr {
55 union {
56 AnalysisID ID;
57 Pass *P;
58 };
59 bool IsInstance = false;
60
61public:
62 IdentifyingPassPtr() : P(nullptr) {}
63 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr) {}
64 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
65
66 bool isValid() const { return P; }
67 bool isInstance() const { return IsInstance; }
68
69 AnalysisID getID() const {
70 assert(!IsInstance && "Not a Pass ID");
71 return ID;
72 }
73
74 Pass *getInstance() const {
75 assert(IsInstance && "Not a Pass Instance");
76 return P;
77 }
78};
79
80
81/// Target-Independent Code Generator Pass Configuration Options.
82///
83/// This is an ImmutablePass solely for the purpose of exposing CodeGen options
84/// to the internals of other CodeGen passes.
85class LLVM_ABI TargetPassConfig : public ImmutablePass {
86private:
87 PassManagerBase *PM = nullptr;
88 const CodeGenOptions &Opts;
89 AnalysisID StartBefore = nullptr;
90 AnalysisID StartAfter = nullptr;
91 AnalysisID StopBefore = nullptr;
92 AnalysisID StopAfter = nullptr;
93
94 unsigned StartBeforeInstanceNum = 0;
95 unsigned StartBeforeCount = 0;
96
97 unsigned StartAfterInstanceNum = 0;
98 unsigned StartAfterCount = 0;
99
100 unsigned StopBeforeInstanceNum = 0;
101 unsigned StopBeforeCount = 0;
102
103 unsigned StopAfterInstanceNum = 0;
104 unsigned StopAfterCount = 0;
105
106 bool Started = true;
107 bool Stopped = false;
108 bool AddingMachinePasses = false;
109 bool DebugifyIsSafe = true;
110
111 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
112 /// a portion of the normal code-gen pass sequence.
113 ///
114 /// If the StartAfter and StartBefore pass ID is zero, then compilation will
115 /// begin at the normal point; otherwise, clear the Started flag to indicate
116 /// that passes should not be added until the starting pass is seen. If the
117 /// Stop pass ID is zero, then compilation will continue to the end.
118 ///
119 /// This function expects that at least one of the StartAfter or the
120 /// StartBefore pass IDs is null.
121 void setStartStopPasses();
122
123protected:
124 TargetMachine *TM;
125 PassConfigImpl *Impl = nullptr; // Internal data structures
126 bool Initialized = false; // Flagged after all passes are configured.
127
128 // Target Pass Options
129 // Targets provide a default setting, user flags override.
130 bool DisableVerify = false;
131
132 MachineVerifierMode VerifyMode = MachineVerifierMode::End;
133
134 /// Default setting for -enable-tail-merge on this target.
135 bool EnableTailMerge = true;
136
137 /// Enable sinking of instructions in MachineSink where a computation can be
138 /// folded into the addressing mode of a memory load/store instruction or
139 /// replace a copy.
140 bool EnableSinkAndFold = false;
141
142 /// Enable insertion of SSAMachineScheduler pass, this triggers early
143 /// computation of live intervals.
144 bool EnableSSAMachineScheduler = false;
145
146 /// Require processing of functions such that callees are generated before
147 /// callers.
148 bool RequireCodeGenSCCOrder = false;
149
150 /// Enable LoopTermFold immediately after LSR
151 bool EnableLoopTermFold = false;
152
153 /// Add the actual instruction selection passes. This does not include
154 /// preparation passes on IR.
155 bool addCoreISelPasses();
156
157public:
158 TargetPassConfig(TargetMachine &TM, PassManagerBase &PM);
159
160 ~TargetPassConfig() override;
161
162 static char ID;
163
164 /// Get the right type of TargetMachine for this target.
165 template<typename TMC> TMC &getTM() const {
166 return *static_cast<TMC*>(TM);
167 }
168
169 //
170 void setInitialized() { Initialized = true; }
171
172 CodeGenOptLevel getOptLevel() const;
173
174 /// Returns true if one of the `-start-after`, `-start-before`, `-stop-after`
175 /// or `-stop-before` options is set.
176 bool hasLimitedCodeGenPipeline() const;
177
178 /// Returns true if none of the `-stop-before` and `-stop-after` options is
179 /// set.
180 bool willCompleteCodeGenPipeline() const;
181
182 /// If hasLimitedCodeGenPipeline is true, this method returns
183 /// a string with the name of the options that caused this
184 /// pipeline to be limited.
185 std::string getLimitedCodeGenPipelineReason() const;
186
187 struct StartStopInfo {
188 bool StartAfter;
189 bool StopAfter;
190 unsigned StartInstanceNum;
191 unsigned StopInstanceNum;
192 StringRef StartPass;
193 StringRef StopPass;
194
195 /// Returns true if a start or stop pass is set.
196 bool isLimited() const { return !StartPass.empty() || !StopPass.empty(); }
197
198 /// Returns the names of the options that set the start and stop passes.
199 LLVM_ABI std::string getLimitReason() const;
200 };
201
202 /// Returns pass name in `-stop-before` or `-stop-after`
203 /// NOTE: New pass manager migration only
204 static Expected<StartStopInfo>
205 getStartStopInfo(const TargetMachine &TM, PassInstrumentationCallbacks &PIC);
206
207 void setDisableVerify(bool Disable) { setOpt(Opt&: DisableVerify, Val: Disable); }
208
209 /// Return where the machine verifier runs in the pipeline.
210 MachineVerifierMode getMachineVerifierMode() const { return VerifyMode; }
211
212 bool getEnableTailMerge() const { return EnableTailMerge; }
213 void setEnableTailMerge(bool Enable) { setOpt(Opt&: EnableTailMerge, Val: Enable); }
214
215 bool getEnableSinkAndFold() const { return EnableSinkAndFold; }
216 void setEnableSinkAndFold(bool Enable) { setOpt(Opt&: EnableSinkAndFold, Val: Enable); }
217
218 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; }
219 void setRequiresCodeGenSCCOrder(bool Enable = true) {
220 setOpt(Opt&: RequireCodeGenSCCOrder, Val: Enable);
221 }
222
223 bool getEnableSSAMachineScheduler() const {
224 return EnableSSAMachineScheduler;
225 }
226 void setEnableSSAMachineScheduler(bool Enable) {
227 setOpt(Opt&: EnableSSAMachineScheduler, Val: Enable);
228 }
229
230 /// Allow the target to override a specific pass without overriding the pass
231 /// pipeline. When passes are added to the standard pipeline at the
232 /// point where StandardID is expected, add TargetID in its place.
233 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
234
235 /// Insert InsertedPassID pass after TargetPassID pass.
236 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
237
238 /// Allow the target to enable a specific standard pass by default.
239 void enablePass(AnalysisID PassID) { substitutePass(StandardID: PassID, TargetID: PassID); }
240
241 /// Allow the target to disable a specific standard pass by default.
242 void disablePass(AnalysisID PassID) {
243 substitutePass(StandardID: PassID, TargetID: IdentifyingPassPtr());
244 }
245
246 /// Return the pass substituted for StandardID by the target.
247 /// If no substitution exists, return StandardID.
248 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
249
250 /// Return true if the pass has been substituted by the target or
251 /// overridden on the command line.
252 bool isPassSubstitutedOrOverridden(AnalysisID ID) const;
253
254 /// Return true if the optimized regalloc pipeline is enabled.
255 bool getOptimizeRegAlloc() const;
256
257 /// Return true if the default global register allocator is in use and
258 /// has not be overriden on the command line with '-regalloc=...'
259 bool usingDefaultRegAlloc() const;
260
261 /// High level function that adds all passes necessary to go from llvm IR
262 /// representation to the MI representation.
263 /// Adds IR based lowering and target specific optimization passes and finally
264 /// the core instruction selection passes.
265 /// \returns true if an error occurred, false otherwise.
266 bool addISelPasses();
267
268 /// Add common target configurable passes that perform LLVM IR to IR
269 /// transforms following machine independent optimization.
270 virtual void addIRPasses();
271
272 /// Add passes to lower exception handling for the code generator.
273 virtual void addPassesToHandleExceptions();
274
275 /// Add pass to prepare the LLVM IR for code generation. This should be done
276 /// before exception handling preparation passes.
277 virtual void addCodeGenPrepare();
278
279 /// Add common passes that perform LLVM IR to IR transforms in preparation for
280 /// instruction selection.
281 virtual void addISelPrepare();
282
283 /// addInstSelector - This method should install an instruction selector pass,
284 /// which converts from LLVM code to machine instructions.
285 virtual bool addInstSelector() {
286 return true;
287 }
288
289 /// This method should install an IR translator pass, which converts from
290 /// LLVM code to machine instructions with possibly generic opcodes.
291 virtual bool addIRTranslator() { return true; }
292
293 /// This method may be implemented by targets that want to run passes
294 /// immediately before legalization.
295 virtual void addPreLegalizeMachineIR() {}
296
297 /// This method should install a legalize pass, which converts the instruction
298 /// sequence into one that can be selected by the target.
299 virtual bool addLegalizeMachineIR() { return true; }
300
301 /// This method may be implemented by targets that want to run passes
302 /// immediately before the register bank selection.
303 virtual void addPreRegBankSelect() {}
304
305 /// This method should install a register bank selector pass, which
306 /// assigns register banks to virtual registers without a register
307 /// class or register banks.
308 virtual bool addRegBankSelect() { return true; }
309
310 /// This method may be implemented by targets that want to run passes
311 /// immediately before the (global) instruction selection.
312 virtual void addPreGlobalInstructionSelect() {}
313
314 /// This method should install a (global) instruction selector pass, which
315 /// converts possibly generic instructions to fully target-specific
316 /// instructions, thereby constraining all generic virtual registers to
317 /// register classes.
318 virtual bool addGlobalInstructionSelect() { return true; }
319
320 /// Add the complete, standard set of LLVM CodeGen passes.
321 /// Fully developed targets will not generally override this.
322 virtual void addMachinePasses();
323
324 /// printAndVerify - Add a pass to dump then verify the machine function, if
325 /// those steps are enabled.
326 void printAndVerify(const std::string &Banner);
327
328 /// Add a pass to print the machine function if printing is enabled.
329 void addPrintPass(const std::string &Banner);
330
331 /// Add a pass to perform basic verification of the machine function if
332 /// verification is enabled.
333 void addVerifyPass(const std::string &Banner);
334
335 /// Add a pass to add synthesized debug info to the MIR.
336 void addDebugifyPass();
337
338 /// Add a pass to remove debug info from the MIR.
339 void addStripDebugPass();
340
341 /// Add a pass to check synthesized debug info for MIR.
342 void addCheckDebugPass();
343
344 /// Add standard passes before a pass that's about to be added. For example,
345 /// the DebugifyMachineModulePass if it is enabled.
346 void addMachinePrePasses(bool AllowDebugify = true);
347
348 /// Add standard passes after a pass that has just been added. For example,
349 /// the MachineVerifier if it is enabled.
350 void addMachinePostPasses(const std::string &Banner);
351
352 /// Check whether or not GlobalISel should abort on error.
353 /// When this is disabled, GlobalISel will fall back on SDISel instead of
354 /// erroring out.
355 bool isGlobalISelAbortEnabled() const;
356
357 /// Check whether or not a diagnostic should be emitted when GlobalISel
358 /// uses the fallback path. In other words, it will emit a diagnostic
359 /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
360 virtual bool reportDiagnosticWhenGlobalISelFallback() const;
361
362 /// Returns the CSEConfig object to use for the current optimization level.
363 virtual std::unique_ptr<CSEConfigBase> getCSEConfig() const;
364
365protected:
366 // Helper to verify the analysis is really immutable.
367 void setOpt(bool &Opt, bool Val);
368
369 /// Return true if register allocator is specified by -regalloc=override.
370 bool isCustomizedRegAlloc();
371
372 /// Methods with trivial inline returns are convenient points in the common
373 /// codegen pass pipeline where targets may insert passes. Methods with
374 /// out-of-line standard implementations are major CodeGen stages called by
375 /// addMachinePasses. Some targets may override major stages when inserting
376 /// passes is insufficient, but maintaining overriden stages is more work.
377 ///
378
379 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
380 /// passes (which are run just before instruction selector).
381 virtual bool addPreISel() {
382 return true;
383 }
384
385 /// addMachineSSAOptimization - Add standard passes that optimize machine
386 /// instructions in SSA form.
387 virtual void addMachineSSAOptimization();
388
389 /// Add passes that optimize instruction level parallelism for out-of-order
390 /// targets. These passes are run while the machine code is still in SSA
391 /// form, so they can use MachineTraceMetrics to control their heuristics.
392 ///
393 /// All passes added here should preserve the MachineDominatorTree,
394 /// MachineLoopInfo, and MachineTraceMetrics analyses.
395 virtual bool addILPOpts() {
396 return false;
397 }
398
399 /// This method may be implemented by targets that want to run passes
400 /// immediately before register allocation.
401 virtual void addPreRegAlloc() { }
402
403 /// createTargetRegisterAllocator - Create the register allocator pass for
404 /// this target at the current optimization level.
405 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
406
407 /// addFastRegAlloc - Add the minimum set of target-independent passes that
408 /// are required for fast register allocation.
409 virtual void addFastRegAlloc();
410
411 /// addOptimizedRegAlloc - Add passes related to register allocation.
412 /// CodeGenTargetMachineImpl provides standard regalloc passes for most
413 /// targets.
414 virtual void addOptimizedRegAlloc();
415
416 /// addPreRewrite - Add passes to the optimized register allocation pipeline
417 /// after register allocation is complete, but before virtual registers are
418 /// rewritten to physical registers.
419 ///
420 /// These passes must preserve VirtRegMap and LiveIntervals, and when running
421 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
422 /// When these passes run, VirtRegMap contains legal physreg assignments for
423 /// all virtual registers.
424 ///
425 /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
426 /// be honored. This is also not generally used for the fast variant,
427 /// where the allocation and rewriting are done in one pass.
428 virtual bool addPreRewrite() {
429 return false;
430 }
431
432 /// addPostFastRegAllocRewrite - Add passes to the optimized register
433 /// allocation pipeline after fast register allocation is complete.
434 virtual bool addPostFastRegAllocRewrite() { return false; }
435
436 /// Add passes to be run immediately after virtual registers are rewritten
437 /// to physical registers.
438 virtual void addPostRewrite() { }
439
440 /// This method may be implemented by targets that want to run passes after
441 /// register allocation pass pipeline but before prolog-epilog insertion.
442 virtual void addPostRegAlloc() { }
443
444 /// Add passes that optimize machine instructions after register allocation.
445 virtual void addMachineLateOptimization();
446
447 /// This method may be implemented by targets that want to run passes after
448 /// prolog-epilog insertion and before the second instruction scheduling pass.
449 virtual void addPreSched2() { }
450
451 /// addGCPasses - Add late codegen passes that analyze code for garbage
452 /// collection. This should return true if GC info should be printed after
453 /// these passes.
454 virtual bool addGCPasses();
455
456 /// Add standard basic block placement passes.
457 virtual void addBlockPlacement();
458
459 /// This pass may be implemented by targets that want to run passes
460 /// immediately before machine code is emitted.
461 virtual void addPreEmitPass() { }
462
463 /// This pass may be implemented by targets that want to run passes
464 /// immediately after basic block sections are assigned.
465 virtual void addPostBBSections() {}
466
467 /// Targets may add passes immediately before machine code is emitted in this
468 /// callback. This is called even later than `addPreEmitPass`.
469 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
470 // position and remove the `2` suffix here as this callback is what
471 // `addPreEmitPass` *should* be but in reality isn't.
472 virtual void addPreEmitPass2() {}
473
474 /// Utilities for targets to add passes to the pass manager.
475 ///
476
477 /// Add a CodeGen pass at this point in the pipeline after checking overrides.
478 /// Return the pass that was added, or zero if no pass was added.
479 AnalysisID addPass(AnalysisID PassID);
480
481 /// Add a pass to the PassManager if that pass is supposed to be run, as
482 /// determined by the StartAfter and StopAfter options. Takes ownership of the
483 /// pass.
484 void addPass(Pass *P);
485
486 /// addMachinePasses helper to create the target-selected or overriden
487 /// regalloc pass.
488 virtual FunctionPass *createRegAllocPass(bool Optimized);
489
490 /// Add core register allocator passes which do the actual register assignment
491 /// and rewriting. \returns true if any passes were added.
492 virtual bool addRegAssignAndRewriteFast();
493 virtual bool addRegAssignAndRewriteOptimized();
494};
495
496/// TargetPassConfig needs a TargetMachine; the pass registry cannot create one.
497template <> LLVM_ABI Pass *callDefaultCtor<TargetPassConfig>();
498
499LLVM_ABI void registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
500 TargetMachine &);
501
502} // end namespace llvm
503
504#endif // LLVM_CODEGEN_TARGETPASSCONFIG_H
505