PassManagerBuilder.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
  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. //
  9. // This file defines the PassManagerBuilder class, which is used to set up a
  10. // "standard" optimization sequence suitable for languages like C and C++.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  14. #include "llvm-c/Transforms/PassManagerBuilder.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/BasicAliasAnalysis.h"
  18. #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
  19. #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
  20. #include "llvm/Analysis/GlobalsModRef.h"
  21. #include "llvm/Analysis/InlineCost.h"
  22. #include "llvm/Analysis/Passes.h"
  23. #include "llvm/Analysis/ScopedNoAliasAA.h"
  24. #include "llvm/Analysis/TargetLibraryInfo.h"
  25. #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/LegacyPassManager.h"
  28. #include "llvm/IR/Verifier.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/ManagedStatic.h"
  31. #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
  32. #include "llvm/Transforms/IPO.h"
  33. #include "llvm/Transforms/IPO/Attributor.h"
  34. #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
  35. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  36. #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
  37. #include "llvm/Transforms/InstCombine/InstCombine.h"
  38. #include "llvm/Transforms/Instrumentation.h"
  39. #include "llvm/Transforms/Scalar.h"
  40. #include "llvm/Transforms/Scalar/GVN.h"
  41. #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
  42. #include "llvm/Transforms/Scalar/LICM.h"
  43. #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
  44. #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
  45. #include "llvm/Transforms/Utils.h"
  46. #include "llvm/Transforms/Vectorize.h"
  47. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  48. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  49. #include "llvm/Transforms/Vectorize/VectorCombine.h"
  50. using namespace llvm;
  51. cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::init(false),
  52. cl::Hidden, cl::ZeroOrMore,
  53. cl::desc("Run Partial inlinining pass"));
  54. static cl::opt<bool>
  55. UseGVNAfterVectorization("use-gvn-after-vectorization",
  56. cl::init(false), cl::Hidden,
  57. cl::desc("Run GVN instead of Early CSE after vectorization passes"));
  58. cl::opt<bool> ExtraVectorizerPasses(
  59. "extra-vectorizer-passes", cl::init(false), cl::Hidden,
  60. cl::desc("Run cleanup optimization passes after vectorization."));
  61. static cl::opt<bool>
  62. RunLoopRerolling("reroll-loops", cl::Hidden,
  63. cl::desc("Run the loop rerolling pass"));
  64. cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
  65. cl::desc("Run the NewGVN pass"));
  66. // Experimental option to use CFL-AA
  67. enum class CFLAAType { None, Steensgaard, Andersen, Both };
  68. static cl::opt<::CFLAAType>
  69. UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden,
  70. cl::desc("Enable the new, experimental CFL alias analysis"),
  71. cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"),
  72. clEnumValN(::CFLAAType::Steensgaard, "steens",
  73. "Enable unification-based CFL-AA"),
  74. clEnumValN(::CFLAAType::Andersen, "anders",
  75. "Enable inclusion-based CFL-AA"),
  76. clEnumValN(::CFLAAType::Both, "both",
  77. "Enable both variants of CFL-AA")));
  78. static cl::opt<bool> EnableLoopInterchange(
  79. "enable-loopinterchange", cl::init(false), cl::Hidden,
  80. cl::desc("Enable the new, experimental LoopInterchange Pass"));
  81. cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false),
  82. cl::Hidden,
  83. cl::desc("Enable Unroll And Jam Pass"));
  84. cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
  85. cl::Hidden,
  86. cl::desc("Enable the LoopFlatten Pass"));
  87. static cl::opt<bool>
  88. EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
  89. cl::desc("Enable preparation for ThinLTO."));
  90. static cl::opt<bool>
  91. EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden,
  92. cl::desc("Enable performing ThinLTO."));
  93. cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false),
  94. cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass"));
  95. cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden,
  96. cl::desc("Enable ir outliner pass"));
  97. static cl::opt<bool> UseLoopVersioningLICM(
  98. "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
  99. cl::desc("Enable the experimental Loop Versioning LICM pass"));
  100. cl::opt<bool>
  101. DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
  102. cl::desc("Disable pre-instrumentation inliner"));
  103. cl::opt<int> PreInlineThreshold(
  104. "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
  105. cl::desc("Control the amount of inlining in pre-instrumentation inliner "
  106. "(default = 75)"));
  107. cl::opt<bool>
  108. EnableGVNHoist("enable-gvn-hoist", cl::init(false), cl::ZeroOrMore,
  109. cl::desc("Enable the GVN hoisting pass (default = off)"));
  110. static cl::opt<bool>
  111. DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
  112. cl::Hidden,
  113. cl::desc("Disable shrink-wrap library calls"));
  114. static cl::opt<bool> EnableSimpleLoopUnswitch(
  115. "enable-simple-loop-unswitch", cl::init(false), cl::Hidden,
  116. cl::desc("Enable the simple loop unswitch pass. Also enables independent "
  117. "cleanup passes integrated into the loop pass manager pipeline."));
  118. cl::opt<bool>
  119. EnableGVNSink("enable-gvn-sink", cl::init(false), cl::ZeroOrMore,
  120. cl::desc("Enable the GVN sinking pass (default = off)"));
  121. // This option is used in simplifying testing SampleFDO optimizations for
  122. // profile loading.
  123. cl::opt<bool>
  124. EnableCHR("enable-chr", cl::init(true), cl::Hidden,
  125. cl::desc("Enable control height reduction optimization (CHR)"));
  126. cl::opt<bool> FlattenedProfileUsed(
  127. "flattened-profile-used", cl::init(false), cl::Hidden,
  128. cl::desc("Indicate the sample profile being used is flattened, i.e., "
  129. "no inline hierachy exists in the profile. "));
  130. cl::opt<bool> EnableOrderFileInstrumentation(
  131. "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
  132. cl::desc("Enable order file instrumentation (default = off)"));
  133. cl::opt<bool> EnableMatrix(
  134. "enable-matrix", cl::init(false), cl::Hidden,
  135. cl::desc("Enable lowering of the matrix intrinsics"));
  136. cl::opt<bool> EnableConstraintElimination(
  137. "enable-constraint-elimination", cl::init(false), cl::Hidden,
  138. cl::desc(
  139. "Enable pass to eliminate conditions based on linear constraints."));
  140. cl::opt<AttributorRunOption> AttributorRun(
  141. "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
  142. cl::desc("Enable the attributor inter-procedural deduction pass."),
  143. cl::values(clEnumValN(AttributorRunOption::ALL, "all",
  144. "enable all attributor runs"),
  145. clEnumValN(AttributorRunOption::MODULE, "module",
  146. "enable module-wide attributor runs"),
  147. clEnumValN(AttributorRunOption::CGSCC, "cgscc",
  148. "enable call graph SCC attributor runs"),
  149. clEnumValN(AttributorRunOption::NONE, "none",
  150. "disable attributor runs")));
  151. extern cl::opt<bool> EnableKnowledgeRetention;
  152. PassManagerBuilder::PassManagerBuilder() {
  153. OptLevel = 2;
  154. SizeLevel = 0;
  155. LibraryInfo = nullptr;
  156. Inliner = nullptr;
  157. DisableUnrollLoops = false;
  158. SLPVectorize = false;
  159. LoopVectorize = true;
  160. LoopsInterleaved = true;
  161. RerollLoops = RunLoopRerolling;
  162. NewGVN = RunNewGVN;
  163. LicmMssaOptCap = SetLicmMssaOptCap;
  164. LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
  165. DisableGVNLoadPRE = false;
  166. ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
  167. VerifyInput = false;
  168. VerifyOutput = false;
  169. MergeFunctions = false;
  170. PrepareForLTO = false;
  171. EnablePGOInstrGen = false;
  172. EnablePGOCSInstrGen = false;
  173. EnablePGOCSInstrUse = false;
  174. PGOInstrGen = "";
  175. PGOInstrUse = "";
  176. PGOSampleUse = "";
  177. PrepareForThinLTO = EnablePrepareForThinLTO;
  178. PerformThinLTO = EnablePerformThinLTO;
  179. DivergentTarget = false;
  180. CallGraphProfile = true;
  181. }
  182. PassManagerBuilder::~PassManagerBuilder() {
  183. delete LibraryInfo;
  184. delete Inliner;
  185. }
  186. /// Set of global extensions, automatically added as part of the standard set.
  187. static ManagedStatic<
  188. SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy,
  189. PassManagerBuilder::ExtensionFn,
  190. PassManagerBuilder::GlobalExtensionID>,
  191. 8>>
  192. GlobalExtensions;
  193. static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter;
  194. /// Check if GlobalExtensions is constructed and not empty.
  195. /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger
  196. /// the construction of the object.
  197. static bool GlobalExtensionsNotEmpty() {
  198. return GlobalExtensions.isConstructed() && !GlobalExtensions->empty();
  199. }
  200. PassManagerBuilder::GlobalExtensionID
  201. PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,
  202. PassManagerBuilder::ExtensionFn Fn) {
  203. auto ExtensionID = GlobalExtensionsCounter++;
  204. GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID));
  205. return ExtensionID;
  206. }
  207. void PassManagerBuilder::removeGlobalExtension(
  208. PassManagerBuilder::GlobalExtensionID ExtensionID) {
  209. // RegisterStandardPasses may try to call this function after GlobalExtensions
  210. // has already been destroyed; doing so should not generate an error.
  211. if (!GlobalExtensions.isConstructed())
  212. return;
  213. auto GlobalExtension =
  214. llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) {
  215. return std::get<2>(elem) == ExtensionID;
  216. });
  217. assert(GlobalExtension != GlobalExtensions->end() &&
  218. "The extension ID to be removed should always be valid.");
  219. GlobalExtensions->erase(GlobalExtension);
  220. }
  221. void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
  222. Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
  223. }
  224. void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
  225. legacy::PassManagerBase &PM) const {
  226. if (GlobalExtensionsNotEmpty()) {
  227. for (auto &Ext : *GlobalExtensions) {
  228. if (std::get<0>(Ext) == ETy)
  229. std::get<1>(Ext)(*this, PM);
  230. }
  231. }
  232. for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
  233. if (Extensions[i].first == ETy)
  234. Extensions[i].second(*this, PM);
  235. }
  236. void PassManagerBuilder::addInitialAliasAnalysisPasses(
  237. legacy::PassManagerBase &PM) const {
  238. switch (UseCFLAA) {
  239. case ::CFLAAType::Steensgaard:
  240. PM.add(createCFLSteensAAWrapperPass());
  241. break;
  242. case ::CFLAAType::Andersen:
  243. PM.add(createCFLAndersAAWrapperPass());
  244. break;
  245. case ::CFLAAType::Both:
  246. PM.add(createCFLSteensAAWrapperPass());
  247. PM.add(createCFLAndersAAWrapperPass());
  248. break;
  249. default:
  250. break;
  251. }
  252. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  253. // BasicAliasAnalysis wins if they disagree. This is intended to help
  254. // support "obvious" type-punning idioms.
  255. PM.add(createTypeBasedAAWrapperPass());
  256. PM.add(createScopedNoAliasAAWrapperPass());
  257. }
  258. void PassManagerBuilder::populateFunctionPassManager(
  259. legacy::FunctionPassManager &FPM) {
  260. addExtensionsToPM(EP_EarlyAsPossible, FPM);
  261. FPM.add(createEntryExitInstrumenterPass());
  262. // Add LibraryInfo if we have some.
  263. if (LibraryInfo)
  264. FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  265. // The backends do not handle matrix intrinsics currently.
  266. // Make sure they are also lowered in O0.
  267. // FIXME: A lightweight version of the pass should run in the backend
  268. // pipeline on demand.
  269. if (EnableMatrix && OptLevel == 0)
  270. FPM.add(createLowerMatrixIntrinsicsMinimalPass());
  271. if (OptLevel == 0) return;
  272. addInitialAliasAnalysisPasses(FPM);
  273. FPM.add(createCFGSimplificationPass());
  274. FPM.add(createSROAPass());
  275. FPM.add(createEarlyCSEPass());
  276. FPM.add(createLowerExpectIntrinsicPass());
  277. }
  278. // Do PGO instrumentation generation or use pass as the option specified.
  279. void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM,
  280. bool IsCS = false) {
  281. if (IsCS) {
  282. if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse)
  283. return;
  284. } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty())
  285. return;
  286. // Perform the preinline and cleanup passes for O1 and above.
  287. // We will not do this inline for context sensitive PGO (when IsCS is true).
  288. if (OptLevel > 0 && !DisablePreInliner && PGOSampleUse.empty() && !IsCS) {
  289. // Create preinline pass. We construct an InlineParams object and specify
  290. // the threshold here to avoid the command line options of the regular
  291. // inliner to influence pre-inlining. The only fields of InlineParams we
  292. // care about are DefaultThreshold and HintThreshold.
  293. InlineParams IP;
  294. IP.DefaultThreshold = PreInlineThreshold;
  295. // FIXME: The hint threshold has the same value used by the regular inliner
  296. // when not optimzing for size. This should probably be lowered after
  297. // performance testing.
  298. // Use PreInlineThreshold for both -Os and -Oz. Not running preinliner makes
  299. // the instrumented binary unusably large. Even if PreInlineThreshold is not
  300. // correct thresold for -Oz, it is better than not running preinliner.
  301. IP.HintThreshold = SizeLevel > 0 ? PreInlineThreshold : 325;
  302. MPM.add(createFunctionInliningPass(IP));
  303. MPM.add(createSROAPass());
  304. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  305. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  306. MPM.add(createInstructionCombiningPass()); // Combine silly seq's
  307. addExtensionsToPM(EP_Peephole, MPM);
  308. }
  309. if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) {
  310. MPM.add(createPGOInstrumentationGenLegacyPass(IsCS));
  311. // Add the profile lowering pass.
  312. InstrProfOptions Options;
  313. if (!PGOInstrGen.empty())
  314. Options.InstrProfileOutput = PGOInstrGen;
  315. Options.DoCounterPromotion = true;
  316. Options.UseBFIInPromotion = IsCS;
  317. MPM.add(createLoopRotatePass());
  318. MPM.add(createInstrProfilingLegacyPass(Options, IsCS));
  319. }
  320. if (!PGOInstrUse.empty())
  321. MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS));
  322. // Indirect call promotion that promotes intra-module targets only.
  323. // For ThinLTO this is done earlier due to interactions with globalopt
  324. // for imported functions. We don't run this at -O0.
  325. if (OptLevel > 0 && !IsCS)
  326. MPM.add(
  327. createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
  328. }
  329. void PassManagerBuilder::addFunctionSimplificationPasses(
  330. legacy::PassManagerBase &MPM) {
  331. // Start of function pass.
  332. // Break up aggregate allocas, using SSAUpdater.
  333. assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!");
  334. MPM.add(createSROAPass());
  335. MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies
  336. if (EnableKnowledgeRetention)
  337. MPM.add(createAssumeSimplifyPass());
  338. if (OptLevel > 1) {
  339. if (EnableGVNHoist)
  340. MPM.add(createGVNHoistPass());
  341. if (EnableGVNSink) {
  342. MPM.add(createGVNSinkPass());
  343. MPM.add(createCFGSimplificationPass());
  344. }
  345. }
  346. if (EnableConstraintElimination)
  347. MPM.add(createConstraintEliminationPass());
  348. if (OptLevel > 1) {
  349. // Speculative execution if the target has divergent branches; otherwise nop.
  350. MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
  351. MPM.add(createJumpThreadingPass()); // Thread jumps.
  352. MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
  353. }
  354. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  355. // Combine silly seq's
  356. if (OptLevel > 2)
  357. MPM.add(createAggressiveInstCombinerPass());
  358. MPM.add(createInstructionCombiningPass());
  359. if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
  360. MPM.add(createLibCallsShrinkWrapPass());
  361. addExtensionsToPM(EP_Peephole, MPM);
  362. // Optimize memory intrinsic calls based on the profiled size information.
  363. if (SizeLevel == 0)
  364. MPM.add(createPGOMemOPSizeOptLegacyPass());
  365. // TODO: Investigate the cost/benefit of tail call elimination on debugging.
  366. if (OptLevel > 1)
  367. MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
  368. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  369. MPM.add(createReassociatePass()); // Reassociate expressions
  370. // Begin the loop pass pipeline.
  371. if (EnableSimpleLoopUnswitch) {
  372. // The simple loop unswitch pass relies on separate cleanup passes. Schedule
  373. // them first so when we re-process a loop they run before other loop
  374. // passes.
  375. MPM.add(createLoopInstSimplifyPass());
  376. MPM.add(createLoopSimplifyCFGPass());
  377. }
  378. // Rotate Loop - disable header duplication at -Oz
  379. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO));
  380. // TODO: Investigate promotion cap for O1.
  381. MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  382. if (EnableSimpleLoopUnswitch)
  383. MPM.add(createSimpleLoopUnswitchLegacyPass());
  384. else
  385. MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
  386. // FIXME: We break the loop pass pipeline here in order to do full
  387. // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the
  388. // need for this.
  389. MPM.add(createCFGSimplificationPass());
  390. MPM.add(createInstructionCombiningPass());
  391. // We resume loop passes creating a second loop pipeline here.
  392. if (EnableLoopFlatten) {
  393. MPM.add(createLoopFlattenPass()); // Flatten loops
  394. MPM.add(createLoopSimplifyCFGPass());
  395. }
  396. MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
  397. MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
  398. addExtensionsToPM(EP_LateLoopOptimizations, MPM);
  399. MPM.add(createLoopDeletionPass()); // Delete dead loops
  400. if (EnableLoopInterchange)
  401. MPM.add(createLoopInterchangePass()); // Interchange loops
  402. // Unroll small loops and perform peeling.
  403. MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
  404. ForgetAllSCEVInLoopUnroll));
  405. addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
  406. // This ends the loop pass pipelines.
  407. // Break up allocas that may now be splittable after loop unrolling.
  408. MPM.add(createSROAPass());
  409. if (OptLevel > 1) {
  410. MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
  411. MPM.add(NewGVN ? createNewGVNPass()
  412. : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  413. }
  414. MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
  415. MPM.add(createSCCPPass()); // Constant prop with SCCP
  416. if (EnableConstraintElimination)
  417. MPM.add(createConstraintEliminationPass());
  418. // Delete dead bit computations (instcombine runs after to fold away the dead
  419. // computations, and then ADCE will run later to exploit any new DCE
  420. // opportunities that creates).
  421. MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
  422. // Run instcombine after redundancy elimination to exploit opportunities
  423. // opened up by them.
  424. MPM.add(createInstructionCombiningPass());
  425. addExtensionsToPM(EP_Peephole, MPM);
  426. if (OptLevel > 1) {
  427. MPM.add(createJumpThreadingPass()); // Thread jumps
  428. MPM.add(createCorrelatedValuePropagationPass());
  429. }
  430. MPM.add(createAggressiveDCEPass()); // Delete dead instructions
  431. // TODO: Investigate if this is too expensive at O1.
  432. if (OptLevel > 1) {
  433. MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
  434. MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  435. }
  436. addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
  437. if (RerollLoops)
  438. MPM.add(createLoopRerollPass());
  439. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  440. // Clean up after everything.
  441. MPM.add(createInstructionCombiningPass());
  442. addExtensionsToPM(EP_Peephole, MPM);
  443. if (EnableCHR && OptLevel >= 3 &&
  444. (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen))
  445. MPM.add(createControlHeightReductionLegacyPass());
  446. }
  447. void PassManagerBuilder::populateModulePassManager(
  448. legacy::PassManagerBase &MPM) {
  449. // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link
  450. // is handled separately, so just check this is not the ThinLTO post-link.
  451. bool DefaultOrPreLinkPipeline = !PerformThinLTO;
  452. MPM.add(createAnnotation2MetadataLegacyPass());
  453. if (!PGOSampleUse.empty()) {
  454. MPM.add(createPruneEHPass());
  455. // In ThinLTO mode, when flattened profile is used, all the available
  456. // profile information will be annotated in PreLink phase so there is
  457. // no need to load the profile again in PostLink.
  458. if (!(FlattenedProfileUsed && PerformThinLTO))
  459. MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
  460. }
  461. // Allow forcing function attributes as a debugging and tuning aid.
  462. MPM.add(createForceFunctionAttrsLegacyPass());
  463. // If all optimizations are disabled, just run the always-inline pass and,
  464. // if enabled, the function merging pass.
  465. if (OptLevel == 0) {
  466. addPGOInstrPasses(MPM);
  467. if (Inliner) {
  468. MPM.add(Inliner);
  469. Inliner = nullptr;
  470. }
  471. // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
  472. // creates a CGSCC pass manager, but we don't want to add extensions into
  473. // that pass manager. To prevent this we insert a no-op module pass to reset
  474. // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
  475. // builds. The function merging pass is
  476. if (MergeFunctions)
  477. MPM.add(createMergeFunctionsPass());
  478. else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
  479. MPM.add(createBarrierNoopPass());
  480. if (PerformThinLTO) {
  481. MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
  482. // Drop available_externally and unreferenced globals. This is necessary
  483. // with ThinLTO in order to avoid leaving undefined references to dead
  484. // globals in the object file.
  485. MPM.add(createEliminateAvailableExternallyPass());
  486. MPM.add(createGlobalDCEPass());
  487. }
  488. addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
  489. if (PrepareForLTO || PrepareForThinLTO) {
  490. MPM.add(createCanonicalizeAliasesPass());
  491. // Rename anon globals to be able to export them in the summary.
  492. // This has to be done after we add the extensions to the pass manager
  493. // as there could be passes (e.g. Adddress sanitizer) which introduce
  494. // new unnamed globals.
  495. MPM.add(createNameAnonGlobalPass());
  496. }
  497. MPM.add(createAnnotationRemarksLegacyPass());
  498. return;
  499. }
  500. // Add LibraryInfo if we have some.
  501. if (LibraryInfo)
  502. MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  503. addInitialAliasAnalysisPasses(MPM);
  504. // For ThinLTO there are two passes of indirect call promotion. The
  505. // first is during the compile phase when PerformThinLTO=false and
  506. // intra-module indirect call targets are promoted. The second is during
  507. // the ThinLTO backend when PerformThinLTO=true, when we promote imported
  508. // inter-module indirect calls. For that we perform indirect call promotion
  509. // earlier in the pass pipeline, here before globalopt. Otherwise imported
  510. // available_externally functions look unreferenced and are removed.
  511. if (PerformThinLTO) {
  512. MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
  513. !PGOSampleUse.empty()));
  514. MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
  515. }
  516. // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
  517. // as it will change the CFG too much to make the 2nd profile annotation
  518. // in backend more difficult.
  519. bool PrepareForThinLTOUsingPGOSampleProfile =
  520. PrepareForThinLTO && !PGOSampleUse.empty();
  521. if (PrepareForThinLTOUsingPGOSampleProfile)
  522. DisableUnrollLoops = true;
  523. // Infer attributes about declarations if possible.
  524. MPM.add(createInferFunctionAttrsLegacyPass());
  525. // Infer attributes on declarations, call sites, arguments, etc.
  526. if (AttributorRun & AttributorRunOption::MODULE)
  527. MPM.add(createAttributorLegacyPass());
  528. addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
  529. if (OptLevel > 2)
  530. MPM.add(createCallSiteSplittingPass());
  531. MPM.add(createIPSCCPPass()); // IP SCCP
  532. MPM.add(createCalledValuePropagationPass());
  533. MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
  534. // Promote any localized global vars.
  535. MPM.add(createPromoteMemoryToRegisterPass());
  536. MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
  537. MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
  538. addExtensionsToPM(EP_Peephole, MPM);
  539. MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
  540. // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
  541. // call promotion as it will change the CFG too much to make the 2nd
  542. // profile annotation in backend more difficult.
  543. // PGO instrumentation is added during the compile phase for ThinLTO, do
  544. // not run it a second time
  545. if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile)
  546. addPGOInstrPasses(MPM);
  547. // Create profile COMDAT variables. Lld linker wants to see all variables
  548. // before the LTO/ThinLTO link since it needs to resolve symbols/comdats.
  549. if (!PerformThinLTO && EnablePGOCSInstrGen)
  550. MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen));
  551. // We add a module alias analysis pass here. In part due to bugs in the
  552. // analysis infrastructure this "works" in that the analysis stays alive
  553. // for the entire SCC pass run below.
  554. MPM.add(createGlobalsAAWrapperPass());
  555. // Start of CallGraph SCC passes.
  556. MPM.add(createPruneEHPass()); // Remove dead EH info
  557. bool RunInliner = false;
  558. if (Inliner) {
  559. MPM.add(Inliner);
  560. Inliner = nullptr;
  561. RunInliner = true;
  562. }
  563. // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
  564. if (AttributorRun & AttributorRunOption::CGSCC)
  565. MPM.add(createAttributorCGSCCLegacyPass());
  566. // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
  567. // there are no OpenMP runtime calls present in the module.
  568. if (OptLevel > 1)
  569. MPM.add(createOpenMPOptLegacyPass());
  570. MPM.add(createPostOrderFunctionAttrsLegacyPass());
  571. if (OptLevel > 2)
  572. MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
  573. addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
  574. addFunctionSimplificationPasses(MPM);
  575. // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
  576. // pass manager that we are specifically trying to avoid. To prevent this
  577. // we must insert a no-op module pass to reset the pass manager.
  578. MPM.add(createBarrierNoopPass());
  579. if (RunPartialInlining)
  580. MPM.add(createPartialInliningPass());
  581. if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO)
  582. // Remove avail extern fns and globals definitions if we aren't
  583. // compiling an object file for later LTO. For LTO we want to preserve
  584. // these so they are eligible for inlining at link-time. Note if they
  585. // are unreferenced they will be removed by GlobalDCE later, so
  586. // this only impacts referenced available externally globals.
  587. // Eventually they will be suppressed during codegen, but eliminating
  588. // here enables more opportunity for GlobalDCE as it may make
  589. // globals referenced by available external functions dead
  590. // and saves running remaining passes on the eliminated functions.
  591. MPM.add(createEliminateAvailableExternallyPass());
  592. // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass
  593. // for LTO and ThinLTO -- The actual pass will be called after all inlines
  594. // are performed.
  595. // Need to do this after COMDAT variables have been eliminated,
  596. // (i.e. after EliminateAvailableExternallyPass).
  597. if (!(PrepareForLTO || PrepareForThinLTO))
  598. addPGOInstrPasses(MPM, /* IsCS */ true);
  599. if (EnableOrderFileInstrumentation)
  600. MPM.add(createInstrOrderFilePass());
  601. MPM.add(createReversePostOrderFunctionAttrsPass());
  602. // The inliner performs some kind of dead code elimination as it goes,
  603. // but there are cases that are not really caught by it. We might
  604. // at some point consider teaching the inliner about them, but it
  605. // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
  606. // benefits generally outweight the cost, making the whole pipeline
  607. // faster.
  608. if (RunInliner) {
  609. MPM.add(createGlobalOptimizerPass());
  610. MPM.add(createGlobalDCEPass());
  611. }
  612. // If we are planning to perform ThinLTO later, let's not bloat the code with
  613. // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
  614. // during ThinLTO and perform the rest of the optimizations afterward.
  615. if (PrepareForThinLTO) {
  616. // Ensure we perform any last passes, but do so before renaming anonymous
  617. // globals in case the passes add any.
  618. addExtensionsToPM(EP_OptimizerLast, MPM);
  619. MPM.add(createCanonicalizeAliasesPass());
  620. // Rename anon globals to be able to export them in the summary.
  621. MPM.add(createNameAnonGlobalPass());
  622. return;
  623. }
  624. if (PerformThinLTO)
  625. // Optimize globals now when performing ThinLTO, this enables more
  626. // optimizations later.
  627. MPM.add(createGlobalOptimizerPass());
  628. // Scheduling LoopVersioningLICM when inlining is over, because after that
  629. // we may see more accurate aliasing. Reason to run this late is that too
  630. // early versioning may prevent further inlining due to increase of code
  631. // size. By placing it just after inlining other optimizations which runs
  632. // later might get benefit of no-alias assumption in clone loop.
  633. if (UseLoopVersioningLICM) {
  634. MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM
  635. MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  636. }
  637. // We add a fresh GlobalsModRef run at this point. This is particularly
  638. // useful as the above will have inlined, DCE'ed, and function-attr
  639. // propagated everything. We should at this point have a reasonably minimal
  640. // and richly annotated call graph. By computing aliasing and mod/ref
  641. // information for all local globals here, the late loop passes and notably
  642. // the vectorizer will be able to use them to help recognize vectorizable
  643. // memory operations.
  644. //
  645. // Note that this relies on a bug in the pass manager which preserves
  646. // a module analysis into a function pass pipeline (and throughout it) so
  647. // long as the first function pass doesn't invalidate the module analysis.
  648. // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
  649. // this to work. Fortunately, it is trivial to preserve AliasAnalysis
  650. // (doing nothing preserves it as it is required to be conservatively
  651. // correct in the face of IR changes).
  652. MPM.add(createGlobalsAAWrapperPass());
  653. MPM.add(createFloat2IntPass());
  654. MPM.add(createLowerConstantIntrinsicsPass());
  655. if (EnableMatrix) {
  656. MPM.add(createLowerMatrixIntrinsicsPass());
  657. // CSE the pointer arithmetic of the column vectors. This allows alias
  658. // analysis to establish no-aliasing between loads and stores of different
  659. // columns of the same matrix.
  660. MPM.add(createEarlyCSEPass(false));
  661. }
  662. addExtensionsToPM(EP_VectorizerStart, MPM);
  663. // Re-rotate loops in all our loop nests. These may have fallout out of
  664. // rotated form due to GVN or other transformations, and the vectorizer relies
  665. // on the rotated form. Disable header duplication at -Oz.
  666. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO));
  667. // Distribute loops to allow partial vectorization. I.e. isolate dependences
  668. // into separate loop that would otherwise inhibit vectorization. This is
  669. // currently only performed for loops marked with the metadata
  670. // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
  671. MPM.add(createLoopDistributePass());
  672. MPM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize));
  673. // Eliminate loads by forwarding stores from the previous iteration to loads
  674. // of the current iteration.
  675. MPM.add(createLoopLoadEliminationPass());
  676. // FIXME: Because of #pragma vectorize enable, the passes below are always
  677. // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
  678. // on -O1 and no #pragma is found). Would be good to have these two passes
  679. // as function calls, so that we can only pass them when the vectorizer
  680. // changed the code.
  681. MPM.add(createInstructionCombiningPass());
  682. if (OptLevel > 1 && ExtraVectorizerPasses) {
  683. // At higher optimization levels, try to clean up any runtime overlap and
  684. // alignment checks inserted by the vectorizer. We want to track correllated
  685. // runtime checks for two inner loops in the same outer loop, fold any
  686. // common computations, hoist loop-invariant aspects out of any outer loop,
  687. // and unswitch the runtime checks if possible. Once hoisted, we may have
  688. // dead (or speculatable) control flows or more combining opportunities.
  689. MPM.add(createEarlyCSEPass());
  690. MPM.add(createCorrelatedValuePropagationPass());
  691. MPM.add(createInstructionCombiningPass());
  692. MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  693. MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
  694. MPM.add(createCFGSimplificationPass());
  695. MPM.add(createInstructionCombiningPass());
  696. }
  697. // Cleanup after loop vectorization, etc. Simplification passes like CVP and
  698. // GVN, loop transforms, and others have already run, so it's now better to
  699. // convert to more optimized IR using more aggressive simplify CFG options.
  700. // The extra sinking transform can create larger basic blocks, so do this
  701. // before SLP vectorization.
  702. // FIXME: study whether hoisting and/or sinking of common instructions should
  703. // be delayed until after SLP vectorizer.
  704. MPM.add(createCFGSimplificationPass(SimplifyCFGOptions()
  705. .forwardSwitchCondToPhi(true)
  706. .convertSwitchToLookupTable(true)
  707. .needCanonicalLoops(false)
  708. .hoistCommonInsts(true)
  709. .sinkCommonInsts(true)));
  710. if (SLPVectorize) {
  711. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  712. if (OptLevel > 1 && ExtraVectorizerPasses) {
  713. MPM.add(createEarlyCSEPass());
  714. }
  715. }
  716. // Enhance/cleanup vector code.
  717. MPM.add(createVectorCombinePass());
  718. addExtensionsToPM(EP_Peephole, MPM);
  719. MPM.add(createInstructionCombiningPass());
  720. if (EnableUnrollAndJam && !DisableUnrollLoops) {
  721. // Unroll and Jam. We do this before unroll but need to be in a separate
  722. // loop pass manager in order for the outer loop to be processed by
  723. // unroll and jam before the inner loop is unrolled.
  724. MPM.add(createLoopUnrollAndJamPass(OptLevel));
  725. }
  726. // Unroll small loops
  727. MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
  728. ForgetAllSCEVInLoopUnroll));
  729. if (!DisableUnrollLoops) {
  730. // LoopUnroll may generate some redundency to cleanup.
  731. MPM.add(createInstructionCombiningPass());
  732. // Runtime unrolling will introduce runtime check in loop prologue. If the
  733. // unrolled loop is a inner loop, then the prologue will be inside the
  734. // outer loop. LICM pass can help to promote the runtime check out if the
  735. // checked value is loop invariant.
  736. MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  737. }
  738. MPM.add(createWarnMissedTransformationsPass());
  739. // After vectorization and unrolling, assume intrinsics may tell us more
  740. // about pointer alignments.
  741. MPM.add(createAlignmentFromAssumptionsPass());
  742. // FIXME: We shouldn't bother with this anymore.
  743. MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
  744. // GlobalOpt already deletes dead functions and globals, at -O2 try a
  745. // late pass of GlobalDCE. It is capable of deleting dead cycles.
  746. if (OptLevel > 1) {
  747. MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
  748. MPM.add(createConstantMergePass()); // Merge dup global constants
  749. }
  750. // See comment in the new PM for justification of scheduling splitting at
  751. // this stage (\ref buildModuleSimplificationPipeline).
  752. if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO))
  753. MPM.add(createHotColdSplittingPass());
  754. if (EnableIROutliner)
  755. MPM.add(createIROutlinerPass());
  756. if (MergeFunctions)
  757. MPM.add(createMergeFunctionsPass());
  758. // Add Module flag "CG Profile" based on Branch Frequency Information.
  759. if (CallGraphProfile)
  760. MPM.add(createCGProfileLegacyPass());
  761. // LoopSink pass sinks instructions hoisted by LICM, which serves as a
  762. // canonicalization pass that enables other optimizations. As a result,
  763. // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
  764. // result too early.
  765. MPM.add(createLoopSinkPass());
  766. // Get rid of LCSSA nodes.
  767. MPM.add(createInstSimplifyLegacyPass());
  768. // This hoists/decomposes div/rem ops. It should run after other sink/hoist
  769. // passes to avoid re-sinking, but before SimplifyCFG because it can allow
  770. // flattening of blocks.
  771. MPM.add(createDivRemPairsPass());
  772. // LoopSink (and other loop passes since the last simplifyCFG) might have
  773. // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
  774. MPM.add(createCFGSimplificationPass());
  775. addExtensionsToPM(EP_OptimizerLast, MPM);
  776. if (PrepareForLTO) {
  777. MPM.add(createCanonicalizeAliasesPass());
  778. // Rename anon globals to be able to handle them in the summary
  779. MPM.add(createNameAnonGlobalPass());
  780. }
  781. MPM.add(createAnnotationRemarksLegacyPass());
  782. }
  783. void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
  784. // Load sample profile before running the LTO optimization pipeline.
  785. if (!PGOSampleUse.empty()) {
  786. PM.add(createPruneEHPass());
  787. PM.add(createSampleProfileLoaderPass(PGOSampleUse));
  788. }
  789. // Remove unused virtual tables to improve the quality of code generated by
  790. // whole-program devirtualization and bitset lowering.
  791. PM.add(createGlobalDCEPass());
  792. // Provide AliasAnalysis services for optimizations.
  793. addInitialAliasAnalysisPasses(PM);
  794. // Allow forcing function attributes as a debugging and tuning aid.
  795. PM.add(createForceFunctionAttrsLegacyPass());
  796. // Infer attributes about declarations if possible.
  797. PM.add(createInferFunctionAttrsLegacyPass());
  798. if (OptLevel > 1) {
  799. // Split call-site with more constrained arguments.
  800. PM.add(createCallSiteSplittingPass());
  801. // Indirect call promotion. This should promote all the targets that are
  802. // left by the earlier promotion pass that promotes intra-module targets.
  803. // This two-step promotion is to save the compile time. For LTO, it should
  804. // produce the same result as if we only do promotion here.
  805. PM.add(
  806. createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
  807. // Propagate constants at call sites into the functions they call. This
  808. // opens opportunities for globalopt (and inlining) by substituting function
  809. // pointers passed as arguments to direct uses of functions.
  810. PM.add(createIPSCCPPass());
  811. // Attach metadata to indirect call sites indicating the set of functions
  812. // they may target at run-time. This should follow IPSCCP.
  813. PM.add(createCalledValuePropagationPass());
  814. // Infer attributes on declarations, call sites, arguments, etc.
  815. if (AttributorRun & AttributorRunOption::MODULE)
  816. PM.add(createAttributorLegacyPass());
  817. }
  818. // Infer attributes about definitions. The readnone attribute in particular is
  819. // required for virtual constant propagation.
  820. PM.add(createPostOrderFunctionAttrsLegacyPass());
  821. PM.add(createReversePostOrderFunctionAttrsPass());
  822. // Split globals using inrange annotations on GEP indices. This can help
  823. // improve the quality of generated code when virtual constant propagation or
  824. // control flow integrity are enabled.
  825. PM.add(createGlobalSplitPass());
  826. // Apply whole-program devirtualization and virtual constant propagation.
  827. PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
  828. // That's all we need at opt level 1.
  829. if (OptLevel == 1)
  830. return;
  831. // Now that we internalized some globals, see if we can hack on them!
  832. PM.add(createGlobalOptimizerPass());
  833. // Promote any localized global vars.
  834. PM.add(createPromoteMemoryToRegisterPass());
  835. // Linking modules together can lead to duplicated global constants, only
  836. // keep one copy of each constant.
  837. PM.add(createConstantMergePass());
  838. // Remove unused arguments from functions.
  839. PM.add(createDeadArgEliminationPass());
  840. // Reduce the code after globalopt and ipsccp. Both can open up significant
  841. // simplification opportunities, and both can propagate functions through
  842. // function pointers. When this happens, we often have to resolve varargs
  843. // calls, etc, so let instcombine do this.
  844. if (OptLevel > 2)
  845. PM.add(createAggressiveInstCombinerPass());
  846. PM.add(createInstructionCombiningPass());
  847. addExtensionsToPM(EP_Peephole, PM);
  848. // Inline small functions
  849. bool RunInliner = Inliner;
  850. if (RunInliner) {
  851. PM.add(Inliner);
  852. Inliner = nullptr;
  853. }
  854. PM.add(createPruneEHPass()); // Remove dead EH info.
  855. // CSFDO instrumentation and use pass.
  856. addPGOInstrPasses(PM, /* IsCS */ true);
  857. // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
  858. if (AttributorRun & AttributorRunOption::CGSCC)
  859. PM.add(createAttributorCGSCCLegacyPass());
  860. // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
  861. // there are no OpenMP runtime calls present in the module.
  862. if (OptLevel > 1)
  863. PM.add(createOpenMPOptLegacyPass());
  864. // Optimize globals again if we ran the inliner.
  865. if (RunInliner)
  866. PM.add(createGlobalOptimizerPass());
  867. PM.add(createGlobalDCEPass()); // Remove dead functions.
  868. // If we didn't decide to inline a function, check to see if we can
  869. // transform it to pass arguments by value instead of by reference.
  870. PM.add(createArgumentPromotionPass());
  871. // The IPO passes may leave cruft around. Clean up after them.
  872. PM.add(createInstructionCombiningPass());
  873. addExtensionsToPM(EP_Peephole, PM);
  874. PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
  875. // Break up allocas
  876. PM.add(createSROAPass());
  877. // LTO provides additional opportunities for tailcall elimination due to
  878. // link-time inlining, and visibility of nocapture attribute.
  879. if (OptLevel > 1)
  880. PM.add(createTailCallEliminationPass());
  881. // Infer attributes on declarations, call sites, arguments, etc.
  882. PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
  883. // Run a few AA driven optimizations here and now, to cleanup the code.
  884. PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
  885. PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
  886. PM.add(NewGVN ? createNewGVNPass()
  887. : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
  888. PM.add(createMemCpyOptPass()); // Remove dead memcpys.
  889. // Nuke dead stores.
  890. PM.add(createDeadStoreEliminationPass());
  891. PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
  892. // More loops are countable; try to optimize them.
  893. if (EnableLoopFlatten)
  894. PM.add(createLoopFlattenPass());
  895. PM.add(createIndVarSimplifyPass());
  896. PM.add(createLoopDeletionPass());
  897. if (EnableLoopInterchange)
  898. PM.add(createLoopInterchangePass());
  899. if (EnableConstraintElimination)
  900. PM.add(createConstraintEliminationPass());
  901. // Unroll small loops and perform peeling.
  902. PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
  903. ForgetAllSCEVInLoopUnroll));
  904. PM.add(createLoopDistributePass());
  905. PM.add(createLoopVectorizePass(true, !LoopVectorize));
  906. // The vectorizer may have significantly shortened a loop body; unroll again.
  907. PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
  908. ForgetAllSCEVInLoopUnroll));
  909. PM.add(createWarnMissedTransformationsPass());
  910. // Now that we've optimized loops (in particular loop induction variables),
  911. // we may have exposed more scalar opportunities. Run parts of the scalar
  912. // optimizer again at this point.
  913. PM.add(createInstructionCombiningPass()); // Initial cleanup
  914. PM.add(createCFGSimplificationPass(SimplifyCFGOptions() // if-convert
  915. .hoistCommonInsts(true)));
  916. PM.add(createSCCPPass()); // Propagate exposed constants
  917. PM.add(createInstructionCombiningPass()); // Clean up again
  918. PM.add(createBitTrackingDCEPass());
  919. // More scalar chains could be vectorized due to more alias information
  920. if (SLPVectorize)
  921. PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  922. PM.add(createVectorCombinePass()); // Clean up partial vectorization.
  923. // After vectorization, assume intrinsics may tell us more about pointer
  924. // alignments.
  925. PM.add(createAlignmentFromAssumptionsPass());
  926. // Cleanup and simplify the code after the scalar optimizations.
  927. PM.add(createInstructionCombiningPass());
  928. addExtensionsToPM(EP_Peephole, PM);
  929. PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
  930. }
  931. void PassManagerBuilder::addLateLTOOptimizationPasses(
  932. legacy::PassManagerBase &PM) {
  933. // See comment in the new PM for justification of scheduling splitting at
  934. // this stage (\ref buildLTODefaultPipeline).
  935. if (EnableHotColdSplit)
  936. PM.add(createHotColdSplittingPass());
  937. // Delete basic blocks, which optimization passes may have killed.
  938. PM.add(
  939. createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true)));
  940. // Drop bodies of available externally objects to improve GlobalDCE.
  941. PM.add(createEliminateAvailableExternallyPass());
  942. // Now that we have optimized the program, discard unreachable functions.
  943. PM.add(createGlobalDCEPass());
  944. // FIXME: this is profitable (for compiler time) to do at -O0 too, but
  945. // currently it damages debug info.
  946. if (MergeFunctions)
  947. PM.add(createMergeFunctionsPass());
  948. }
  949. void PassManagerBuilder::populateThinLTOPassManager(
  950. legacy::PassManagerBase &PM) {
  951. PerformThinLTO = true;
  952. if (LibraryInfo)
  953. PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  954. if (VerifyInput)
  955. PM.add(createVerifierPass());
  956. if (ImportSummary) {
  957. // This pass imports type identifier resolutions for whole-program
  958. // devirtualization and CFI. It must run early because other passes may
  959. // disturb the specific instruction patterns that these passes look for,
  960. // creating dependencies on resolutions that may not appear in the summary.
  961. //
  962. // For example, GVN may transform the pattern assume(type.test) appearing in
  963. // two basic blocks into assume(phi(type.test, type.test)), which would
  964. // transform a dependency on a WPD resolution into a dependency on a type
  965. // identifier resolution for CFI.
  966. //
  967. // Also, WPD has access to more precise information than ICP and can
  968. // devirtualize more effectively, so it should operate on the IR first.
  969. PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
  970. PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
  971. }
  972. populateModulePassManager(PM);
  973. if (VerifyOutput)
  974. PM.add(createVerifierPass());
  975. PerformThinLTO = false;
  976. }
  977. void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
  978. if (LibraryInfo)
  979. PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  980. if (VerifyInput)
  981. PM.add(createVerifierPass());
  982. addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM);
  983. if (OptLevel != 0)
  984. addLTOOptimizationPasses(PM);
  985. else {
  986. // The whole-program-devirt pass needs to run at -O0 because only it knows
  987. // about the llvm.type.checked.load intrinsic: it needs to both lower the
  988. // intrinsic itself and handle it in the summary.
  989. PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
  990. }
  991. // Create a function that performs CFI checks for cross-DSO calls with targets
  992. // in the current module.
  993. PM.add(createCrossDSOCFIPass());
  994. // Lower type metadata and the type.test intrinsic. This pass supports Clang's
  995. // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
  996. // link time if CFI is enabled. The pass does nothing if CFI is disabled.
  997. PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
  998. // Run a second time to clean up any type tests left behind by WPD for use
  999. // in ICP (which is performed earlier than this in the regular LTO pipeline).
  1000. PM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
  1001. if (OptLevel != 0)
  1002. addLateLTOOptimizationPasses(PM);
  1003. addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM);
  1004. PM.add(createAnnotationRemarksLegacyPass());
  1005. if (VerifyOutput)
  1006. PM.add(createVerifierPass());
  1007. }
  1008. LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
  1009. PassManagerBuilder *PMB = new PassManagerBuilder();
  1010. return wrap(PMB);
  1011. }
  1012. void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
  1013. PassManagerBuilder *Builder = unwrap(PMB);
  1014. delete Builder;
  1015. }
  1016. void
  1017. LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
  1018. unsigned OptLevel) {
  1019. PassManagerBuilder *Builder = unwrap(PMB);
  1020. Builder->OptLevel = OptLevel;
  1021. }
  1022. void
  1023. LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
  1024. unsigned SizeLevel) {
  1025. PassManagerBuilder *Builder = unwrap(PMB);
  1026. Builder->SizeLevel = SizeLevel;
  1027. }
  1028. void
  1029. LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
  1030. LLVMBool Value) {
  1031. // NOTE: The DisableUnitAtATime switch has been removed.
  1032. }
  1033. void
  1034. LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
  1035. LLVMBool Value) {
  1036. PassManagerBuilder *Builder = unwrap(PMB);
  1037. Builder->DisableUnrollLoops = Value;
  1038. }
  1039. void
  1040. LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
  1041. LLVMBool Value) {
  1042. // NOTE: The simplify-libcalls pass has been removed.
  1043. }
  1044. void
  1045. LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
  1046. unsigned Threshold) {
  1047. PassManagerBuilder *Builder = unwrap(PMB);
  1048. Builder->Inliner = createFunctionInliningPass(Threshold);
  1049. }
  1050. void
  1051. LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
  1052. LLVMPassManagerRef PM) {
  1053. PassManagerBuilder *Builder = unwrap(PMB);
  1054. legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
  1055. Builder->populateFunctionPassManager(*FPM);
  1056. }
  1057. void
  1058. LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
  1059. LLVMPassManagerRef PM) {
  1060. PassManagerBuilder *Builder = unwrap(PMB);
  1061. legacy::PassManagerBase *MPM = unwrap(PM);
  1062. Builder->populateModulePassManager(*MPM);
  1063. }
  1064. void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
  1065. LLVMPassManagerRef PM,
  1066. LLVMBool Internalize,
  1067. LLVMBool RunInliner) {
  1068. PassManagerBuilder *Builder = unwrap(PMB);
  1069. legacy::PassManagerBase *LPM = unwrap(PM);
  1070. // A small backwards compatibility hack. populateLTOPassManager used to take
  1071. // an RunInliner option.
  1072. if (RunInliner && !Builder->Inliner)
  1073. Builder->Inliner = createFunctionInliningPass();
  1074. Builder->populateLTOPassManager(*LPM);
  1075. }