TargetPassConfig.cpp 42 KB

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