TargetPassConfig.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. /// Target-Independent Code Generator Pass Configuration Options pass.
  15. ///
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H
  18. #define LLVM_CODEGEN_TARGETPASSCONFIG_H
  19. #include "llvm/Pass.h"
  20. #include "llvm/Support/CodeGen.h"
  21. #include <cassert>
  22. #include <string>
  23. namespace llvm {
  24. class LLVMTargetMachine;
  25. struct MachineSchedContext;
  26. class PassConfigImpl;
  27. class ScheduleDAGInstrs;
  28. class CSEConfigBase;
  29. class PassInstrumentationCallbacks;
  30. // The old pass manager infrastructure is hidden in a legacy namespace now.
  31. namespace legacy {
  32. class PassManagerBase;
  33. } // end namespace legacy
  34. using legacy::PassManagerBase;
  35. /// Discriminated union of Pass ID types.
  36. ///
  37. /// The PassConfig API prefers dealing with IDs because they are safer and more
  38. /// efficient. IDs decouple configuration from instantiation. This way, when a
  39. /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to
  40. /// refer to a Pass pointer after adding it to a pass manager, which deletes
  41. /// redundant pass instances.
  42. ///
  43. /// However, it is convient to directly instantiate target passes with
  44. /// non-default ctors. These often don't have a registered PassInfo. Rather than
  45. /// force all target passes to implement the pass registry boilerplate, allow
  46. /// the PassConfig API to handle either type.
  47. ///
  48. /// AnalysisID is sadly char*, so PointerIntPair won't work.
  49. class IdentifyingPassPtr {
  50. union {
  51. AnalysisID ID;
  52. Pass *P;
  53. };
  54. bool IsInstance = false;
  55. public:
  56. IdentifyingPassPtr() : P(nullptr) {}
  57. IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr) {}
  58. IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {}
  59. bool isValid() const { return P; }
  60. bool isInstance() const { return IsInstance; }
  61. AnalysisID getID() const {
  62. assert(!IsInstance && "Not a Pass ID");
  63. return ID;
  64. }
  65. Pass *getInstance() const {
  66. assert(IsInstance && "Not a Pass Instance");
  67. return P;
  68. }
  69. };
  70. /// Target-Independent Code Generator Pass Configuration Options.
  71. ///
  72. /// This is an ImmutablePass solely for the purpose of exposing CodeGen options
  73. /// to the internals of other CodeGen passes.
  74. class TargetPassConfig : public ImmutablePass {
  75. private:
  76. PassManagerBase *PM = nullptr;
  77. AnalysisID StartBefore = nullptr;
  78. AnalysisID StartAfter = nullptr;
  79. AnalysisID StopBefore = nullptr;
  80. AnalysisID StopAfter = nullptr;
  81. unsigned StartBeforeInstanceNum = 0;
  82. unsigned StartBeforeCount = 0;
  83. unsigned StartAfterInstanceNum = 0;
  84. unsigned StartAfterCount = 0;
  85. unsigned StopBeforeInstanceNum = 0;
  86. unsigned StopBeforeCount = 0;
  87. unsigned StopAfterInstanceNum = 0;
  88. unsigned StopAfterCount = 0;
  89. bool Started = true;
  90. bool Stopped = false;
  91. bool AddingMachinePasses = false;
  92. bool DebugifyIsSafe = true;
  93. /// Set the StartAfter, StartBefore and StopAfter passes to allow running only
  94. /// a portion of the normal code-gen pass sequence.
  95. ///
  96. /// If the StartAfter and StartBefore pass ID is zero, then compilation will
  97. /// begin at the normal point; otherwise, clear the Started flag to indicate
  98. /// that passes should not be added until the starting pass is seen. If the
  99. /// Stop pass ID is zero, then compilation will continue to the end.
  100. ///
  101. /// This function expects that at least one of the StartAfter or the
  102. /// StartBefore pass IDs is null.
  103. void setStartStopPasses();
  104. protected:
  105. LLVMTargetMachine *TM;
  106. PassConfigImpl *Impl = nullptr; // Internal data structures
  107. bool Initialized = false; // Flagged after all passes are configured.
  108. // Target Pass Options
  109. // Targets provide a default setting, user flags override.
  110. bool DisableVerify = false;
  111. /// Default setting for -enable-tail-merge on this target.
  112. bool EnableTailMerge = true;
  113. /// Require processing of functions such that callees are generated before
  114. /// callers.
  115. bool RequireCodeGenSCCOrder = false;
  116. /// Add the actual instruction selection passes. This does not include
  117. /// preparation passes on IR.
  118. bool addCoreISelPasses();
  119. public:
  120. TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm);
  121. // Dummy constructor.
  122. TargetPassConfig();
  123. ~TargetPassConfig() override;
  124. static char ID;
  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. void setInitialized() { Initialized = true; }
  131. CodeGenOpt::Level getOptLevel() const;
  132. /// Returns true if one of the `-start-after`, `-start-before`, `-stop-after`
  133. /// or `-stop-before` options is set.
  134. static bool hasLimitedCodeGenPipeline();
  135. /// Returns true if none of the `-stop-before` and `-stop-after` options is
  136. /// set.
  137. static bool willCompleteCodeGenPipeline();
  138. /// If hasLimitedCodeGenPipeline is true, this method
  139. /// returns a string with the name of the options, separated
  140. /// by \p Separator that caused this pipeline to be limited.
  141. static std::string
  142. getLimitedCodeGenPipelineReason(const char *Separator = "/");
  143. void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
  144. bool getEnableTailMerge() const { return EnableTailMerge; }
  145. void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
  146. bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; }
  147. void setRequiresCodeGenSCCOrder(bool Enable = true) {
  148. setOpt(RequireCodeGenSCCOrder, Enable);
  149. }
  150. /// Allow the target to override a specific pass without overriding the pass
  151. /// pipeline. When passes are added to the standard pipeline at the
  152. /// point where StandardID is expected, add TargetID in its place.
  153. void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID);
  154. /// Insert InsertedPassID pass after TargetPassID pass.
  155. void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID);
  156. /// Allow the target to enable a specific standard pass by default.
  157. void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); }
  158. /// Allow the target to disable a specific standard pass by default.
  159. void disablePass(AnalysisID PassID) {
  160. substitutePass(PassID, IdentifyingPassPtr());
  161. }
  162. /// Return the pass substituted for StandardID by the target.
  163. /// If no substitution exists, return StandardID.
  164. IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const;
  165. /// Return true if the pass has been substituted by the target or
  166. /// overridden on the command line.
  167. bool isPassSubstitutedOrOverridden(AnalysisID ID) const;
  168. /// Return true if the optimized regalloc pipeline is enabled.
  169. bool getOptimizeRegAlloc() const;
  170. /// Return true if the default global register allocator is in use and
  171. /// has not be overriden on the command line with '-regalloc=...'
  172. bool usingDefaultRegAlloc() const;
  173. /// High level function that adds all passes necessary to go from llvm IR
  174. /// representation to the MI representation.
  175. /// Adds IR based lowering and target specific optimization passes and finally
  176. /// the core instruction selection passes.
  177. /// \returns true if an error occurred, false otherwise.
  178. bool addISelPasses();
  179. /// Add common target configurable passes that perform LLVM IR to IR
  180. /// transforms following machine independent optimization.
  181. virtual void addIRPasses();
  182. /// Add passes to lower exception handling for the code generator.
  183. void addPassesToHandleExceptions();
  184. /// Add pass to prepare the LLVM IR for code generation. This should be done
  185. /// before exception handling preparation passes.
  186. virtual void addCodeGenPrepare();
  187. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  188. /// instruction selection.
  189. virtual void addISelPrepare();
  190. /// addInstSelector - This method should install an instruction selector pass,
  191. /// which converts from LLVM code to machine instructions.
  192. virtual bool addInstSelector() {
  193. return true;
  194. }
  195. /// This method should install an IR translator pass, which converts from
  196. /// LLVM code to machine instructions with possibly generic opcodes.
  197. virtual bool addIRTranslator() { return true; }
  198. /// This method may be implemented by targets that want to run passes
  199. /// immediately before legalization.
  200. virtual void addPreLegalizeMachineIR() {}
  201. /// This method should install a legalize pass, which converts the instruction
  202. /// sequence into one that can be selected by the target.
  203. virtual bool addLegalizeMachineIR() { return true; }
  204. /// This method may be implemented by targets that want to run passes
  205. /// immediately before the register bank selection.
  206. virtual void addPreRegBankSelect() {}
  207. /// This method should install a register bank selector pass, which
  208. /// assigns register banks to virtual registers without a register
  209. /// class or register banks.
  210. virtual bool addRegBankSelect() { return true; }
  211. /// This method may be implemented by targets that want to run passes
  212. /// immediately before the (global) instruction selection.
  213. virtual void addPreGlobalInstructionSelect() {}
  214. /// This method should install a (global) instruction selector pass, which
  215. /// converts possibly generic instructions to fully target-specific
  216. /// instructions, thereby constraining all generic virtual registers to
  217. /// register classes.
  218. virtual bool addGlobalInstructionSelect() { return true; }
  219. /// Add the complete, standard set of LLVM CodeGen passes.
  220. /// Fully developed targets will not generally override this.
  221. virtual void addMachinePasses();
  222. /// Create an instance of ScheduleDAGInstrs to be run within the standard
  223. /// MachineScheduler pass for this function and target at the current
  224. /// optimization level.
  225. ///
  226. /// This can also be used to plug a new MachineSchedStrategy into an instance
  227. /// of the standard ScheduleDAGMI:
  228. /// return new ScheduleDAGMI(C, std::make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false)
  229. ///
  230. /// Return NULL to select the default (generic) machine scheduler.
  231. virtual ScheduleDAGInstrs *
  232. createMachineScheduler(MachineSchedContext *C) const {
  233. return nullptr;
  234. }
  235. /// Similar to createMachineScheduler but used when postRA machine scheduling
  236. /// is enabled.
  237. virtual ScheduleDAGInstrs *
  238. createPostMachineScheduler(MachineSchedContext *C) const {
  239. return nullptr;
  240. }
  241. /// printAndVerify - Add a pass to dump then verify the machine function, if
  242. /// those steps are enabled.
  243. void printAndVerify(const std::string &Banner);
  244. /// Add a pass to print the machine function if printing is enabled.
  245. void addPrintPass(const std::string &Banner);
  246. /// Add a pass to perform basic verification of the machine function if
  247. /// verification is enabled.
  248. void addVerifyPass(const std::string &Banner);
  249. /// Add a pass to add synthesized debug info to the MIR.
  250. void addDebugifyPass();
  251. /// Add a pass to remove debug info from the MIR.
  252. void addStripDebugPass();
  253. /// Add a pass to check synthesized debug info for MIR.
  254. void addCheckDebugPass();
  255. /// Add standard passes before a pass that's about to be added. For example,
  256. /// the DebugifyMachineModulePass if it is enabled.
  257. void addMachinePrePasses(bool AllowDebugify = true);
  258. /// Add standard passes after a pass that has just been added. For example,
  259. /// the MachineVerifier if it is enabled.
  260. void addMachinePostPasses(const std::string &Banner);
  261. /// Check whether or not GlobalISel should abort on error.
  262. /// When this is disabled, GlobalISel will fall back on SDISel instead of
  263. /// erroring out.
  264. bool isGlobalISelAbortEnabled() const;
  265. /// Check whether or not a diagnostic should be emitted when GlobalISel
  266. /// uses the fallback path. In other words, it will emit a diagnostic
  267. /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
  268. virtual bool reportDiagnosticWhenGlobalISelFallback() const;
  269. /// Check whether continuous CSE should be enabled in GISel passes.
  270. /// By default, it's enabled for non O0 levels.
  271. virtual bool isGISelCSEEnabled() const;
  272. /// Returns the CSEConfig object to use for the current optimization level.
  273. virtual std::unique_ptr<CSEConfigBase> getCSEConfig() const;
  274. protected:
  275. // Helper to verify the analysis is really immutable.
  276. void setOpt(bool &Opt, bool Val);
  277. /// Methods with trivial inline returns are convenient points in the common
  278. /// codegen pass pipeline where targets may insert passes. Methods with
  279. /// out-of-line standard implementations are major CodeGen stages called by
  280. /// addMachinePasses. Some targets may override major stages when inserting
  281. /// passes is insufficient, but maintaining overriden stages is more work.
  282. ///
  283. /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM
  284. /// passes (which are run just before instruction selector).
  285. virtual bool addPreISel() {
  286. return true;
  287. }
  288. /// addMachineSSAOptimization - Add standard passes that optimize machine
  289. /// instructions in SSA form.
  290. virtual void addMachineSSAOptimization();
  291. /// Add passes that optimize instruction level parallelism for out-of-order
  292. /// targets. These passes are run while the machine code is still in SSA
  293. /// form, so they can use MachineTraceMetrics to control their heuristics.
  294. ///
  295. /// All passes added here should preserve the MachineDominatorTree,
  296. /// MachineLoopInfo, and MachineTraceMetrics analyses.
  297. virtual bool addILPOpts() {
  298. return false;
  299. }
  300. /// This method may be implemented by targets that want to run passes
  301. /// immediately before register allocation.
  302. virtual void addPreRegAlloc() { }
  303. /// createTargetRegisterAllocator - Create the register allocator pass for
  304. /// this target at the current optimization level.
  305. virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
  306. /// addFastRegAlloc - Add the minimum set of target-independent passes that
  307. /// are required for fast register allocation.
  308. virtual void addFastRegAlloc();
  309. /// addOptimizedRegAlloc - Add passes related to register allocation.
  310. /// LLVMTargetMachine provides standard regalloc passes for most targets.
  311. virtual void addOptimizedRegAlloc();
  312. /// addPreRewrite - Add passes to the optimized register allocation pipeline
  313. /// after register allocation is complete, but before virtual registers are
  314. /// rewritten to physical registers.
  315. ///
  316. /// These passes must preserve VirtRegMap and LiveIntervals, and when running
  317. /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
  318. /// When these passes run, VirtRegMap contains legal physreg assignments for
  319. /// all virtual registers.
  320. ///
  321. /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
  322. /// be honored. This is also not generally used for the the fast variant,
  323. /// where the allocation and rewriting are done in one pass.
  324. virtual bool addPreRewrite() {
  325. return false;
  326. }
  327. /// addPostFastRegAllocRewrite - Add passes to the optimized register
  328. /// allocation pipeline after fast register allocation is complete.
  329. virtual bool addPostFastRegAllocRewrite() { return false; }
  330. /// Add passes to be run immediately after virtual registers are rewritten
  331. /// to physical registers.
  332. virtual void addPostRewrite() { }
  333. /// This method may be implemented by targets that want to run passes after
  334. /// register allocation pass pipeline but before prolog-epilog insertion.
  335. virtual void addPostRegAlloc() { }
  336. /// Add passes that optimize machine instructions after register allocation.
  337. virtual void addMachineLateOptimization();
  338. /// This method may be implemented by targets that want to run passes after
  339. /// prolog-epilog insertion and before the second instruction scheduling pass.
  340. virtual void addPreSched2() { }
  341. /// addGCPasses - Add late codegen passes that analyze code for garbage
  342. /// collection. This should return true if GC info should be printed after
  343. /// these passes.
  344. virtual bool addGCPasses();
  345. /// Add standard basic block placement passes.
  346. virtual void addBlockPlacement();
  347. /// This pass may be implemented by targets that want to run passes
  348. /// immediately before machine code is emitted.
  349. virtual void addPreEmitPass() { }
  350. /// Targets may add passes immediately before machine code is emitted in this
  351. /// callback. This is called even later than `addPreEmitPass`.
  352. // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
  353. // position and remove the `2` suffix here as this callback is what
  354. // `addPreEmitPass` *should* be but in reality isn't.
  355. virtual void addPreEmitPass2() {}
  356. /// Utilities for targets to add passes to the pass manager.
  357. ///
  358. /// Add a CodeGen pass at this point in the pipeline after checking overrides.
  359. /// Return the pass that was added, or zero if no pass was added.
  360. AnalysisID addPass(AnalysisID PassID);
  361. /// Add a pass to the PassManager if that pass is supposed to be run, as
  362. /// determined by the StartAfter and StopAfter options. Takes ownership of the
  363. /// pass.
  364. void addPass(Pass *P);
  365. /// addMachinePasses helper to create the target-selected or overriden
  366. /// regalloc pass.
  367. virtual FunctionPass *createRegAllocPass(bool Optimized);
  368. /// Add core register allocator passes which do the actual register assignment
  369. /// and rewriting. \returns true if any passes were added.
  370. virtual bool addRegAssignAndRewriteFast();
  371. virtual bool addRegAssignAndRewriteOptimized();
  372. };
  373. void registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
  374. LLVMTargetMachine &);
  375. } // end namespace llvm
  376. #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H
  377. #ifdef __GNUC__
  378. #pragma GCC diagnostic pop
  379. #endif