• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- TargetPassConfig.h - Code Generation pass options -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// Target-Independent Code Generator Pass Configuration Options pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
15 #define LLVM_CODEGEN_TARGETPASSCONFIG_H
16 
17 #include "llvm/Pass.h"
18 #include "llvm/Support/CodeGen.h"
19 #include <string>
20 
21 namespace llvm {
22 
23 class PassConfigImpl;
24 class ScheduleDAGInstrs;
25 class TargetMachine;
26 struct MachineSchedContext;
27 
28 // The old pass manager infrastructure is hidden in a legacy namespace now.
29 namespace legacy {
30 class PassManagerBase;
31 }
32 using legacy::PassManagerBase;
33 
34 /// Discriminated union of Pass ID types.
35 ///
36 /// The PassConfig API prefers dealing with IDs because they are safer and more
37 /// efficient. IDs decouple configuration from instantiation. This way, when a
38 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
39 /// refer to a Pass pointer after adding it to a pass manager, which deletes
40 /// redundant pass instances.
41 ///
42 /// However, it is convient to directly instantiate target passes with
43 /// non-default ctors. These often don't have a registered PassInfo. Rather than
44 /// force all target passes to implement the pass registry boilerplate, allow
45 /// the PassConfig API to handle either type.
46 ///
47 /// AnalysisID is sadly char*, so PointerIntPair won't work.
48 class IdentifyingPassPtr {
49   union {
50     AnalysisID ID;
51     Pass *P;
52   };
53   bool IsInstance;
54 public:
IdentifyingPassPtr()55   IdentifyingPassPtr() : P(nullptr), IsInstance(false) {}
IdentifyingPassPtr(AnalysisID IDPtr)56   IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr), IsInstance(false) {}
IdentifyingPassPtr(Pass * InstancePtr)57   IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
58 
isValid()59   bool isValid() const { return P; }
isInstance()60   bool isInstance() const { return IsInstance; }
61 
getID()62   AnalysisID getID() const {
63     assert(!IsInstance && "Not a Pass ID");
64     return ID;
65   }
getInstance()66   Pass *getInstance() const {
67     assert(IsInstance && "Not a Pass Instance");
68     return P;
69   }
70 };
71 
72 template <> struct isPodLike<IdentifyingPassPtr> {
73   static const bool value = true;
74 };
75 
76 /// Target-Independent Code Generator Pass Configuration Options.
77 ///
78 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
79 /// to the internals of other CodeGen passes.
80 class TargetPassConfig : public ImmutablePass {
81 public:
82   /// Pseudo Pass IDs. These are defined within TargetPassConfig because they
83   /// are unregistered pass IDs. They are only useful for use with
84   /// TargetPassConfig APIs to identify multiple occurrences of the same pass.
85   ///
86 
87   /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early
88   /// during codegen, on SSA form.
89   static char EarlyTailDuplicateID;
90 
91   /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine
92   /// optimization after regalloc.
93   static char PostRAMachineLICMID;
94 
95 private:
96   PassManagerBase *PM;
97   AnalysisID StartBefore, StartAfter;
98   AnalysisID StopAfter;
99   bool Started;
100   bool Stopped;
101   bool AddingMachinePasses;
102 
103 protected:
104   TargetMachine *TM;
105   PassConfigImpl *Impl; // Internal data structures
106   bool Initialized;     // Flagged after all passes are configured.
107 
108   // Target Pass Options
109   // Targets provide a default setting, user flags override.
110   //
111   bool DisableVerify;
112 
113   /// Default setting for -enable-tail-merge on this target.
114   bool EnableTailMerge;
115 
116 public:
117   TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
118   // Dummy constructor.
119   TargetPassConfig();
120 
121   ~TargetPassConfig() override;
122 
123   static char ID;
124 
125   /// Get the right type of TargetMachine for this target.
126   template<typename TMC> TMC &getTM() const {
127     return *static_cast<TMC*>(TM);
128   }
129 
130   //
131   void setInitialized() { Initialized = true; }
132 
133   CodeGenOpt::Level getOptLevel() const;
134 
135   /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
136   /// a portion of the normal code-gen pass sequence.
137   ///
138   /// If the StartAfter and StartBefore pass ID is zero, then compilation will
139   /// begin at the normal point; otherwise, clear the Started flag to indicate
140   /// that passes should not be added until the starting pass is seen.  If the
141   /// Stop pass ID is zero, then compilation will continue to the end.
142   ///
143   /// This function expects that at least one of the StartAfter or the
144   /// StartBefore pass IDs is null.
145   void setStartStopPasses(AnalysisID StartBefore, AnalysisID StartAfter,
146                           AnalysisID StopAfter) {
147     if (StartAfter)
148       assert(!StartBefore && "Start after and start before passes are given");
149     this->StartBefore = StartBefore;
150     this->StartAfter = StartAfter;
151     this->StopAfter = StopAfter;
152     Started = (StartAfter == nullptr) && (StartBefore == nullptr);
153   }
154 
155   void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
156 
157   bool getEnableTailMerge() const { return EnableTailMerge; }
158   void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
159 
160   /// Allow the target to override a specific pass without overriding the pass
161   /// pipeline. When passes are added to the standard pipeline at the
162   /// point where StandardID is expected, add TargetID in its place.
163   void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
164 
165   /// Insert InsertedPassID pass after TargetPassID pass.
166   void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
167                   bool VerifyAfter = true, bool PrintAfter = true);
168 
169   /// Allow the target to enable a specific standard pass by default.
170   void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
171 
172   /// Allow the target to disable a specific standard pass by default.
173   void disablePass(AnalysisID PassID) {
174     substitutePass(PassID, IdentifyingPassPtr());
175   }
176 
177   /// Return the pass substituted for StandardID by the target.
178   /// If no substitution exists, return StandardID.
179   IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
180 
181   /// Return true if the pass has been substituted by the target or
182   /// overridden on the command line.
183   bool isPassSubstitutedOrOverridden(AnalysisID ID) const;
184 
185   /// Return true if the optimized regalloc pipeline is enabled.
186   bool getOptimizeRegAlloc() const;
187 
188   /// Return true if shrink wrapping is enabled.
189   bool getEnableShrinkWrap() const;
190 
191   /// Return true if the default global register allocator is in use and
192   /// has not be overriden on the command line with '-regalloc=...'
193   bool usingDefaultRegAlloc() const;
194 
195   /// Add common target configurable passes that perform LLVM IR to IR
196   /// transforms following machine independent optimization.
197   virtual void addIRPasses();
198 
199   /// Add passes to lower exception handling for the code generator.
200   void addPassesToHandleExceptions();
201 
202   /// Add pass to prepare the LLVM IR for code generation. This should be done
203   /// before exception handling preparation passes.
204   virtual void addCodeGenPrepare();
205 
206   /// Add common passes that perform LLVM IR to IR transforms in preparation for
207   /// instruction selection.
208   virtual void addISelPrepare();
209 
210   /// addInstSelector - This method should install an instruction selector pass,
211   /// which converts from LLVM code to machine instructions.
212   virtual bool addInstSelector() {
213     return true;
214   }
215 
216   /// This method should install an IR translator pass, which converts from
217   /// LLVM code to machine instructions with possibly generic opcodes.
218   virtual bool addIRTranslator() { return true; }
219 
220   /// This method may be implemented by targets that want to run passes
221   /// immediately before the register bank selection.
222   virtual void addPreRegBankSelect() {}
223 
224   /// This method should install a register bank selector pass, which
225   /// assigns register banks to virtual registers without a register
226   /// class or register banks.
227   virtual bool addRegBankSelect() { return true; }
228 
229   /// Add the complete, standard set of LLVM CodeGen passes.
230   /// Fully developed targets will not generally override this.
231   virtual void addMachinePasses();
232 
233   /// Create an instance of ScheduleDAGInstrs to be run within the standard
234   /// MachineScheduler pass for this function and target at the current
235   /// optimization level.
236   ///
237   /// This can also be used to plug a new MachineSchedStrategy into an instance
238   /// of the standard ScheduleDAGMI:
239   ///   return new ScheduleDAGMI(C, make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false)
240   ///
241   /// Return NULL to select the default (generic) machine scheduler.
242   virtual ScheduleDAGInstrs *
243   createMachineScheduler(MachineSchedContext *C) const {
244     return nullptr;
245   }
246 
247   /// Similar to createMachineScheduler but used when postRA machine scheduling
248   /// is enabled.
249   virtual ScheduleDAGInstrs *
250   createPostMachineScheduler(MachineSchedContext *C) const {
251     return nullptr;
252   }
253 
254   /// printAndVerify - Add a pass to dump then verify the machine function, if
255   /// those steps are enabled.
256   ///
257   void printAndVerify(const std::string &Banner);
258 
259   /// Add a pass to print the machine function if printing is enabled.
260   void addPrintPass(const std::string &Banner);
261 
262   /// Add a pass to perform basic verification of the machine function if
263   /// verification is enabled.
264   void addVerifyPass(const std::string &Banner);
265 
266 protected:
267   // Helper to verify the analysis is really immutable.
268   void setOpt(bool &Opt, bool Val);
269 
270   /// Methods with trivial inline returns are convenient points in the common
271   /// codegen pass pipeline where targets may insert passes. Methods with
272   /// out-of-line standard implementations are major CodeGen stages called by
273   /// addMachinePasses. Some targets may override major stages when inserting
274   /// passes is insufficient, but maintaining overriden stages is more work.
275   ///
276 
277   /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
278   /// passes (which are run just before instruction selector).
279   virtual bool addPreISel() {
280     return true;
281   }
282 
283   /// addMachineSSAOptimization - Add standard passes that optimize machine
284   /// instructions in SSA form.
285   virtual void addMachineSSAOptimization();
286 
287   /// Add passes that optimize instruction level parallelism for out-of-order
288   /// targets. These passes are run while the machine code is still in SSA
289   /// form, so they can use MachineTraceMetrics to control their heuristics.
290   ///
291   /// All passes added here should preserve the MachineDominatorTree,
292   /// MachineLoopInfo, and MachineTraceMetrics analyses.
293   virtual bool addILPOpts() {
294     return false;
295   }
296 
297   /// This method may be implemented by targets that want to run passes
298   /// immediately before register allocation.
299   virtual void addPreRegAlloc() { }
300 
301   /// createTargetRegisterAllocator - Create the register allocator pass for
302   /// this target at the current optimization level.
303   virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
304 
305   /// addFastRegAlloc - Add the minimum set of target-independent passes that
306   /// are required for fast register allocation.
307   virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
308 
309   /// addOptimizedRegAlloc - Add passes related to register allocation.
310   /// LLVMTargetMachine provides standard regalloc passes for most targets.
311   virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
312 
313   /// addPreRewrite - Add passes to the optimized register allocation pipeline
314   /// after register allocation is complete, but before virtual registers are
315   /// rewritten to physical registers.
316   ///
317   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
318   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
319   /// When these passes run, VirtRegMap contains legal physreg assignments for
320   /// all virtual registers.
321   virtual bool addPreRewrite() {
322     return false;
323   }
324 
325   /// This method may be implemented by targets that want to run passes after
326   /// register allocation pass pipeline but before prolog-epilog insertion.
327   virtual void addPostRegAlloc() { }
328 
329   /// Add passes that optimize machine instructions after register allocation.
330   virtual void addMachineLateOptimization();
331 
332   /// This method may be implemented by targets that want to run passes after
333   /// prolog-epilog insertion and before the second instruction scheduling pass.
334   virtual void addPreSched2() { }
335 
336   /// addGCPasses - Add late codegen passes that analyze code for garbage
337   /// collection. This should return true if GC info should be printed after
338   /// these passes.
339   virtual bool addGCPasses();
340 
341   /// Add standard basic block placement passes.
342   virtual void addBlockPlacement();
343 
344   /// This pass may be implemented by targets that want to run passes
345   /// immediately before machine code is emitted.
346   virtual void addPreEmitPass() { }
347 
348   /// Utilities for targets to add passes to the pass manager.
349   ///
350 
351   /// Add a CodeGen pass at this point in the pipeline after checking overrides.
352   /// Return the pass that was added, or zero if no pass was added.
353   /// @p printAfter    if true and adding a machine function pass add an extra
354   ///                  machine printer pass afterwards
355   /// @p verifyAfter   if true and adding a machine function pass add an extra
356   ///                  machine verification pass afterwards.
357   AnalysisID addPass(AnalysisID PassID, bool verifyAfter = true,
358                      bool printAfter = true);
359 
360   /// Add a pass to the PassManager if that pass is supposed to be run, as
361   /// determined by the StartAfter and StopAfter options. Takes ownership of the
362   /// pass.
363   /// @p printAfter    if true and adding a machine function pass add an extra
364   ///                  machine printer pass afterwards
365   /// @p verifyAfter   if true and adding a machine function pass add an extra
366   ///                  machine verification pass afterwards.
367   void addPass(Pass *P, bool verifyAfter = true, bool printAfter = true);
368 
369   /// addMachinePasses helper to create the target-selected or overriden
370   /// regalloc pass.
371   FunctionPass *createRegAllocPass(bool Optimized);
372 };
373 
374 } // end namespace llvm
375 
376 #endif
377