TargetPassConfig.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. //===-- TargetPassConfig.cpp - Target independent code generation passes --===//
  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. // This file defines interfaces to access the target independent code
  11. // generation passes provided by the LLVM backend.
  12. //
  13. //===---------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/TargetPassConfig.h"
  15. #include "llvm/Analysis/BasicAliasAnalysis.h"
  16. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  17. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  18. #include "llvm/Analysis/CallGraphSCCPass.h"
  19. #include "llvm/Analysis/Passes.h"
  20. #include "llvm/Analysis/ScopedNoAliasAA.h"
  21. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  22. #include "llvm/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/RegAllocRegistry.h"
  24. #include "llvm/CodeGen/RegisterUsageInfo.h"
  25. #include "llvm/IR/IRPrintingPasses.h"
  26. #include "llvm/IR/LegacyPassManager.h"
  27. #include "llvm/IR/Verifier.h"
  28. #include "llvm/MC/MCAsmInfo.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Transforms/Instrumentation.h"
  34. #include "llvm/Transforms/Scalar.h"
  35. #include "llvm/Transforms/Utils/SymbolRewriter.h"
  36. using namespace llvm;
  37. static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
  38. cl::desc("Disable Post Regalloc"));
  39. static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
  40. cl::desc("Disable branch folding"));
  41. static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
  42. cl::desc("Disable tail duplication"));
  43. static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
  44. cl::desc("Disable pre-register allocation tail duplication"));
  45. static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
  46. cl::Hidden, cl::desc("Disable probability-driven block placement"));
  47. static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
  48. cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
  49. static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
  50. cl::desc("Disable Stack Slot Coloring"));
  51. static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
  52. cl::desc("Disable Machine Dead Code Elimination"));
  53. static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
  54. cl::desc("Disable Early If-conversion"));
  55. static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
  56. cl::desc("Disable Machine LICM"));
  57. static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
  58. cl::desc("Disable Machine Common Subexpression Elimination"));
  59. static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
  60. "optimize-regalloc", cl::Hidden,
  61. cl::desc("Enable optimized register allocation compilation path."));
  62. static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
  63. cl::Hidden,
  64. cl::desc("Disable Machine LICM"));
  65. static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
  66. cl::desc("Disable Machine Sinking"));
  67. static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
  68. cl::desc("Disable Loop Strength Reduction Pass"));
  69. static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
  70. cl::Hidden, cl::desc("Disable ConstantHoisting"));
  71. static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
  72. cl::desc("Disable Codegen Prepare"));
  73. static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
  74. cl::desc("Disable Copy Propagation pass"));
  75. static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
  76. cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
  77. static cl::opt<bool> EnableImplicitNullChecks(
  78. "enable-implicit-null-checks",
  79. cl::desc("Fold null checks into faulting memory operations"),
  80. cl::init(false));
  81. static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
  82. cl::desc("Print LLVM IR produced by the loop-reduce pass"));
  83. static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
  84. cl::desc("Print LLVM IR input to isel pass"));
  85. static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
  86. cl::desc("Dump garbage collector data"));
  87. static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
  88. cl::desc("Verify generated machine code"),
  89. cl::init(false),
  90. cl::ZeroOrMore);
  91. static cl::opt<std::string>
  92. PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
  93. cl::desc("Print machine instrs"),
  94. cl::value_desc("pass-name"), cl::init("option-unspecified"));
  95. static cl::opt<int> EnableGlobalISelAbort(
  96. "global-isel-abort", cl::Hidden,
  97. cl::desc("Enable abort calls when \"global\" instruction selection "
  98. "fails to lower/select an instruction: 0 disable the abort, "
  99. "1 enable the abort, and "
  100. "2 disable the abort but emit a diagnostic on failure"),
  101. cl::init(1));
  102. // Temporary option to allow experimenting with MachineScheduler as a post-RA
  103. // scheduler. Targets can "properly" enable this with
  104. // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
  105. // Targets can return true in targetSchedulesPostRAScheduling() and
  106. // insert a PostRA scheduling pass wherever it wants.
  107. cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
  108. cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
  109. // Experimental option to run live interval analysis early.
  110. static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
  111. cl::desc("Run live interval analysis earlier in the pipeline"));
  112. // Experimental option to use CFL-AA in codegen
  113. enum class CFLAAType { None, Steensgaard, Andersen, Both };
  114. static cl::opt<CFLAAType> UseCFLAA(
  115. "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
  116. cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
  117. cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
  118. clEnumValN(CFLAAType::Steensgaard, "steens",
  119. "Enable unification-based CFL-AA"),
  120. clEnumValN(CFLAAType::Andersen, "anders",
  121. "Enable inclusion-based CFL-AA"),
  122. clEnumValN(CFLAAType::Both, "both",
  123. "Enable both variants of CFL-AA"),
  124. clEnumValEnd));
  125. /// Allow standard passes to be disabled by command line options. This supports
  126. /// simple binary flags that either suppress the pass or do nothing.
  127. /// i.e. -disable-mypass=false has no effect.
  128. /// These should be converted to boolOrDefault in order to use applyOverride.
  129. static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
  130. bool Override) {
  131. if (Override)
  132. return IdentifyingPassPtr();
  133. return PassID;
  134. }
  135. /// Allow standard passes to be disabled by the command line, regardless of who
  136. /// is adding the pass.
  137. ///
  138. /// StandardID is the pass identified in the standard pass pipeline and provided
  139. /// to addPass(). It may be a target-specific ID in the case that the target
  140. /// directly adds its own pass, but in that case we harmlessly fall through.
  141. ///
  142. /// TargetID is the pass that the target has configured to override StandardID.
  143. ///
  144. /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
  145. /// pass to run. This allows multiple options to control a single pass depending
  146. /// on where in the pipeline that pass is added.
  147. static IdentifyingPassPtr overridePass(AnalysisID StandardID,
  148. IdentifyingPassPtr TargetID) {
  149. if (StandardID == &PostRASchedulerID)
  150. return applyDisable(TargetID, DisablePostRA);
  151. if (StandardID == &BranchFolderPassID)
  152. return applyDisable(TargetID, DisableBranchFold);
  153. if (StandardID == &TailDuplicateID)
  154. return applyDisable(TargetID, DisableTailDuplicate);
  155. if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
  156. return applyDisable(TargetID, DisableEarlyTailDup);
  157. if (StandardID == &MachineBlockPlacementID)
  158. return applyDisable(TargetID, DisableBlockPlacement);
  159. if (StandardID == &StackSlotColoringID)
  160. return applyDisable(TargetID, DisableSSC);
  161. if (StandardID == &DeadMachineInstructionElimID)
  162. return applyDisable(TargetID, DisableMachineDCE);
  163. if (StandardID == &EarlyIfConverterID)
  164. return applyDisable(TargetID, DisableEarlyIfConversion);
  165. if (StandardID == &MachineLICMID)
  166. return applyDisable(TargetID, DisableMachineLICM);
  167. if (StandardID == &MachineCSEID)
  168. return applyDisable(TargetID, DisableMachineCSE);
  169. if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
  170. return applyDisable(TargetID, DisablePostRAMachineLICM);
  171. if (StandardID == &MachineSinkingID)
  172. return applyDisable(TargetID, DisableMachineSink);
  173. if (StandardID == &MachineCopyPropagationID)
  174. return applyDisable(TargetID, DisableCopyProp);
  175. return TargetID;
  176. }
  177. //===---------------------------------------------------------------------===//
  178. /// TargetPassConfig
  179. //===---------------------------------------------------------------------===//
  180. INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
  181. "Target Pass Configuration", false, false)
  182. char TargetPassConfig::ID = 0;
  183. // Pseudo Pass IDs.
  184. char TargetPassConfig::EarlyTailDuplicateID = 0;
  185. char TargetPassConfig::PostRAMachineLICMID = 0;
  186. namespace {
  187. struct InsertedPass {
  188. AnalysisID TargetPassID;
  189. IdentifyingPassPtr InsertedPassID;
  190. bool VerifyAfter;
  191. bool PrintAfter;
  192. InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
  193. bool VerifyAfter, bool PrintAfter)
  194. : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
  195. VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
  196. Pass *getInsertedPass() const {
  197. assert(InsertedPassID.isValid() && "Illegal Pass ID!");
  198. if (InsertedPassID.isInstance())
  199. return InsertedPassID.getInstance();
  200. Pass *NP = Pass::createPass(InsertedPassID.getID());
  201. assert(NP && "Pass ID not registered");
  202. return NP;
  203. }
  204. };
  205. }
  206. namespace llvm {
  207. class PassConfigImpl {
  208. public:
  209. // List of passes explicitly substituted by this target. Normally this is
  210. // empty, but it is a convenient way to suppress or replace specific passes
  211. // that are part of a standard pass pipeline without overridding the entire
  212. // pipeline. This mechanism allows target options to inherit a standard pass's
  213. // user interface. For example, a target may disable a standard pass by
  214. // default by substituting a pass ID of zero, and the user may still enable
  215. // that standard pass with an explicit command line option.
  216. DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
  217. /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
  218. /// is inserted after each instance of the first one.
  219. SmallVector<InsertedPass, 4> InsertedPasses;
  220. };
  221. } // namespace llvm
  222. // Out of line virtual method.
  223. TargetPassConfig::~TargetPassConfig() {
  224. delete Impl;
  225. }
  226. // Out of line constructor provides default values for pass options and
  227. // registers all common codegen passes.
  228. TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
  229. : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
  230. StopAfter(nullptr), Started(true), Stopped(false),
  231. AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
  232. DisableVerify(false), EnableTailMerge(true) {
  233. Impl = new PassConfigImpl();
  234. // Register all target independent codegen passes to activate their PassIDs,
  235. // including this pass itself.
  236. initializeCodeGen(*PassRegistry::getPassRegistry());
  237. // Also register alias analysis passes required by codegen passes.
  238. initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
  239. initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
  240. // Substitute Pseudo Pass IDs for real ones.
  241. substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
  242. substitutePass(&PostRAMachineLICMID, &MachineLICMID);
  243. if (StringRef(PrintMachineInstrs.getValue()).equals(""))
  244. TM->Options.PrintMachineCode = true;
  245. }
  246. CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
  247. return TM->getOptLevel();
  248. }
  249. /// Insert InsertedPassID pass after TargetPassID.
  250. void TargetPassConfig::insertPass(AnalysisID TargetPassID,
  251. IdentifyingPassPtr InsertedPassID,
  252. bool VerifyAfter, bool PrintAfter) {
  253. assert(((!InsertedPassID.isInstance() &&
  254. TargetPassID != InsertedPassID.getID()) ||
  255. (InsertedPassID.isInstance() &&
  256. TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
  257. "Insert a pass after itself!");
  258. Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
  259. PrintAfter);
  260. }
  261. /// createPassConfig - Create a pass configuration object to be used by
  262. /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
  263. ///
  264. /// Targets may override this to extend TargetPassConfig.
  265. TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
  266. return new TargetPassConfig(this, PM);
  267. }
  268. TargetPassConfig::TargetPassConfig()
  269. : ImmutablePass(ID), PM(nullptr) {
  270. llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
  271. }
  272. // Helper to verify the analysis is really immutable.
  273. void TargetPassConfig::setOpt(bool &Opt, bool Val) {
  274. assert(!Initialized && "PassConfig is immutable");
  275. Opt = Val;
  276. }
  277. void TargetPassConfig::substitutePass(AnalysisID StandardID,
  278. IdentifyingPassPtr TargetID) {
  279. Impl->TargetPasses[StandardID] = TargetID;
  280. }
  281. IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
  282. DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
  283. I = Impl->TargetPasses.find(ID);
  284. if (I == Impl->TargetPasses.end())
  285. return ID;
  286. return I->second;
  287. }
  288. bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
  289. IdentifyingPassPtr TargetID = getPassSubstitution(ID);
  290. IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
  291. return !FinalPtr.isValid() || FinalPtr.isInstance() ||
  292. FinalPtr.getID() != ID;
  293. }
  294. /// Add a pass to the PassManager if that pass is supposed to be run. If the
  295. /// Started/Stopped flags indicate either that the compilation should start at
  296. /// a later pass or that it should stop after an earlier pass, then do not add
  297. /// the pass. Finally, compare the current pass against the StartAfter
  298. /// and StopAfter options and change the Started/Stopped flags accordingly.
  299. void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
  300. assert(!Initialized && "PassConfig is immutable");
  301. // Cache the Pass ID here in case the pass manager finds this pass is
  302. // redundant with ones already scheduled / available, and deletes it.
  303. // Fundamentally, once we add the pass to the manager, we no longer own it
  304. // and shouldn't reference it.
  305. AnalysisID PassID = P->getPassID();
  306. if (StartBefore == PassID)
  307. Started = true;
  308. if (Started && !Stopped) {
  309. std::string Banner;
  310. // Construct banner message before PM->add() as that may delete the pass.
  311. if (AddingMachinePasses && (printAfter || verifyAfter))
  312. Banner = std::string("After ") + std::string(P->getPassName());
  313. PM->add(P);
  314. if (AddingMachinePasses) {
  315. if (printAfter)
  316. addPrintPass(Banner);
  317. if (verifyAfter)
  318. addVerifyPass(Banner);
  319. }
  320. // Add the passes after the pass P if there is any.
  321. for (auto IP : Impl->InsertedPasses) {
  322. if (IP.TargetPassID == PassID)
  323. addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
  324. }
  325. } else {
  326. delete P;
  327. }
  328. if (StopAfter == PassID)
  329. Stopped = true;
  330. if (StartAfter == PassID)
  331. Started = true;
  332. if (Stopped && !Started)
  333. report_fatal_error("Cannot stop compilation after pass that is not run");
  334. }
  335. /// Add a CodeGen pass at this point in the pipeline after checking for target
  336. /// and command line overrides.
  337. ///
  338. /// addPass cannot return a pointer to the pass instance because is internal the
  339. /// PassManager and the instance we create here may already be freed.
  340. AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
  341. bool printAfter) {
  342. IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
  343. IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
  344. if (!FinalPtr.isValid())
  345. return nullptr;
  346. Pass *P;
  347. if (FinalPtr.isInstance())
  348. P = FinalPtr.getInstance();
  349. else {
  350. P = Pass::createPass(FinalPtr.getID());
  351. if (!P)
  352. llvm_unreachable("Pass ID not registered");
  353. }
  354. AnalysisID FinalID = P->getPassID();
  355. addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
  356. return FinalID;
  357. }
  358. void TargetPassConfig::printAndVerify(const std::string &Banner) {
  359. addPrintPass(Banner);
  360. addVerifyPass(Banner);
  361. }
  362. void TargetPassConfig::addPrintPass(const std::string &Banner) {
  363. if (TM->shouldPrintMachineCode())
  364. PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
  365. }
  366. void TargetPassConfig::addVerifyPass(const std::string &Banner) {
  367. if (VerifyMachineCode)
  368. PM->add(createMachineVerifierPass(Banner));
  369. }
  370. /// Add common target configurable passes that perform LLVM IR to IR transforms
  371. /// following machine independent optimization.
  372. void TargetPassConfig::addIRPasses() {
  373. switch (UseCFLAA) {
  374. case CFLAAType::Steensgaard:
  375. addPass(createCFLSteensAAWrapperPass());
  376. break;
  377. case CFLAAType::Andersen:
  378. addPass(createCFLAndersAAWrapperPass());
  379. break;
  380. case CFLAAType::Both:
  381. addPass(createCFLAndersAAWrapperPass());
  382. addPass(createCFLSteensAAWrapperPass());
  383. break;
  384. default:
  385. break;
  386. }
  387. // Basic AliasAnalysis support.
  388. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  389. // BasicAliasAnalysis wins if they disagree. This is intended to help
  390. // support "obvious" type-punning idioms.
  391. addPass(createTypeBasedAAWrapperPass());
  392. addPass(createScopedNoAliasAAWrapperPass());
  393. addPass(createBasicAAWrapperPass());
  394. // Before running any passes, run the verifier to determine if the input
  395. // coming from the front-end and/or optimizer is valid.
  396. if (!DisableVerify)
  397. addPass(createVerifierPass());
  398. // Run loop strength reduction before anything else.
  399. if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
  400. addPass(createLoopStrengthReducePass());
  401. if (PrintLSR)
  402. addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
  403. }
  404. // Run GC lowering passes for builtin collectors
  405. // TODO: add a pass insertion point here
  406. addPass(createGCLoweringPass());
  407. addPass(createShadowStackGCLoweringPass());
  408. // Make sure that no unreachable blocks are instruction selected.
  409. addPass(createUnreachableBlockEliminationPass());
  410. // Prepare expensive constants for SelectionDAG.
  411. if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
  412. addPass(createConstantHoistingPass());
  413. if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
  414. addPass(createPartiallyInlineLibCallsPass());
  415. // Insert calls to mcount-like functions.
  416. addPass(createCountingFunctionInserterPass());
  417. }
  418. /// Turn exception handling constructs into something the code generators can
  419. /// handle.
  420. void TargetPassConfig::addPassesToHandleExceptions() {
  421. const MCAsmInfo *MCAI = TM->getMCAsmInfo();
  422. assert(MCAI && "No MCAsmInfo");
  423. switch (MCAI->getExceptionHandlingType()) {
  424. case ExceptionHandling::SjLj:
  425. // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
  426. // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
  427. // catch info can get misplaced when a selector ends up more than one block
  428. // removed from the parent invoke(s). This could happen when a landing
  429. // pad is shared by multiple invokes and is also a target of a normal
  430. // edge from elsewhere.
  431. addPass(createSjLjEHPreparePass());
  432. LLVM_FALLTHROUGH;
  433. case ExceptionHandling::DwarfCFI:
  434. case ExceptionHandling::ARM:
  435. addPass(createDwarfEHPass(TM));
  436. break;
  437. case ExceptionHandling::WinEH:
  438. // We support using both GCC-style and MSVC-style exceptions on Windows, so
  439. // add both preparation passes. Each pass will only actually run if it
  440. // recognizes the personality function.
  441. addPass(createWinEHPass(TM));
  442. addPass(createDwarfEHPass(TM));
  443. break;
  444. case ExceptionHandling::None:
  445. addPass(createLowerInvokePass());
  446. // The lower invoke pass may create unreachable code. Remove it.
  447. addPass(createUnreachableBlockEliminationPass());
  448. break;
  449. }
  450. }
  451. /// Add pass to prepare the LLVM IR for code generation. This should be done
  452. /// before exception handling preparation passes.
  453. void TargetPassConfig::addCodeGenPrepare() {
  454. if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
  455. addPass(createCodeGenPreparePass(TM));
  456. addPass(createRewriteSymbolsPass());
  457. }
  458. /// Add common passes that perform LLVM IR to IR transforms in preparation for
  459. /// instruction selection.
  460. void TargetPassConfig::addISelPrepare() {
  461. addPreISel();
  462. // Force codegen to run according to the callgraph.
  463. if (TM->Options.EnableIPRA)
  464. addPass(new DummyCGSCCPass);
  465. // Add both the safe stack and the stack protection passes: each of them will
  466. // only protect functions that have corresponding attributes.
  467. addPass(createSafeStackPass(TM));
  468. addPass(createStackProtectorPass(TM));
  469. if (PrintISelInput)
  470. addPass(createPrintFunctionPass(
  471. dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
  472. // All passes which modify the LLVM IR are now complete; run the verifier
  473. // to ensure that the IR is valid.
  474. if (!DisableVerify)
  475. addPass(createVerifierPass());
  476. }
  477. /// Add the complete set of target-independent postISel code generator passes.
  478. ///
  479. /// This can be read as the standard order of major LLVM CodeGen stages. Stages
  480. /// with nontrivial configuration or multiple passes are broken out below in
  481. /// add%Stage routines.
  482. ///
  483. /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
  484. /// addPre/Post methods with empty header implementations allow injecting
  485. /// target-specific fixups just before or after major stages. Additionally,
  486. /// targets have the flexibility to change pass order within a stage by
  487. /// overriding default implementation of add%Stage routines below. Each
  488. /// technique has maintainability tradeoffs because alternate pass orders are
  489. /// not well supported. addPre/Post works better if the target pass is easily
  490. /// tied to a common pass. But if it has subtle dependencies on multiple passes,
  491. /// the target should override the stage instead.
  492. ///
  493. /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
  494. /// before/after any target-independent pass. But it's currently overkill.
  495. void TargetPassConfig::addMachinePasses() {
  496. AddingMachinePasses = true;
  497. if (TM->Options.EnableIPRA)
  498. addPass(createRegUsageInfoPropPass());
  499. // Insert a machine instr printer pass after the specified pass.
  500. if (!StringRef(PrintMachineInstrs.getValue()).equals("") &&
  501. !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) {
  502. const PassRegistry *PR = PassRegistry::getPassRegistry();
  503. const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
  504. const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
  505. assert (TPI && IPI && "Pass ID not registered!");
  506. const char *TID = (const char *)(TPI->getTypeInfo());
  507. const char *IID = (const char *)(IPI->getTypeInfo());
  508. insertPass(TID, IID);
  509. }
  510. // Print the instruction selected machine code...
  511. printAndVerify("After Instruction Selection");
  512. // Expand pseudo-instructions emitted by ISel.
  513. addPass(&ExpandISelPseudosID);
  514. // Add passes that optimize machine instructions in SSA form.
  515. if (getOptLevel() != CodeGenOpt::None) {
  516. addMachineSSAOptimization();
  517. } else {
  518. // If the target requests it, assign local variables to stack slots relative
  519. // to one another and simplify frame index references where possible.
  520. addPass(&LocalStackSlotAllocationID, false);
  521. }
  522. // Run pre-ra passes.
  523. addPreRegAlloc();
  524. // Run register allocation and passes that are tightly coupled with it,
  525. // including phi elimination and scheduling.
  526. if (getOptimizeRegAlloc())
  527. addOptimizedRegAlloc(createRegAllocPass(true));
  528. else
  529. addFastRegAlloc(createRegAllocPass(false));
  530. // Run post-ra passes.
  531. addPostRegAlloc();
  532. // Insert prolog/epilog code. Eliminate abstract frame index references...
  533. if (getOptLevel() != CodeGenOpt::None)
  534. addPass(&ShrinkWrapID);
  535. // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
  536. // do so if it hasn't been disabled, substituted, or overridden.
  537. if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
  538. addPass(createPrologEpilogInserterPass(TM));
  539. /// Add passes that optimize machine instructions after register allocation.
  540. if (getOptLevel() != CodeGenOpt::None)
  541. addMachineLateOptimization();
  542. // Expand pseudo instructions before second scheduling pass.
  543. addPass(&ExpandPostRAPseudosID);
  544. // Run pre-sched2 passes.
  545. addPreSched2();
  546. if (EnableImplicitNullChecks)
  547. addPass(&ImplicitNullChecksID);
  548. // Second pass scheduler.
  549. // Let Target optionally insert this pass by itself at some other
  550. // point.
  551. if (getOptLevel() != CodeGenOpt::None &&
  552. !TM->targetSchedulesPostRAScheduling()) {
  553. if (MISchedPostRA)
  554. addPass(&PostMachineSchedulerID);
  555. else
  556. addPass(&PostRASchedulerID);
  557. }
  558. // GC
  559. if (addGCPasses()) {
  560. if (PrintGCInfo)
  561. addPass(createGCInfoPrinter(dbgs()), false, false);
  562. }
  563. // Basic block placement.
  564. if (getOptLevel() != CodeGenOpt::None)
  565. addBlockPlacement();
  566. addPreEmitPass();
  567. if (TM->Options.EnableIPRA)
  568. // Collect register usage information and produce a register mask of
  569. // clobbered registers, to be used to optimize call sites.
  570. addPass(createRegUsageInfoCollector());
  571. addPass(&FuncletLayoutID, false);
  572. addPass(&StackMapLivenessID, false);
  573. addPass(&LiveDebugValuesID, false);
  574. addPass(&XRayInstrumentationID, false);
  575. addPass(&PatchableFunctionID, false);
  576. AddingMachinePasses = false;
  577. }
  578. /// Add passes that optimize machine instructions in SSA form.
  579. void TargetPassConfig::addMachineSSAOptimization() {
  580. // Pre-ra tail duplication.
  581. addPass(&EarlyTailDuplicateID);
  582. // Optimize PHIs before DCE: removing dead PHI cycles may make more
  583. // instructions dead.
  584. addPass(&OptimizePHIsID, false);
  585. // This pass merges large allocas. StackSlotColoring is a different pass
  586. // which merges spill slots.
  587. addPass(&StackColoringID, false);
  588. // If the target requests it, assign local variables to stack slots relative
  589. // to one another and simplify frame index references where possible.
  590. addPass(&LocalStackSlotAllocationID, false);
  591. // With optimization, dead code should already be eliminated. However
  592. // there is one known exception: lowered code for arguments that are only
  593. // used by tail calls, where the tail calls reuse the incoming stack
  594. // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
  595. addPass(&DeadMachineInstructionElimID);
  596. // Allow targets to insert passes that improve instruction level parallelism,
  597. // like if-conversion. Such passes will typically need dominator trees and
  598. // loop info, just like LICM and CSE below.
  599. addILPOpts();
  600. addPass(&MachineLICMID, false);
  601. addPass(&MachineCSEID, false);
  602. addPass(&MachineSinkingID);
  603. addPass(&PeepholeOptimizerID);
  604. // Clean-up the dead code that may have been generated by peephole
  605. // rewriting.
  606. addPass(&DeadMachineInstructionElimID);
  607. }
  608. //===---------------------------------------------------------------------===//
  609. /// Register Allocation Pass Configuration
  610. //===---------------------------------------------------------------------===//
  611. bool TargetPassConfig::getOptimizeRegAlloc() const {
  612. switch (OptimizeRegAlloc) {
  613. case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
  614. case cl::BOU_TRUE: return true;
  615. case cl::BOU_FALSE: return false;
  616. }
  617. llvm_unreachable("Invalid optimize-regalloc state");
  618. }
  619. /// RegisterRegAlloc's global Registry tracks allocator registration.
  620. MachinePassRegistry RegisterRegAlloc::Registry;
  621. /// A dummy default pass factory indicates whether the register allocator is
  622. /// overridden on the command line.
  623. LLVM_DEFINE_ONCE_FLAG(InitializeDefaultRegisterAllocatorFlag);
  624. static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
  625. static RegisterRegAlloc
  626. defaultRegAlloc("default",
  627. "pick register allocator based on -O option",
  628. useDefaultRegisterAllocator);
  629. /// -regalloc=... command line option.
  630. static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
  631. RegisterPassParser<RegisterRegAlloc> >
  632. RegAlloc("regalloc",
  633. cl::init(&useDefaultRegisterAllocator),
  634. cl::desc("Register allocator to use"));
  635. static void initializeDefaultRegisterAllocatorOnce() {
  636. RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
  637. if (!Ctor) {
  638. Ctor = RegAlloc;
  639. RegisterRegAlloc::setDefault(RegAlloc);
  640. }
  641. }
  642. /// Instantiate the default register allocator pass for this target for either
  643. /// the optimized or unoptimized allocation path. This will be added to the pass
  644. /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
  645. /// in the optimized case.
  646. ///
  647. /// A target that uses the standard regalloc pass order for fast or optimized
  648. /// allocation may still override this for per-target regalloc
  649. /// selection. But -regalloc=... always takes precedence.
  650. FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
  651. if (Optimized)
  652. return createGreedyRegisterAllocator();
  653. else
  654. return createFastRegisterAllocator();
  655. }
  656. /// Find and instantiate the register allocation pass requested by this target
  657. /// at the current optimization level. Different register allocators are
  658. /// defined as separate passes because they may require different analysis.
  659. ///
  660. /// This helper ensures that the regalloc= option is always available,
  661. /// even for targets that override the default allocator.
  662. ///
  663. /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
  664. /// this can be folded into addPass.
  665. FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
  666. // Initialize the global default.
  667. llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
  668. initializeDefaultRegisterAllocatorOnce);
  669. RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
  670. if (Ctor != useDefaultRegisterAllocator)
  671. return Ctor();
  672. // With no -regalloc= override, ask the target for a regalloc pass.
  673. return createTargetRegisterAllocator(Optimized);
  674. }
  675. /// Return true if the default global register allocator is in use and
  676. /// has not be overriden on the command line with '-regalloc=...'
  677. bool TargetPassConfig::usingDefaultRegAlloc() const {
  678. return RegAlloc.getNumOccurrences() == 0;
  679. }
  680. /// Add the minimum set of target-independent passes that are required for
  681. /// register allocation. No coalescing or scheduling.
  682. void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
  683. addPass(&PHIEliminationID, false);
  684. addPass(&TwoAddressInstructionPassID, false);
  685. if (RegAllocPass)
  686. addPass(RegAllocPass);
  687. }
  688. /// Add standard target-independent passes that are tightly coupled with
  689. /// optimized register allocation, including coalescing, machine instruction
  690. /// scheduling, and register allocation itself.
  691. void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
  692. addPass(&DetectDeadLanesID, false);
  693. addPass(&ProcessImplicitDefsID, false);
  694. // LiveVariables currently requires pure SSA form.
  695. //
  696. // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
  697. // LiveVariables can be removed completely, and LiveIntervals can be directly
  698. // computed. (We still either need to regenerate kill flags after regalloc, or
  699. // preferably fix the scavenger to not depend on them).
  700. addPass(&LiveVariablesID, false);
  701. // Edge splitting is smarter with machine loop info.
  702. addPass(&MachineLoopInfoID, false);
  703. addPass(&PHIEliminationID, false);
  704. // Eventually, we want to run LiveIntervals before PHI elimination.
  705. if (EarlyLiveIntervals)
  706. addPass(&LiveIntervalsID, false);
  707. addPass(&TwoAddressInstructionPassID, false);
  708. addPass(&RegisterCoalescerID);
  709. // The machine scheduler may accidentally create disconnected components
  710. // when moving subregister definitions around, avoid this by splitting them to
  711. // separate vregs before. Splitting can also improve reg. allocation quality.
  712. addPass(&RenameIndependentSubregsID);
  713. // PreRA instruction scheduling.
  714. addPass(&MachineSchedulerID);
  715. if (RegAllocPass) {
  716. // Add the selected register allocation pass.
  717. addPass(RegAllocPass);
  718. // Allow targets to change the register assignments before rewriting.
  719. addPreRewrite();
  720. // Finally rewrite virtual registers.
  721. addPass(&VirtRegRewriterID);
  722. // Perform stack slot coloring and post-ra machine LICM.
  723. //
  724. // FIXME: Re-enable coloring with register when it's capable of adding
  725. // kill markers.
  726. addPass(&StackSlotColoringID);
  727. // Run post-ra machine LICM to hoist reloads / remats.
  728. //
  729. // FIXME: can this move into MachineLateOptimization?
  730. addPass(&PostRAMachineLICMID);
  731. }
  732. }
  733. //===---------------------------------------------------------------------===//
  734. /// Post RegAlloc Pass Configuration
  735. //===---------------------------------------------------------------------===//
  736. /// Add passes that optimize machine instructions after register allocation.
  737. void TargetPassConfig::addMachineLateOptimization() {
  738. // Branch folding must be run after regalloc and prolog/epilog insertion.
  739. addPass(&BranchFolderPassID);
  740. // Tail duplication.
  741. // Note that duplicating tail just increases code size and degrades
  742. // performance for targets that require Structured Control Flow.
  743. // In addition it can also make CFG irreducible. Thus we disable it.
  744. if (!TM->requiresStructuredCFG())
  745. addPass(&TailDuplicateID);
  746. // Copy propagation.
  747. addPass(&MachineCopyPropagationID);
  748. }
  749. /// Add standard GC passes.
  750. bool TargetPassConfig::addGCPasses() {
  751. addPass(&GCMachineCodeAnalysisID, false);
  752. return true;
  753. }
  754. /// Add standard basic block placement passes.
  755. void TargetPassConfig::addBlockPlacement() {
  756. if (addPass(&MachineBlockPlacementID)) {
  757. // Run a separate pass to collect block placement statistics.
  758. if (EnableBlockPlacementStats)
  759. addPass(&MachineBlockPlacementStatsID);
  760. }
  761. }
  762. //===---------------------------------------------------------------------===//
  763. /// GlobalISel Configuration
  764. //===---------------------------------------------------------------------===//
  765. bool TargetPassConfig::isGlobalISelAbortEnabled() const {
  766. return EnableGlobalISelAbort == 1;
  767. }
  768. bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
  769. return EnableGlobalISelAbort == 2;
  770. }