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