PassManagerBuilder.cpp 45 KB

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