PassManagerBuilder.cpp 54 KB

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