CodeGenPassBuilder.h 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. //===- Construction of codegen pass pipelines ------------------*- 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. ///
  10. /// Interfaces for registering analysis passes, producing common pass manager
  11. /// configurations, and parsing of pass pipelines.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_CODEGEN_CODEGENPASSBUILDER_H
  15. #define LLVM_CODEGEN_CODEGENPASSBUILDER_H
  16. #include "llvm/ADT/FunctionExtras.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BasicAliasAnalysis.h"
  21. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  22. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  23. #include "llvm/Analysis/ScopedNoAliasAA.h"
  24. #include "llvm/Analysis/TargetTransformInfo.h"
  25. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  26. #include "llvm/CodeGen/ExpandReductions.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachinePassManager.h"
  29. #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
  30. #include "llvm/CodeGen/ReplaceWithVeclib.h"
  31. #include "llvm/CodeGen/UnreachableBlockElim.h"
  32. #include "llvm/IR/IRPrintingPasses.h"
  33. #include "llvm/IR/PassManager.h"
  34. #include "llvm/IR/Verifier.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/MCStreamer.h"
  37. #include "llvm/MC/MCTargetOptions.h"
  38. #include "llvm/Support/CodeGen.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/Error.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Target/CGPassBuilderOption.h"
  43. #include "llvm/Target/TargetMachine.h"
  44. #include "llvm/Transforms/Scalar.h"
  45. #include "llvm/Transforms/Scalar/ConstantHoisting.h"
  46. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  47. #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
  48. #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
  49. #include "llvm/Transforms/Scalar/MergeICmps.h"
  50. #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
  51. #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
  52. #include "llvm/Transforms/Utils.h"
  53. #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
  54. #include "llvm/Transforms/Utils/LowerInvoke.h"
  55. #include <cassert>
  56. #include <type_traits>
  57. #include <utility>
  58. namespace llvm {
  59. // FIXME: Dummy target independent passes definitions that have not yet been
  60. // ported to new pass manager. Once they do, remove these.
  61. #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  62. struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
  63. template <typename... Ts> PASS_NAME(Ts &&...) {} \
  64. PreservedAnalyses run(Function &, FunctionAnalysisManager &) { \
  65. return PreservedAnalyses::all(); \
  66. } \
  67. };
  68. #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  69. struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
  70. template <typename... Ts> PASS_NAME(Ts &&...) {} \
  71. PreservedAnalyses run(Module &, ModuleAnalysisManager &) { \
  72. return PreservedAnalyses::all(); \
  73. } \
  74. };
  75. #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  76. struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
  77. template <typename... Ts> PASS_NAME(Ts &&...) {} \
  78. Error run(Module &, MachineFunctionAnalysisManager &) { \
  79. return Error::success(); \
  80. } \
  81. PreservedAnalyses run(MachineFunction &, \
  82. MachineFunctionAnalysisManager &) { \
  83. llvm_unreachable("this api is to make new PM api happy"); \
  84. } \
  85. static AnalysisKey Key; \
  86. };
  87. #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  88. struct PASS_NAME : public PassInfoMixin<PASS_NAME> { \
  89. template <typename... Ts> PASS_NAME(Ts &&...) {} \
  90. PreservedAnalyses run(MachineFunction &, \
  91. MachineFunctionAnalysisManager &) { \
  92. return PreservedAnalyses::all(); \
  93. } \
  94. static AnalysisKey Key; \
  95. };
  96. #include "MachinePassRegistry.def"
  97. /// This class provides access to building LLVM's passes.
  98. ///
  99. /// Its members provide the baseline state available to passes during their
  100. /// construction. The \c MachinePassRegistry.def file specifies how to construct
  101. /// all of the built-in passes, and those may reference these members during
  102. /// construction.
  103. template <typename DerivedT> class CodeGenPassBuilder {
  104. public:
  105. explicit CodeGenPassBuilder(LLVMTargetMachine &TM, CGPassBuilderOption Opts,
  106. PassInstrumentationCallbacks *PIC)
  107. : TM(TM), Opt(Opts), PIC(PIC) {
  108. // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
  109. // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
  110. // Target should override TM.Options.EnableIPRA in their target-specific
  111. // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
  112. if (Opt.EnableIPRA)
  113. TM.Options.EnableIPRA = *Opt.EnableIPRA;
  114. if (Opt.EnableGlobalISelAbort)
  115. TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
  116. if (!Opt.OptimizeRegAlloc)
  117. Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOpt::None;
  118. }
  119. Error buildPipeline(ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
  120. raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
  121. CodeGenFileType FileType) const;
  122. void registerModuleAnalyses(ModuleAnalysisManager &) const;
  123. void registerFunctionAnalyses(FunctionAnalysisManager &) const;
  124. void registerMachineFunctionAnalyses(MachineFunctionAnalysisManager &) const;
  125. std::pair<StringRef, bool> getPassNameFromLegacyName(StringRef) const;
  126. void registerAnalyses(MachineFunctionAnalysisManager &MFAM) const {
  127. registerModuleAnalyses(*MFAM.MAM);
  128. registerFunctionAnalyses(*MFAM.FAM);
  129. registerMachineFunctionAnalyses(MFAM);
  130. }
  131. PassInstrumentationCallbacks *getPassInstrumentationCallbacks() const {
  132. return PIC;
  133. }
  134. protected:
  135. template <typename PassT> using has_key_t = decltype(PassT::Key);
  136. template <typename PassT>
  137. using is_module_pass_t = decltype(std::declval<PassT &>().run(
  138. std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
  139. template <typename PassT>
  140. using is_function_pass_t = decltype(std::declval<PassT &>().run(
  141. std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
  142. // Function object to maintain state while adding codegen IR passes.
  143. class AddIRPass {
  144. public:
  145. AddIRPass(ModulePassManager &MPM, bool DebugPM, bool Check = true)
  146. : MPM(MPM), FPM() {
  147. if (Check)
  148. AddingFunctionPasses = false;
  149. }
  150. ~AddIRPass() {
  151. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  152. }
  153. // Add Function Pass
  154. template <typename PassT>
  155. std::enable_if_t<is_detected<is_function_pass_t, PassT>::value>
  156. operator()(PassT &&Pass) {
  157. if (AddingFunctionPasses && !*AddingFunctionPasses)
  158. AddingFunctionPasses = true;
  159. FPM.addPass(std::forward<PassT>(Pass));
  160. }
  161. // Add Module Pass
  162. template <typename PassT>
  163. std::enable_if_t<is_detected<is_module_pass_t, PassT>::value &&
  164. !is_detected<is_function_pass_t, PassT>::value>
  165. operator()(PassT &&Pass) {
  166. assert((!AddingFunctionPasses || !*AddingFunctionPasses) &&
  167. "could not add module pass after adding function pass");
  168. MPM.addPass(std::forward<PassT>(Pass));
  169. }
  170. private:
  171. ModulePassManager &MPM;
  172. FunctionPassManager FPM;
  173. // The codegen IR pipeline are mostly function passes with the exceptions of
  174. // a few loop and module passes. `AddingFunctionPasses` make sures that
  175. // we could only add module passes at the beginning of the pipeline. Once
  176. // we begin adding function passes, we could no longer add module passes.
  177. // This special-casing introduces less adaptor passes. If we have the need
  178. // of adding module passes after function passes, we could change the
  179. // implementation to accommodate that.
  180. Optional<bool> AddingFunctionPasses;
  181. };
  182. // Function object to maintain state while adding codegen machine passes.
  183. class AddMachinePass {
  184. public:
  185. AddMachinePass(MachineFunctionPassManager &PM) : PM(PM) {}
  186. template <typename PassT> void operator()(PassT &&Pass) {
  187. static_assert(
  188. is_detected<has_key_t, PassT>::value,
  189. "Machine function pass must define a static member variable `Key`.");
  190. for (auto &C : BeforeCallbacks)
  191. if (!C(&PassT::Key))
  192. return;
  193. PM.addPass(std::forward<PassT>(Pass));
  194. for (auto &C : AfterCallbacks)
  195. C(&PassT::Key);
  196. }
  197. template <typename PassT> void insertPass(AnalysisKey *ID, PassT Pass) {
  198. AfterCallbacks.emplace_back(
  199. [this, ID, Pass = std::move(Pass)](AnalysisKey *PassID) {
  200. if (PassID == ID)
  201. this->PM.addPass(std::move(Pass));
  202. });
  203. }
  204. void disablePass(AnalysisKey *ID) {
  205. BeforeCallbacks.emplace_back(
  206. [ID](AnalysisKey *PassID) { return PassID != ID; });
  207. }
  208. MachineFunctionPassManager releasePM() { return std::move(PM); }
  209. private:
  210. MachineFunctionPassManager &PM;
  211. SmallVector<llvm::unique_function<bool(AnalysisKey *)>, 4> BeforeCallbacks;
  212. SmallVector<llvm::unique_function<void(AnalysisKey *)>, 4> AfterCallbacks;
  213. };
  214. LLVMTargetMachine &TM;
  215. CGPassBuilderOption Opt;
  216. PassInstrumentationCallbacks *PIC;
  217. /// Target override these hooks to parse target-specific analyses.
  218. void registerTargetAnalysis(ModuleAnalysisManager &) const {}
  219. void registerTargetAnalysis(FunctionAnalysisManager &) const {}
  220. void registerTargetAnalysis(MachineFunctionAnalysisManager &) const {}
  221. std::pair<StringRef, bool> getTargetPassNameFromLegacyName(StringRef) const {
  222. return {"", false};
  223. }
  224. template <typename TMC> TMC &getTM() const { return static_cast<TMC &>(TM); }
  225. CodeGenOpt::Level getOptLevel() const { return TM.getOptLevel(); }
  226. /// Check whether or not GlobalISel should abort on error.
  227. /// When this is disabled, GlobalISel will fall back on SDISel instead of
  228. /// erroring out.
  229. bool isGlobalISelAbortEnabled() const {
  230. return TM.Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
  231. }
  232. /// Check whether or not a diagnostic should be emitted when GlobalISel
  233. /// uses the fallback path. In other words, it will emit a diagnostic
  234. /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
  235. bool reportDiagnosticWhenGlobalISelFallback() const {
  236. return TM.Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
  237. }
  238. /// addInstSelector - This method should install an instruction selector pass,
  239. /// which converts from LLVM code to machine instructions.
  240. Error addInstSelector(AddMachinePass &) const {
  241. return make_error<StringError>("addInstSelector is not overridden",
  242. inconvertibleErrorCode());
  243. }
  244. /// Add passes that optimize instruction level parallelism for out-of-order
  245. /// targets. These passes are run while the machine code is still in SSA
  246. /// form, so they can use MachineTraceMetrics to control their heuristics.
  247. ///
  248. /// All passes added here should preserve the MachineDominatorTree,
  249. /// MachineLoopInfo, and MachineTraceMetrics analyses.
  250. void addILPOpts(AddMachinePass &) const {}
  251. /// This method may be implemented by targets that want to run passes
  252. /// immediately before register allocation.
  253. void addPreRegAlloc(AddMachinePass &) const {}
  254. /// addPreRewrite - Add passes to the optimized register allocation pipeline
  255. /// after register allocation is complete, but before virtual registers are
  256. /// rewritten to physical registers.
  257. ///
  258. /// These passes must preserve VirtRegMap and LiveIntervals, and when running
  259. /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
  260. /// When these passes run, VirtRegMap contains legal physreg assignments for
  261. /// all virtual registers.
  262. ///
  263. /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
  264. /// be honored. This is also not generally used for the the fast variant,
  265. /// where the allocation and rewriting are done in one pass.
  266. void addPreRewrite(AddMachinePass &) const {}
  267. /// Add passes to be run immediately after virtual registers are rewritten
  268. /// to physical registers.
  269. void addPostRewrite(AddMachinePass &) const {}
  270. /// This method may be implemented by targets that want to run passes after
  271. /// register allocation pass pipeline but before prolog-epilog insertion.
  272. void addPostRegAlloc(AddMachinePass &) const {}
  273. /// This method may be implemented by targets that want to run passes after
  274. /// prolog-epilog insertion and before the second instruction scheduling pass.
  275. void addPreSched2(AddMachinePass &) const {}
  276. /// This pass may be implemented by targets that want to run passes
  277. /// immediately before machine code is emitted.
  278. void addPreEmitPass(AddMachinePass &) const {}
  279. /// Targets may add passes immediately before machine code is emitted in this
  280. /// callback. This is called even later than `addPreEmitPass`.
  281. // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
  282. // position and remove the `2` suffix here as this callback is what
  283. // `addPreEmitPass` *should* be but in reality isn't.
  284. void addPreEmitPass2(AddMachinePass &) const {}
  285. /// {{@ For GlobalISel
  286. ///
  287. /// addPreISel - This method should add any "last minute" LLVM->LLVM
  288. /// passes (which are run just before instruction selector).
  289. void addPreISel(AddIRPass &) const {
  290. llvm_unreachable("addPreISel is not overridden");
  291. }
  292. /// This method should install an IR translator pass, which converts from
  293. /// LLVM code to machine instructions with possibly generic opcodes.
  294. Error addIRTranslator(AddMachinePass &) const {
  295. return make_error<StringError>("addIRTranslator is not overridden",
  296. inconvertibleErrorCode());
  297. }
  298. /// This method may be implemented by targets that want to run passes
  299. /// immediately before legalization.
  300. void addPreLegalizeMachineIR(AddMachinePass &) const {}
  301. /// This method should install a legalize pass, which converts the instruction
  302. /// sequence into one that can be selected by the target.
  303. Error addLegalizeMachineIR(AddMachinePass &) const {
  304. return make_error<StringError>("addLegalizeMachineIR is not overridden",
  305. inconvertibleErrorCode());
  306. }
  307. /// This method may be implemented by targets that want to run passes
  308. /// immediately before the register bank selection.
  309. void addPreRegBankSelect(AddMachinePass &) const {}
  310. /// This method should install a register bank selector pass, which
  311. /// assigns register banks to virtual registers without a register
  312. /// class or register banks.
  313. Error addRegBankSelect(AddMachinePass &) const {
  314. return make_error<StringError>("addRegBankSelect is not overridden",
  315. inconvertibleErrorCode());
  316. }
  317. /// This method may be implemented by targets that want to run passes
  318. /// immediately before the (global) instruction selection.
  319. void addPreGlobalInstructionSelect(AddMachinePass &) const {}
  320. /// This method should install a (global) instruction selector pass, which
  321. /// converts possibly generic instructions to fully target-specific
  322. /// instructions, thereby constraining all generic virtual registers to
  323. /// register classes.
  324. Error addGlobalInstructionSelect(AddMachinePass &) const {
  325. return make_error<StringError>(
  326. "addGlobalInstructionSelect is not overridden",
  327. inconvertibleErrorCode());
  328. }
  329. /// @}}
  330. /// High level function that adds all passes necessary to go from llvm IR
  331. /// representation to the MI representation.
  332. /// Adds IR based lowering and target specific optimization passes and finally
  333. /// the core instruction selection passes.
  334. void addISelPasses(AddIRPass &) const;
  335. /// Add the actual instruction selection passes. This does not include
  336. /// preparation passes on IR.
  337. Error addCoreISelPasses(AddMachinePass &) const;
  338. /// Add the complete, standard set of LLVM CodeGen passes.
  339. /// Fully developed targets will not generally override this.
  340. Error addMachinePasses(AddMachinePass &) const;
  341. /// Add passes to lower exception handling for the code generator.
  342. void addPassesToHandleExceptions(AddIRPass &) const;
  343. /// Add common target configurable passes that perform LLVM IR to IR
  344. /// transforms following machine independent optimization.
  345. void addIRPasses(AddIRPass &) const;
  346. /// Add pass to prepare the LLVM IR for code generation. This should be done
  347. /// before exception handling preparation passes.
  348. void addCodeGenPrepare(AddIRPass &) const;
  349. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  350. /// instruction selection.
  351. void addISelPrepare(AddIRPass &) const;
  352. /// Methods with trivial inline returns are convenient points in the common
  353. /// codegen pass pipeline where targets may insert passes. Methods with
  354. /// out-of-line standard implementations are major CodeGen stages called by
  355. /// addMachinePasses. Some targets may override major stages when inserting
  356. /// passes is insufficient, but maintaining overriden stages is more work.
  357. ///
  358. /// addMachineSSAOptimization - Add standard passes that optimize machine
  359. /// instructions in SSA form.
  360. void addMachineSSAOptimization(AddMachinePass &) const;
  361. /// addFastRegAlloc - Add the minimum set of target-independent passes that
  362. /// are required for fast register allocation.
  363. Error addFastRegAlloc(AddMachinePass &) const;
  364. /// addOptimizedRegAlloc - Add passes related to register allocation.
  365. /// LLVMTargetMachine provides standard regalloc passes for most targets.
  366. void addOptimizedRegAlloc(AddMachinePass &) const;
  367. /// Add passes that optimize machine instructions after register allocation.
  368. void addMachineLateOptimization(AddMachinePass &) const;
  369. /// addGCPasses - Add late codegen passes that analyze code for garbage
  370. /// collection. This should return true if GC info should be printed after
  371. /// these passes.
  372. void addGCPasses(AddMachinePass &) const {}
  373. /// Add standard basic block placement passes.
  374. void addBlockPlacement(AddMachinePass &) const;
  375. using CreateMCStreamer =
  376. std::function<Expected<std::unique_ptr<MCStreamer>>(MCContext &)>;
  377. void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const {
  378. llvm_unreachable("addAsmPrinter is not overridden");
  379. }
  380. /// Utilities for targets to add passes to the pass manager.
  381. ///
  382. /// createTargetRegisterAllocator - Create the register allocator pass for
  383. /// this target at the current optimization level.
  384. void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const;
  385. /// addMachinePasses helper to create the target-selected or overriden
  386. /// regalloc pass.
  387. void addRegAllocPass(AddMachinePass &, bool Optimized) const;
  388. /// Add core register alloator passes which do the actual register assignment
  389. /// and rewriting. \returns true if any passes were added.
  390. Error addRegAssignmentFast(AddMachinePass &) const;
  391. Error addRegAssignmentOptimized(AddMachinePass &) const;
  392. private:
  393. DerivedT &derived() { return static_cast<DerivedT &>(*this); }
  394. const DerivedT &derived() const {
  395. return static_cast<const DerivedT &>(*this);
  396. }
  397. };
  398. template <typename Derived>
  399. Error CodeGenPassBuilder<Derived>::buildPipeline(
  400. ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
  401. raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
  402. CodeGenFileType FileType) const {
  403. AddIRPass addIRPass(MPM, Opt.DebugPM);
  404. addISelPasses(addIRPass);
  405. AddMachinePass addPass(MFPM);
  406. if (auto Err = addCoreISelPasses(addPass))
  407. return std::move(Err);
  408. if (auto Err = derived().addMachinePasses(addPass))
  409. return std::move(Err);
  410. derived().addAsmPrinter(
  411. addPass, [this, &Out, DwoOut, FileType](MCContext &Ctx) {
  412. return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
  413. });
  414. addPass(FreeMachineFunctionPass());
  415. return Error::success();
  416. }
  417. static inline AAManager registerAAAnalyses(CFLAAType UseCFLAA) {
  418. AAManager AA;
  419. // The order in which these are registered determines their priority when
  420. // being queried.
  421. switch (UseCFLAA) {
  422. case CFLAAType::Steensgaard:
  423. AA.registerFunctionAnalysis<CFLSteensAA>();
  424. break;
  425. case CFLAAType::Andersen:
  426. AA.registerFunctionAnalysis<CFLAndersAA>();
  427. break;
  428. case CFLAAType::Both:
  429. AA.registerFunctionAnalysis<CFLAndersAA>();
  430. AA.registerFunctionAnalysis<CFLSteensAA>();
  431. break;
  432. default:
  433. break;
  434. }
  435. // Basic AliasAnalysis support.
  436. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  437. // BasicAliasAnalysis wins if they disagree. This is intended to help
  438. // support "obvious" type-punning idioms.
  439. AA.registerFunctionAnalysis<TypeBasedAA>();
  440. AA.registerFunctionAnalysis<ScopedNoAliasAA>();
  441. AA.registerFunctionAnalysis<BasicAA>();
  442. return AA;
  443. }
  444. template <typename Derived>
  445. void CodeGenPassBuilder<Derived>::registerModuleAnalyses(
  446. ModuleAnalysisManager &MAM) const {
  447. #define MODULE_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR) \
  448. MAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
  449. #include "MachinePassRegistry.def"
  450. derived().registerTargetAnalysis(MAM);
  451. }
  452. template <typename Derived>
  453. void CodeGenPassBuilder<Derived>::registerFunctionAnalyses(
  454. FunctionAnalysisManager &FAM) const {
  455. FAM.registerPass([this] { return registerAAAnalyses(this->Opt.UseCFLAA); });
  456. #define FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR) \
  457. FAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
  458. #include "MachinePassRegistry.def"
  459. derived().registerTargetAnalysis(FAM);
  460. }
  461. template <typename Derived>
  462. void CodeGenPassBuilder<Derived>::registerMachineFunctionAnalyses(
  463. MachineFunctionAnalysisManager &MFAM) const {
  464. #define MACHINE_FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR) \
  465. MFAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
  466. #include "MachinePassRegistry.def"
  467. derived().registerTargetAnalysis(MFAM);
  468. }
  469. // FIXME: For new PM, use pass name directly in commandline seems good.
  470. // Translate stringfied pass name to its old commandline name. Returns the
  471. // matching legacy name and a boolean value indicating if the pass is a machine
  472. // pass.
  473. template <typename Derived>
  474. std::pair<StringRef, bool>
  475. CodeGenPassBuilder<Derived>::getPassNameFromLegacyName(StringRef Name) const {
  476. std::pair<StringRef, bool> Ret;
  477. if (Name.empty())
  478. return Ret;
  479. #define FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  480. if (Name == NAME) \
  481. Ret = {#PASS_NAME, false};
  482. #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  483. if (Name == NAME) \
  484. Ret = {#PASS_NAME, false};
  485. #define MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  486. if (Name == NAME) \
  487. Ret = {#PASS_NAME, false};
  488. #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  489. if (Name == NAME) \
  490. Ret = {#PASS_NAME, false};
  491. #define MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  492. if (Name == NAME) \
  493. Ret = {#PASS_NAME, true};
  494. #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  495. if (Name == NAME) \
  496. Ret = {#PASS_NAME, true};
  497. #define MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  498. if (Name == NAME) \
  499. Ret = {#PASS_NAME, true};
  500. #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR) \
  501. if (Name == NAME) \
  502. Ret = {#PASS_NAME, true};
  503. #include "llvm/CodeGen/MachinePassRegistry.def"
  504. if (Ret.first.empty())
  505. Ret = derived().getTargetPassNameFromLegacyName(Name);
  506. if (Ret.first.empty())
  507. report_fatal_error(Twine('\"') + Twine(Name) +
  508. Twine("\" pass could not be found."));
  509. return Ret;
  510. }
  511. template <typename Derived>
  512. void CodeGenPassBuilder<Derived>::addISelPasses(AddIRPass &addPass) const {
  513. if (TM.useEmulatedTLS())
  514. addPass(LowerEmuTLSPass());
  515. addPass(PreISelIntrinsicLoweringPass());
  516. derived().addIRPasses(addPass);
  517. derived().addCodeGenPrepare(addPass);
  518. addPassesToHandleExceptions(addPass);
  519. derived().addISelPrepare(addPass);
  520. }
  521. /// Add common target configurable passes that perform LLVM IR to IR transforms
  522. /// following machine independent optimization.
  523. template <typename Derived>
  524. void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
  525. // Before running any passes, run the verifier to determine if the input
  526. // coming from the front-end and/or optimizer is valid.
  527. if (!Opt.DisableVerify)
  528. addPass(VerifierPass());
  529. // Run loop strength reduction before anything else.
  530. if (getOptLevel() != CodeGenOpt::None && !Opt.DisableLSR) {
  531. addPass(createFunctionToLoopPassAdaptor(
  532. LoopStrengthReducePass(), /*UseMemorySSA*/ true, Opt.DebugPM));
  533. // FIXME: use -stop-after so we could remove PrintLSR
  534. if (Opt.PrintLSR)
  535. addPass(PrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
  536. }
  537. if (getOptLevel() != CodeGenOpt::None) {
  538. // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
  539. // loads and compares. ExpandMemCmpPass then tries to expand those calls
  540. // into optimally-sized loads and compares. The transforms are enabled by a
  541. // target lowering hook.
  542. if (!Opt.DisableMergeICmps)
  543. addPass(MergeICmpsPass());
  544. addPass(ExpandMemCmpPass());
  545. }
  546. // Run GC lowering passes for builtin collectors
  547. // TODO: add a pass insertion point here
  548. addPass(GCLoweringPass());
  549. addPass(ShadowStackGCLoweringPass());
  550. addPass(LowerConstantIntrinsicsPass());
  551. // Make sure that no unreachable blocks are instruction selected.
  552. addPass(UnreachableBlockElimPass());
  553. // Prepare expensive constants for SelectionDAG.
  554. if (getOptLevel() != CodeGenOpt::None && !Opt.DisableConstantHoisting)
  555. addPass(ConstantHoistingPass());
  556. // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
  557. // operands with calls to the corresponding functions in a vector library.
  558. if (getOptLevel() != CodeGenOpt::None)
  559. addPass(ReplaceWithVeclib());
  560. if (getOptLevel() != CodeGenOpt::None && !Opt.DisablePartialLibcallInlining)
  561. addPass(PartiallyInlineLibCallsPass());
  562. // Instrument function entry and exit, e.g. with calls to mcount().
  563. addPass(EntryExitInstrumenterPass(/*PostInlining=*/true));
  564. // Add scalarization of target's unsupported masked memory intrinsics pass.
  565. // the unsupported intrinsic will be replaced with a chain of basic blocks,
  566. // that stores/loads element one-by-one if the appropriate mask bit is set.
  567. addPass(ScalarizeMaskedMemIntrinPass());
  568. // Expand reduction intrinsics into shuffle sequences if the target wants to.
  569. addPass(ExpandReductionsPass());
  570. }
  571. /// Turn exception handling constructs into something the code generators can
  572. /// handle.
  573. template <typename Derived>
  574. void CodeGenPassBuilder<Derived>::addPassesToHandleExceptions(
  575. AddIRPass &addPass) const {
  576. const MCAsmInfo *MCAI = TM.getMCAsmInfo();
  577. assert(MCAI && "No MCAsmInfo");
  578. switch (MCAI->getExceptionHandlingType()) {
  579. case ExceptionHandling::SjLj:
  580. // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
  581. // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
  582. // catch info can get misplaced when a selector ends up more than one block
  583. // removed from the parent invoke(s). This could happen when a landing
  584. // pad is shared by multiple invokes and is also a target of a normal
  585. // edge from elsewhere.
  586. addPass(SjLjEHPreparePass());
  587. LLVM_FALLTHROUGH;
  588. case ExceptionHandling::DwarfCFI:
  589. case ExceptionHandling::ARM:
  590. case ExceptionHandling::AIX:
  591. addPass(DwarfEHPass(getOptLevel()));
  592. break;
  593. case ExceptionHandling::WinEH:
  594. // We support using both GCC-style and MSVC-style exceptions on Windows, so
  595. // add both preparation passes. Each pass will only actually run if it
  596. // recognizes the personality function.
  597. addPass(WinEHPass());
  598. addPass(DwarfEHPass(getOptLevel()));
  599. break;
  600. case ExceptionHandling::Wasm:
  601. // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
  602. // on catchpads and cleanuppads because it does not outline them into
  603. // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
  604. // should remove PHIs there.
  605. addPass(WinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
  606. addPass(WasmEHPass());
  607. break;
  608. case ExceptionHandling::None:
  609. addPass(LowerInvokePass());
  610. // The lower invoke pass may create unreachable code. Remove it.
  611. addPass(UnreachableBlockElimPass());
  612. break;
  613. }
  614. }
  615. /// Add pass to prepare the LLVM IR for code generation. This should be done
  616. /// before exception handling preparation passes.
  617. template <typename Derived>
  618. void CodeGenPassBuilder<Derived>::addCodeGenPrepare(AddIRPass &addPass) const {
  619. if (getOptLevel() != CodeGenOpt::None && !Opt.DisableCGP)
  620. addPass(CodeGenPreparePass());
  621. // TODO: Default ctor'd RewriteSymbolPass is no-op.
  622. // addPass(RewriteSymbolPass());
  623. }
  624. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  625. /// instruction selection.
  626. template <typename Derived>
  627. void CodeGenPassBuilder<Derived>::addISelPrepare(AddIRPass &addPass) const {
  628. derived().addPreISel(addPass);
  629. // Add both the safe stack and the stack protection passes: each of them will
  630. // only protect functions that have corresponding attributes.
  631. addPass(SafeStackPass());
  632. addPass(StackProtectorPass());
  633. if (Opt.PrintISelInput)
  634. addPass(PrintFunctionPass(dbgs(),
  635. "\n\n*** Final LLVM Code input to ISel ***\n"));
  636. // All passes which modify the LLVM IR are now complete; run the verifier
  637. // to ensure that the IR is valid.
  638. if (!Opt.DisableVerify)
  639. addPass(VerifierPass());
  640. }
  641. template <typename Derived>
  642. Error CodeGenPassBuilder<Derived>::addCoreISelPasses(
  643. AddMachinePass &addPass) const {
  644. // Enable FastISel with -fast-isel, but allow that to be overridden.
  645. TM.setO0WantsFastISel(Opt.EnableFastISelOption.getValueOr(true));
  646. // Determine an instruction selector.
  647. enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
  648. SelectorType Selector;
  649. if (Opt.EnableFastISelOption && *Opt.EnableFastISelOption == true)
  650. Selector = SelectorType::FastISel;
  651. else if ((Opt.EnableGlobalISelOption &&
  652. *Opt.EnableGlobalISelOption == true) ||
  653. (TM.Options.EnableGlobalISel &&
  654. (!Opt.EnableGlobalISelOption ||
  655. *Opt.EnableGlobalISelOption == false)))
  656. Selector = SelectorType::GlobalISel;
  657. else if (TM.getOptLevel() == CodeGenOpt::None && TM.getO0WantsFastISel())
  658. Selector = SelectorType::FastISel;
  659. else
  660. Selector = SelectorType::SelectionDAG;
  661. // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
  662. if (Selector == SelectorType::FastISel) {
  663. TM.setFastISel(true);
  664. TM.setGlobalISel(false);
  665. } else if (Selector == SelectorType::GlobalISel) {
  666. TM.setFastISel(false);
  667. TM.setGlobalISel(true);
  668. }
  669. // Add instruction selector passes.
  670. if (Selector == SelectorType::GlobalISel) {
  671. if (auto Err = derived().addIRTranslator(addPass))
  672. return std::move(Err);
  673. derived().addPreLegalizeMachineIR(addPass);
  674. if (auto Err = derived().addLegalizeMachineIR(addPass))
  675. return std::move(Err);
  676. // Before running the register bank selector, ask the target if it
  677. // wants to run some passes.
  678. derived().addPreRegBankSelect(addPass);
  679. if (auto Err = derived().addRegBankSelect(addPass))
  680. return std::move(Err);
  681. derived().addPreGlobalInstructionSelect(addPass);
  682. if (auto Err = derived().addGlobalInstructionSelect(addPass))
  683. return std::move(Err);
  684. // Pass to reset the MachineFunction if the ISel failed.
  685. addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
  686. isGlobalISelAbortEnabled()));
  687. // Provide a fallback path when we do not want to abort on
  688. // not-yet-supported input.
  689. if (!isGlobalISelAbortEnabled())
  690. if (auto Err = derived().addInstSelector(addPass))
  691. return std::move(Err);
  692. } else if (auto Err = derived().addInstSelector(addPass))
  693. return std::move(Err);
  694. // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
  695. // FinalizeISel.
  696. addPass(FinalizeISelPass());
  697. // // Print the instruction selected machine code...
  698. // printAndVerify("After Instruction Selection");
  699. return Error::success();
  700. }
  701. /// Add the complete set of target-independent postISel code generator passes.
  702. ///
  703. /// This can be read as the standard order of major LLVM CodeGen stages. Stages
  704. /// with nontrivial configuration or multiple passes are broken out below in
  705. /// add%Stage routines.
  706. ///
  707. /// Any CodeGenPassBuilder<Derived>::addXX routine may be overriden by the
  708. /// Target. The addPre/Post methods with empty header implementations allow
  709. /// injecting target-specific fixups just before or after major stages.
  710. /// Additionally, targets have the flexibility to change pass order within a
  711. /// stage by overriding default implementation of add%Stage routines below. Each
  712. /// technique has maintainability tradeoffs because alternate pass orders are
  713. /// not well supported. addPre/Post works better if the target pass is easily
  714. /// tied to a common pass. But if it has subtle dependencies on multiple passes,
  715. /// the target should override the stage instead.
  716. template <typename Derived>
  717. Error CodeGenPassBuilder<Derived>::addMachinePasses(
  718. AddMachinePass &addPass) const {
  719. // Add passes that optimize machine instructions in SSA form.
  720. if (getOptLevel() != CodeGenOpt::None) {
  721. derived().addMachineSSAOptimization(addPass);
  722. } else {
  723. // If the target requests it, assign local variables to stack slots relative
  724. // to one another and simplify frame index references where possible.
  725. addPass(LocalStackSlotPass());
  726. }
  727. if (TM.Options.EnableIPRA)
  728. addPass(RegUsageInfoPropagationPass());
  729. // Run pre-ra passes.
  730. derived().addPreRegAlloc(addPass);
  731. // Run register allocation and passes that are tightly coupled with it,
  732. // including phi elimination and scheduling.
  733. if (*Opt.OptimizeRegAlloc) {
  734. derived().addOptimizedRegAlloc(addPass);
  735. } else {
  736. if (auto Err = derived().addFastRegAlloc(addPass))
  737. return Err;
  738. }
  739. // Run post-ra passes.
  740. derived().addPostRegAlloc(addPass);
  741. // Insert prolog/epilog code. Eliminate abstract frame index references...
  742. if (getOptLevel() != CodeGenOpt::None) {
  743. addPass(PostRAMachineSinkingPass());
  744. addPass(ShrinkWrapPass());
  745. }
  746. addPass(PrologEpilogInserterPass());
  747. /// Add passes that optimize machine instructions after register allocation.
  748. if (getOptLevel() != CodeGenOpt::None)
  749. derived().addMachineLateOptimization(addPass);
  750. // Expand pseudo instructions before second scheduling pass.
  751. addPass(ExpandPostRAPseudosPass());
  752. // Run pre-sched2 passes.
  753. derived().addPreSched2(addPass);
  754. if (Opt.EnableImplicitNullChecks)
  755. addPass(ImplicitNullChecksPass());
  756. // Second pass scheduler.
  757. // Let Target optionally insert this pass by itself at some other
  758. // point.
  759. if (getOptLevel() != CodeGenOpt::None &&
  760. !TM.targetSchedulesPostRAScheduling()) {
  761. if (Opt.MISchedPostRA)
  762. addPass(PostMachineSchedulerPass());
  763. else
  764. addPass(PostRASchedulerPass());
  765. }
  766. // GC
  767. derived().addGCPasses(addPass);
  768. // Basic block placement.
  769. if (getOptLevel() != CodeGenOpt::None)
  770. derived().addBlockPlacement(addPass);
  771. // Insert before XRay Instrumentation.
  772. addPass(FEntryInserterPass());
  773. addPass(XRayInstrumentationPass());
  774. addPass(PatchableFunctionPass());
  775. derived().addPreEmitPass(addPass);
  776. if (TM.Options.EnableIPRA)
  777. // Collect register usage information and produce a register mask of
  778. // clobbered registers, to be used to optimize call sites.
  779. addPass(RegUsageInfoCollectorPass());
  780. addPass(FuncletLayoutPass());
  781. addPass(StackMapLivenessPass());
  782. addPass(LiveDebugValuesPass());
  783. if (TM.Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
  784. Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
  785. bool RunOnAllFunctions =
  786. (Opt.EnableMachineOutliner == RunOutliner::AlwaysOutline);
  787. bool AddOutliner = RunOnAllFunctions || TM.Options.SupportsDefaultOutlining;
  788. if (AddOutliner)
  789. addPass(MachineOutlinerPass(RunOnAllFunctions));
  790. }
  791. // Add passes that directly emit MI after all other MI passes.
  792. derived().addPreEmitPass2(addPass);
  793. return Error::success();
  794. }
  795. /// Add passes that optimize machine instructions in SSA form.
  796. template <typename Derived>
  797. void CodeGenPassBuilder<Derived>::addMachineSSAOptimization(
  798. AddMachinePass &addPass) const {
  799. // Pre-ra tail duplication.
  800. addPass(EarlyTailDuplicatePass());
  801. // Optimize PHIs before DCE: removing dead PHI cycles may make more
  802. // instructions dead.
  803. addPass(OptimizePHIsPass());
  804. // This pass merges large allocas. StackSlotColoring is a different pass
  805. // which merges spill slots.
  806. addPass(StackColoringPass());
  807. // If the target requests it, assign local variables to stack slots relative
  808. // to one another and simplify frame index references where possible.
  809. addPass(LocalStackSlotPass());
  810. // With optimization, dead code should already be eliminated. However
  811. // there is one known exception: lowered code for arguments that are only
  812. // used by tail calls, where the tail calls reuse the incoming stack
  813. // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
  814. addPass(DeadMachineInstructionElimPass());
  815. // Allow targets to insert passes that improve instruction level parallelism,
  816. // like if-conversion. Such passes will typically need dominator trees and
  817. // loop info, just like LICM and CSE below.
  818. derived().addILPOpts(addPass);
  819. addPass(EarlyMachineLICMPass());
  820. addPass(MachineCSEPass());
  821. addPass(MachineSinkingPass());
  822. addPass(PeepholeOptimizerPass());
  823. // Clean-up the dead code that may have been generated by peephole
  824. // rewriting.
  825. addPass(DeadMachineInstructionElimPass());
  826. }
  827. //===---------------------------------------------------------------------===//
  828. /// Register Allocation Pass Configuration
  829. //===---------------------------------------------------------------------===//
  830. /// Instantiate the default register allocator pass for this target for either
  831. /// the optimized or unoptimized allocation path. This will be added to the pass
  832. /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
  833. /// in the optimized case.
  834. ///
  835. /// A target that uses the standard regalloc pass order for fast or optimized
  836. /// allocation may still override this for per-target regalloc
  837. /// selection. But -regalloc=... always takes precedence.
  838. template <typename Derived>
  839. void CodeGenPassBuilder<Derived>::addTargetRegisterAllocator(
  840. AddMachinePass &addPass, bool Optimized) const {
  841. if (Optimized)
  842. addPass(RAGreedyPass());
  843. else
  844. addPass(RAFastPass());
  845. }
  846. /// Find and instantiate the register allocation pass requested by this target
  847. /// at the current optimization level. Different register allocators are
  848. /// defined as separate passes because they may require different analysis.
  849. template <typename Derived>
  850. void CodeGenPassBuilder<Derived>::addRegAllocPass(AddMachinePass &addPass,
  851. bool Optimized) const {
  852. if (Opt.RegAlloc == RegAllocType::Default)
  853. // With no -regalloc= override, ask the target for a regalloc pass.
  854. derived().addTargetRegisterAllocator(addPass, Optimized);
  855. else if (Opt.RegAlloc == RegAllocType::Basic)
  856. addPass(RABasicPass());
  857. else if (Opt.RegAlloc == RegAllocType::Fast)
  858. addPass(RAFastPass());
  859. else if (Opt.RegAlloc == RegAllocType::Greedy)
  860. addPass(RAGreedyPass());
  861. else if (Opt.RegAlloc == RegAllocType::PBQP)
  862. addPass(RAPBQPPass());
  863. else
  864. llvm_unreachable("unknonwn register allocator type");
  865. }
  866. template <typename Derived>
  867. Error CodeGenPassBuilder<Derived>::addRegAssignmentFast(
  868. AddMachinePass &addPass) const {
  869. if (Opt.RegAlloc != RegAllocType::Default &&
  870. Opt.RegAlloc != RegAllocType::Fast)
  871. return make_error<StringError>(
  872. "Must use fast (default) register allocator for unoptimized regalloc.",
  873. inconvertibleErrorCode());
  874. addRegAllocPass(addPass, false);
  875. return Error::success();
  876. }
  877. template <typename Derived>
  878. Error CodeGenPassBuilder<Derived>::addRegAssignmentOptimized(
  879. AddMachinePass &addPass) const {
  880. // Add the selected register allocation pass.
  881. addRegAllocPass(addPass, true);
  882. // Allow targets to change the register assignments before rewriting.
  883. derived().addPreRewrite(addPass);
  884. // Finally rewrite virtual registers.
  885. addPass(VirtRegRewriterPass());
  886. // Perform stack slot coloring and post-ra machine LICM.
  887. //
  888. // FIXME: Re-enable coloring with register when it's capable of adding
  889. // kill markers.
  890. addPass(StackSlotColoringPass());
  891. return Error::success();
  892. }
  893. /// Add the minimum set of target-independent passes that are required for
  894. /// register allocation. No coalescing or scheduling.
  895. template <typename Derived>
  896. Error CodeGenPassBuilder<Derived>::addFastRegAlloc(
  897. AddMachinePass &addPass) const {
  898. addPass(PHIEliminationPass());
  899. addPass(TwoAddressInstructionPass());
  900. return derived().addRegAssignmentFast(addPass);
  901. }
  902. /// Add standard target-independent passes that are tightly coupled with
  903. /// optimized register allocation, including coalescing, machine instruction
  904. /// scheduling, and register allocation itself.
  905. template <typename Derived>
  906. void CodeGenPassBuilder<Derived>::addOptimizedRegAlloc(
  907. AddMachinePass &addPass) const {
  908. addPass(DetectDeadLanesPass());
  909. addPass(ProcessImplicitDefsPass());
  910. // Edge splitting is smarter with machine loop info.
  911. addPass(PHIEliminationPass());
  912. // Eventually, we want to run LiveIntervals before PHI elimination.
  913. if (Opt.EarlyLiveIntervals)
  914. addPass(LiveIntervalsPass());
  915. addPass(TwoAddressInstructionPass());
  916. addPass(RegisterCoalescerPass());
  917. // The machine scheduler may accidentally create disconnected components
  918. // when moving subregister definitions around, avoid this by splitting them to
  919. // separate vregs before. Splitting can also improve reg. allocation quality.
  920. addPass(RenameIndependentSubregsPass());
  921. // PreRA instruction scheduling.
  922. addPass(MachineSchedulerPass());
  923. if (derived().addRegAssignmentOptimized(addPass)) {
  924. // Allow targets to expand pseudo instructions depending on the choice of
  925. // registers before MachineCopyPropagation.
  926. derived().addPostRewrite(addPass);
  927. // Copy propagate to forward register uses and try to eliminate COPYs that
  928. // were not coalesced.
  929. addPass(MachineCopyPropagationPass());
  930. // Run post-ra machine LICM to hoist reloads / remats.
  931. //
  932. // FIXME: can this move into MachineLateOptimization?
  933. addPass(MachineLICMPass());
  934. }
  935. }
  936. //===---------------------------------------------------------------------===//
  937. /// Post RegAlloc Pass Configuration
  938. //===---------------------------------------------------------------------===//
  939. /// Add passes that optimize machine instructions after register allocation.
  940. template <typename Derived>
  941. void CodeGenPassBuilder<Derived>::addMachineLateOptimization(
  942. AddMachinePass &addPass) const {
  943. // Branch folding must be run after regalloc and prolog/epilog insertion.
  944. addPass(BranchFolderPass());
  945. // Tail duplication.
  946. // Note that duplicating tail just increases code size and degrades
  947. // performance for targets that require Structured Control Flow.
  948. // In addition it can also make CFG irreducible. Thus we disable it.
  949. if (!TM.requiresStructuredCFG())
  950. addPass(TailDuplicatePass());
  951. // Copy propagation.
  952. addPass(MachineCopyPropagationPass());
  953. }
  954. /// Add standard basic block placement passes.
  955. template <typename Derived>
  956. void CodeGenPassBuilder<Derived>::addBlockPlacement(
  957. AddMachinePass &addPass) const {
  958. addPass(MachineBlockPlacementPass());
  959. // Run a separate pass to collect block placement statistics.
  960. if (Opt.EnableBlockPlacementStats)
  961. addPass(MachineBlockPlacementStatsPass());
  962. }
  963. } // namespace llvm
  964. #endif // LLVM_CODEGEN_CODEGENPASSBUILDER_H