PassManagerBuilder.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the PassManagerBuilder class, which is used to set up a
  11. // "standard" optimization sequence suitable for languages like C and C++.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  15. #include "llvm-c/Transforms/PassManagerBuilder.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/Passes.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/IR/Verifier.h"
  20. #include "llvm/IR/LegacyPassManager.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/ManagedStatic.h"
  23. #include "llvm/Analysis/TargetLibraryInfo.h"
  24. #include "llvm/Target/TargetMachine.h"
  25. #include "llvm/Transforms/IPO.h"
  26. #include "llvm/Transforms/Scalar.h"
  27. #include "llvm/Transforms/Vectorize.h"
  28. #include "dxc/HLSL/DxilGenerationPass.h" // HLSL Change
  29. #include "dxc/HLSL/HLMatrixLowerPass.h" // HLSL Change
  30. #include "dxc/HLSL/ComputeViewIdState.h" // HLSL Change
  31. using namespace llvm;
  32. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  33. static cl::opt<bool>
  34. RunLoopVectorization("vectorize-loops", cl::Hidden,
  35. cl::desc("Run the Loop vectorization passes"));
  36. static cl::opt<bool>
  37. RunSLPVectorization("vectorize-slp", cl::Hidden,
  38. cl::desc("Run the SLP vectorization passes"));
  39. static cl::opt<bool>
  40. RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
  41. cl::desc("Run the BB vectorization passes"));
  42. static cl::opt<bool>
  43. UseGVNAfterVectorization("use-gvn-after-vectorization",
  44. cl::init(false), cl::Hidden,
  45. cl::desc("Run GVN instead of Early CSE after vectorization passes"));
  46. static cl::opt<bool> ExtraVectorizerPasses(
  47. "extra-vectorizer-passes", cl::init(false), cl::Hidden,
  48. cl::desc("Run cleanup optimization passes after vectorization."));
  49. static cl::opt<bool> UseNewSROA("use-new-sroa",
  50. cl::init(true), cl::Hidden,
  51. cl::desc("Enable the new, experimental SROA pass"));
  52. static cl::opt<bool>
  53. RunLoopRerolling("reroll-loops", cl::Hidden,
  54. cl::desc("Run the loop rerolling pass"));
  55. static cl::opt<bool>
  56. RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
  57. cl::desc("Run the float2int (float demotion) pass"));
  58. static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
  59. cl::Hidden,
  60. cl::desc("Run the load combining pass"));
  61. static cl::opt<bool>
  62. RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
  63. cl::init(true), cl::Hidden,
  64. cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
  65. "vectorizer instead of before"));
  66. static cl::opt<bool> UseCFLAA("use-cfl-aa",
  67. cl::init(false), cl::Hidden,
  68. cl::desc("Enable the new, experimental CFL alias analysis"));
  69. static cl::opt<bool>
  70. EnableMLSM("mlsm", cl::init(true), cl::Hidden,
  71. cl::desc("Enable motion of merged load and store"));
  72. static cl::opt<bool> EnableLoopInterchange(
  73. "enable-loopinterchange", cl::init(false), cl::Hidden,
  74. cl::desc("Enable the new, experimental LoopInterchange Pass"));
  75. static cl::opt<bool> EnableLoopDistribute(
  76. "enable-loop-distribute", cl::init(false), cl::Hidden,
  77. cl::desc("Enable the new, experimental LoopDistribution Pass"));
  78. #else
  79. // Don't declare the 'false' counterparts - simply avoid altogether.
  80. static const bool UseNewSROA = true;
  81. static const bool RunLoopRerolling = false;
  82. static const bool RunFloat2Int = true;
  83. static const bool RunLoadCombine = false;
  84. static const bool RunSLPAfterLoopVectorization = true;
  85. static const bool UseCFLAA = false;
  86. static const bool EnableMLSM = true;
  87. static const bool EnableLoopInterchange = false;
  88. static const bool EnableLoopDistribute = false;
  89. #endif // HLSL Change - don't build vectorization passes
  90. PassManagerBuilder::PassManagerBuilder() {
  91. OptLevel = 2;
  92. SizeLevel = 0;
  93. LibraryInfo = nullptr;
  94. Inliner = nullptr;
  95. DisableUnitAtATime = false;
  96. DisableUnrollLoops = false;
  97. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  98. BBVectorize = RunBBVectorization;
  99. SLPVectorize = RunSLPVectorization;
  100. LoopVectorize = RunLoopVectorization;
  101. #else
  102. BBVectorize = SLPVectorize = LoopVectorize = false;
  103. #endif
  104. RerollLoops = RunLoopRerolling;
  105. LoadCombine = RunLoadCombine;
  106. DisableGVNLoadPRE = false;
  107. VerifyInput = false;
  108. VerifyOutput = false;
  109. MergeFunctions = false;
  110. PrepareForLTO = false;
  111. }
  112. PassManagerBuilder::~PassManagerBuilder() {
  113. delete LibraryInfo;
  114. delete Inliner;
  115. }
  116. #if 0 // HLSL Change Starts - no global extensions
  117. /// Set of global extensions, automatically added as part of the standard set.
  118. static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
  119. PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
  120. #endif // HLSL Change Ends
  121. #if 0 // HLSL Change Starts - no global extensions
  122. void PassManagerBuilder::addGlobalExtension(
  123. PassManagerBuilder::ExtensionPointTy Ty,
  124. PassManagerBuilder::ExtensionFn Fn) {
  125. GlobalExtensions->push_back(std::make_pair(Ty, Fn));
  126. }
  127. #endif // HLSL Change Ends
  128. void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
  129. Extensions.push_back(std::make_pair(Ty, Fn));
  130. }
  131. void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
  132. legacy::PassManagerBase &PM) const {
  133. #if 0 // HLSL Change Starts - no global extensions
  134. for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
  135. if ((*GlobalExtensions)[i].first == ETy)
  136. (*GlobalExtensions)[i].second(*this, PM);
  137. for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
  138. if (Extensions[i].first == ETy)
  139. Extensions[i].second(*this, PM);
  140. #endif // HLSL Change Ends
  141. }
  142. void PassManagerBuilder::addInitialAliasAnalysisPasses(
  143. legacy::PassManagerBase &PM) const {
  144. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  145. // BasicAliasAnalysis wins if they disagree. This is intended to help
  146. // support "obvious" type-punning idioms.
  147. if (UseCFLAA)
  148. PM.add(createCFLAliasAnalysisPass());
  149. PM.add(createTypeBasedAliasAnalysisPass());
  150. PM.add(createScopedNoAliasAAPass());
  151. PM.add(createBasicAliasAnalysisPass());
  152. }
  153. void PassManagerBuilder::populateFunctionPassManager(
  154. legacy::FunctionPassManager &FPM) {
  155. addExtensionsToPM(EP_EarlyAsPossible, FPM);
  156. // Add LibraryInfo if we have some.
  157. if (LibraryInfo)
  158. FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  159. if (OptLevel == 0) return;
  160. addInitialAliasAnalysisPasses(FPM);
  161. FPM.add(createCFGSimplificationPass());
  162. // HLSL Change - don't run SROA.
  163. // HLSL uses special SROA added in addHLSLPasses.
  164. if (HLSLHighLevel) // HLSL Change
  165. if (UseNewSROA)
  166. FPM.add(createSROAPass());
  167. else
  168. FPM.add(createScalarReplAggregatesPass());
  169. // HLSL Change. FPM.add(createEarlyCSEPass());
  170. FPM.add(createLowerExpectIntrinsicPass());
  171. }
  172. // HLSL Change Starts
  173. static void addHLSLPasses(bool HLSLHighLevel, bool NoOpt, hlsl::HLSLExtensionsCodegenHelper *ExtHelper, legacy::PassManagerBase &MPM) {
  174. // Don't do any lowering if we're targeting high-level.
  175. if (HLSLHighLevel) {
  176. MPM.add(createHLEmitMetadataPass());
  177. return;
  178. }
  179. if (!NoOpt) {
  180. MPM.add(createHLDeadFunctionEliminationPass());
  181. }
  182. // Split struct and array of parameter.
  183. MPM.add(createSROA_Parameter_HLSL());
  184. // Split struct.
  185. MPM.add(createScalarReplAggregatesHLSLPass(/*UseDomTree*/ true,
  186. /*Promote*/ !NoOpt));
  187. MPM.add(createHLMatrixLowerPass());
  188. MPM.add(createResourceToHandlePass());
  189. // DCE should after SROA to remove unused element.
  190. MPM.add(createDeadCodeEliminationPass());
  191. MPM.add(createGlobalDCEPass());
  192. if (NoOpt) {
  193. // If not run mem2reg, try to promote allocas used by EvalOperations.
  194. // Do this before change vector to array.
  195. MPM.add(createDxilLegalizeEvalOperationsPass());
  196. }
  197. // Change dynamic indexing vector to array.
  198. MPM.add(createDynamicIndexingVectorToArrayPass(NoOpt));
  199. if (!NoOpt) {
  200. MPM.add(createLowerStaticGlobalIntoAlloca());
  201. // mem2reg
  202. MPM.add(createPromoteMemoryToRegisterPass());
  203. }
  204. MPM.add(createSimplifyInstPass());
  205. MPM.add(createCFGSimplificationPass());
  206. MPM.add(createDxilLegalizeResourceUsePass());
  207. MPM.add(createDxilLegalizeStaticResourceUsePass());
  208. MPM.add(createDxilGenerationPass(NoOpt, ExtHelper));
  209. MPM.add(createDxilLoadMetadataPass()); // Ensure DxilModule is loaded for optimizations.
  210. MPM.add(createSimplifyInstPass());
  211. // Propagate precise attribute.
  212. MPM.add(createDxilPrecisePropagatePass());
  213. // scalarize vector to scalar
  214. MPM.add(createScalarizerPass());
  215. MPM.add(createSimplifyInstPass());
  216. MPM.add(createCFGSimplificationPass());
  217. MPM.add(createDeadCodeEliminationPass());
  218. MPM.add(createDxilTranslateRawBuffer());
  219. }
  220. // HLSL Change Ends
  221. void PassManagerBuilder::populateModulePassManager(
  222. legacy::PassManagerBase &MPM) {
  223. // If all optimizations are disabled, just run the always-inline pass and,
  224. // if enabled, the function merging pass.
  225. if (OptLevel == 0) {
  226. if (!HLSLHighLevel) {
  227. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  228. }
  229. if (Inliner) {
  230. MPM.add(Inliner);
  231. Inliner = nullptr;
  232. }
  233. // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
  234. // creates a CGSCC pass manager, but we don't want to add extensions into
  235. // that pass manager. To prevent this we insert a no-op module pass to reset
  236. // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
  237. // builds. The function merging pass is
  238. if (MergeFunctions)
  239. MPM.add(createMergeFunctionsPass());
  240. else if (!Extensions.empty()) // HLSL Change - GlobalExtensions not considered
  241. MPM.add(createBarrierNoopPass());
  242. addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
  243. // HLSL Change Begins.
  244. addHLSLPasses(HLSLHighLevel, true/*NoOpt*/, HLSLExtensionsCodeGen, MPM);
  245. if (!HLSLHighLevel) {
  246. MPM.add(createMultiDimArrayToOneDimArrayPass());
  247. MPM.add(createDxilCondenseResourcesPass());
  248. MPM.add(createDxilLegalizeSampleOffsetPass());
  249. MPM.add(createDxilFinalizeModulePass());
  250. MPM.add(createComputeViewIdStatePass());
  251. MPM.add(createDxilDeadFunctionEliminationPass());
  252. MPM.add(createNoPausePassesPass());
  253. MPM.add(createDxilEmitMetadataPass());
  254. }
  255. // HLSL Change Ends.
  256. return;
  257. }
  258. if (!HLSLHighLevel) {
  259. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  260. }
  261. // HLSL Change Begins
  262. MPM.add(createAlwaysInlinerPass(/*InsertLifeTime*/false));
  263. if (Inliner) {
  264. delete Inliner;
  265. Inliner = nullptr;
  266. }
  267. addHLSLPasses(HLSLHighLevel, false/*NoOpt*/, HLSLExtensionsCodeGen, MPM); // HLSL Change
  268. // HLSL Change Ends
  269. // Add LibraryInfo if we have some.
  270. if (LibraryInfo)
  271. MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  272. addInitialAliasAnalysisPasses(MPM);
  273. if (!DisableUnitAtATime) {
  274. addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
  275. MPM.add(createIPSCCPPass()); // IP SCCP
  276. MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
  277. MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
  278. MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
  279. addExtensionsToPM(EP_Peephole, MPM);
  280. MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
  281. }
  282. // Start of CallGraph SCC passes.
  283. if (!DisableUnitAtATime)
  284. MPM.add(createPruneEHPass()); // Remove dead EH info
  285. if (Inliner) {
  286. MPM.add(Inliner);
  287. Inliner = nullptr;
  288. }
  289. if (!DisableUnitAtATime)
  290. MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
  291. if (OptLevel > 2)
  292. MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
  293. // Start of function pass.
  294. // Break up aggregate allocas, using SSAUpdater.
  295. // HLSL Change - don't run SROA.
  296. // HLSL uses special SROA added in addHLSLPasses.
  297. if (HLSLHighLevel) // HLSL Change
  298. if (UseNewSROA)
  299. MPM.add(createSROAPass(/*RequiresDomTree*/ false));
  300. else
  301. MPM.add(createScalarReplAggregatesPass(-1, false));
  302. // HLSL Change. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  303. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps.
  304. MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
  305. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  306. MPM.add(createInstructionCombiningPass()); // Combine silly seq's
  307. addExtensionsToPM(EP_Peephole, MPM);
  308. // HLSL Change Begins.
  309. // HLSL does not allow recursize functions.
  310. //MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
  311. // HLSL Change Ends.
  312. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  313. MPM.add(createReassociatePass()); // Reassociate expressions
  314. // Rotate Loop - disable header duplication at -Oz
  315. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  316. MPM.add(createLICMPass()); // Hoist loop invariants
  317. //MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); // HLSL Change - may move barrier inside divergent if.
  318. MPM.add(createInstructionCombiningPass());
  319. MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
  320. MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
  321. MPM.add(createLoopDeletionPass()); // Delete dead loops
  322. if (EnableLoopInterchange) {
  323. MPM.add(createLoopInterchangePass()); // Interchange loops
  324. MPM.add(createCFGSimplificationPass());
  325. }
  326. if (!DisableUnrollLoops)
  327. MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
  328. addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
  329. if (OptLevel > 1) {
  330. if (EnableMLSM)
  331. MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
  332. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  333. }
  334. // HLSL Change Begins.
  335. // HLSL don't allow memcpy and memset.
  336. //MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
  337. // HLSL Change Ends.
  338. MPM.add(createSCCPPass()); // Constant prop with SCCP
  339. // Delete dead bit computations (instcombine runs after to fold away the dead
  340. // computations, and then ADCE will run later to exploit any new DCE
  341. // opportunities that creates).
  342. MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
  343. // Run instcombine after redundancy elimination to exploit opportunities
  344. // opened up by them.
  345. MPM.add(createInstructionCombiningPass());
  346. addExtensionsToPM(EP_Peephole, MPM);
  347. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps
  348. MPM.add(createCorrelatedValuePropagationPass());
  349. MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
  350. MPM.add(createLICMPass());
  351. addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
  352. if (RerollLoops)
  353. MPM.add(createLoopRerollPass());
  354. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  355. if (!RunSLPAfterLoopVectorization) {
  356. if (SLPVectorize)
  357. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  358. if (BBVectorize) {
  359. MPM.add(createBBVectorizePass());
  360. MPM.add(createInstructionCombiningPass());
  361. addExtensionsToPM(EP_Peephole, MPM);
  362. if (OptLevel > 1 && UseGVNAfterVectorization)
  363. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  364. else
  365. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  366. // BBVectorize may have significantly shortened a loop body; unroll again.
  367. if (!DisableUnrollLoops)
  368. MPM.add(createLoopUnrollPass());
  369. }
  370. }
  371. #endif
  372. if (LoadCombine)
  373. MPM.add(createLoadCombinePass());
  374. MPM.add(createHoistConstantArrayPass()); // HLSL change
  375. MPM.add(createAggressiveDCEPass()); // Delete dead instructions
  376. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  377. MPM.add(createInstructionCombiningPass()); // Clean up after everything.
  378. addExtensionsToPM(EP_Peephole, MPM);
  379. // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
  380. // pass manager that we are specifically trying to avoid. To prevent this
  381. // we must insert a no-op module pass to reset the pass manager.
  382. MPM.add(createBarrierNoopPass());
  383. if (RunFloat2Int)
  384. MPM.add(createFloat2IntPass());
  385. // Re-rotate loops in all our loop nests. These may have fallout out of
  386. // rotated form due to GVN or other transformations, and the vectorizer relies
  387. // on the rotated form. Disable header duplication at -Oz.
  388. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  389. // Distribute loops to allow partial vectorization. I.e. isolate dependences
  390. // into separate loop that would otherwise inhibit vectorization.
  391. if (EnableLoopDistribute)
  392. MPM.add(createLoopDistributePass());
  393. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  394. MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
  395. #endif
  396. // FIXME: Because of #pragma vectorize enable, the passes below are always
  397. // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
  398. // on -O1 and no #pragma is found). Would be good to have these two passes
  399. // as function calls, so that we can only pass them when the vectorizer
  400. // changed the code.
  401. MPM.add(createInstructionCombiningPass());
  402. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  403. if (OptLevel > 1 && ExtraVectorizerPasses) {
  404. // At higher optimization levels, try to clean up any runtime overlap and
  405. // alignment checks inserted by the vectorizer. We want to track correllated
  406. // runtime checks for two inner loops in the same outer loop, fold any
  407. // common computations, hoist loop-invariant aspects out of any outer loop,
  408. // and unswitch the runtime checks if possible. Once hoisted, we may have
  409. // dead (or speculatable) control flows or more combining opportunities.
  410. MPM.add(createEarlyCSEPass());
  411. MPM.add(createCorrelatedValuePropagationPass());
  412. MPM.add(createInstructionCombiningPass());
  413. MPM.add(createLICMPass());
  414. MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
  415. MPM.add(createCFGSimplificationPass());
  416. MPM.add(createInstructionCombiningPass());
  417. }
  418. if (RunSLPAfterLoopVectorization) {
  419. if (SLPVectorize) {
  420. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  421. if (OptLevel > 1 && ExtraVectorizerPasses) {
  422. MPM.add(createEarlyCSEPass());
  423. }
  424. }
  425. if (BBVectorize) {
  426. MPM.add(createBBVectorizePass());
  427. MPM.add(createInstructionCombiningPass());
  428. addExtensionsToPM(EP_Peephole, MPM);
  429. if (OptLevel > 1 && UseGVNAfterVectorization)
  430. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  431. else
  432. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  433. // BBVectorize may have significantly shortened a loop body; unroll again.
  434. if (!DisableUnrollLoops)
  435. MPM.add(createLoopUnrollPass());
  436. }
  437. }
  438. #endif // HLSL Change - don't build vectorization passes
  439. addExtensionsToPM(EP_Peephole, MPM);
  440. MPM.add(createCFGSimplificationPass());
  441. MPM.add(createInstructionCombiningPass());
  442. if (!DisableUnrollLoops) {
  443. MPM.add(createLoopUnrollPass()); // Unroll small loops
  444. // LoopUnroll may generate some redundency to cleanup.
  445. MPM.add(createInstructionCombiningPass());
  446. // Runtime unrolling will introduce runtime check in loop prologue. If the
  447. // unrolled loop is a inner loop, then the prologue will be inside the
  448. // outer loop. LICM pass can help to promote the runtime check out if the
  449. // checked value is loop invariant.
  450. MPM.add(createLICMPass());
  451. }
  452. // After vectorization and unrolling, assume intrinsics may tell us more
  453. // about pointer alignments.
  454. MPM.add(createAlignmentFromAssumptionsPass());
  455. if (!DisableUnitAtATime) {
  456. // FIXME: We shouldn't bother with this anymore.
  457. MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
  458. // GlobalOpt already deletes dead functions and globals, at -O2 try a
  459. // late pass of GlobalDCE. It is capable of deleting dead cycles.
  460. if (OptLevel > 1) {
  461. if (!PrepareForLTO) {
  462. // Remove avail extern fns and globals definitions if we aren't
  463. // compiling an object file for later LTO. For LTO we want to preserve
  464. // these so they are eligible for inlining at link-time. Note if they
  465. // are unreferenced they will be removed by GlobalDCE below, so
  466. // this only impacts referenced available externally globals.
  467. // Eventually they will be suppressed during codegen, but eliminating
  468. // here enables more opportunity for GlobalDCE as it may make
  469. // globals referenced by available external functions dead.
  470. MPM.add(createEliminateAvailableExternallyPass());
  471. }
  472. MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
  473. MPM.add(createConstantMergePass()); // Merge dup global constants
  474. }
  475. }
  476. if (MergeFunctions)
  477. MPM.add(createMergeFunctionsPass());
  478. // HLSL Change Begins.
  479. if (!HLSLHighLevel) {
  480. MPM.add(createMultiDimArrayToOneDimArrayPass());
  481. MPM.add(createDxilCondenseResourcesPass());
  482. if (DisableUnrollLoops)
  483. MPM.add(createDxilLegalizeSampleOffsetPass());
  484. MPM.add(createDxilFinalizeModulePass());
  485. MPM.add(createComputeViewIdStatePass());
  486. MPM.add(createDxilDeadFunctionEliminationPass());
  487. MPM.add(createNoPausePassesPass());
  488. MPM.add(createDxilEmitMetadataPass());
  489. }
  490. // HLSL Change Ends.
  491. addExtensionsToPM(EP_OptimizerLast, MPM);
  492. }
  493. void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
  494. // Provide AliasAnalysis services for optimizations.
  495. addInitialAliasAnalysisPasses(PM);
  496. // Propagate constants at call sites into the functions they call. This
  497. // opens opportunities for globalopt (and inlining) by substituting function
  498. // pointers passed as arguments to direct uses of functions.
  499. PM.add(createIPSCCPPass());
  500. // Now that we internalized some globals, see if we can hack on them!
  501. PM.add(createGlobalOptimizerPass());
  502. // Linking modules together can lead to duplicated global constants, only
  503. // keep one copy of each constant.
  504. PM.add(createConstantMergePass());
  505. // Remove unused arguments from functions.
  506. PM.add(createDeadArgEliminationPass());
  507. // Reduce the code after globalopt and ipsccp. Both can open up significant
  508. // simplification opportunities, and both can propagate functions through
  509. // function pointers. When this happens, we often have to resolve varargs
  510. // calls, etc, so let instcombine do this.
  511. PM.add(createInstructionCombiningPass());
  512. addExtensionsToPM(EP_Peephole, PM);
  513. // Inline small functions
  514. bool RunInliner = Inliner;
  515. if (RunInliner) {
  516. PM.add(Inliner);
  517. Inliner = nullptr;
  518. }
  519. PM.add(createPruneEHPass()); // Remove dead EH info.
  520. // Optimize globals again if we ran the inliner.
  521. if (RunInliner)
  522. PM.add(createGlobalOptimizerPass());
  523. PM.add(createGlobalDCEPass()); // Remove dead functions.
  524. // If we didn't decide to inline a function, check to see if we can
  525. // transform it to pass arguments by value instead of by reference.
  526. PM.add(createArgumentPromotionPass());
  527. // The IPO passes may leave cruft around. Clean up after them.
  528. PM.add(createInstructionCombiningPass());
  529. addExtensionsToPM(EP_Peephole, PM);
  530. // HLSL Change. PM.add(createJumpThreadingPass());
  531. // Break up allocas
  532. if (UseNewSROA)
  533. PM.add(createSROAPass());
  534. else
  535. PM.add(createScalarReplAggregatesPass());
  536. // Run a few AA driven optimizations here and now, to cleanup the code.
  537. PM.add(createFunctionAttrsPass()); // Add nocapture.
  538. PM.add(createGlobalsModRefPass()); // IP alias analysis.
  539. PM.add(createLICMPass()); // Hoist loop invariants.
  540. if (EnableMLSM)
  541. PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
  542. PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
  543. PM.add(createMemCpyOptPass()); // Remove dead memcpys.
  544. // Nuke dead stores.
  545. PM.add(createDeadStoreEliminationPass());
  546. // More loops are countable; try to optimize them.
  547. PM.add(createIndVarSimplifyPass());
  548. PM.add(createLoopDeletionPass());
  549. if (EnableLoopInterchange)
  550. PM.add(createLoopInterchangePass());
  551. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  552. PM.add(createLoopVectorizePass(true, LoopVectorize));
  553. // More scalar chains could be vectorized due to more alias information
  554. if (RunSLPAfterLoopVectorization)
  555. if (SLPVectorize)
  556. PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  557. // After vectorization, assume intrinsics may tell us more about pointer
  558. // alignments.
  559. PM.add(createAlignmentFromAssumptionsPass());
  560. #endif
  561. if (LoadCombine)
  562. PM.add(createLoadCombinePass());
  563. // Cleanup and simplify the code after the scalar optimizations.
  564. PM.add(createInstructionCombiningPass());
  565. addExtensionsToPM(EP_Peephole, PM);
  566. // HLSL Change. PM.add(createJumpThreadingPass());
  567. }
  568. void PassManagerBuilder::addLateLTOOptimizationPasses(
  569. legacy::PassManagerBase &PM) {
  570. // Delete basic blocks, which optimization passes may have killed.
  571. PM.add(createCFGSimplificationPass());
  572. // Now that we have optimized the program, discard unreachable functions.
  573. PM.add(createGlobalDCEPass());
  574. // FIXME: this is profitable (for compiler time) to do at -O0 too, but
  575. // currently it damages debug info.
  576. if (MergeFunctions)
  577. PM.add(createMergeFunctionsPass());
  578. }
  579. void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
  580. if (LibraryInfo)
  581. PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  582. if (VerifyInput)
  583. PM.add(createVerifierPass());
  584. if (OptLevel > 1)
  585. addLTOOptimizationPasses(PM);
  586. // Lower bit sets to globals. This pass supports Clang's control flow
  587. // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
  588. // is enabled. The pass does nothing if CFI is disabled.
  589. PM.add(createLowerBitSetsPass());
  590. if (OptLevel != 0)
  591. addLateLTOOptimizationPasses(PM);
  592. if (VerifyOutput)
  593. PM.add(createVerifierPass());
  594. }
  595. inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
  596. return reinterpret_cast<PassManagerBuilder*>(P);
  597. }
  598. inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
  599. return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
  600. }
  601. LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
  602. PassManagerBuilder *PMB = new PassManagerBuilder();
  603. return wrap(PMB);
  604. }
  605. void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
  606. PassManagerBuilder *Builder = unwrap(PMB);
  607. delete Builder;
  608. }
  609. void
  610. LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
  611. unsigned OptLevel) {
  612. PassManagerBuilder *Builder = unwrap(PMB);
  613. Builder->OptLevel = OptLevel;
  614. }
  615. void
  616. LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
  617. unsigned SizeLevel) {
  618. PassManagerBuilder *Builder = unwrap(PMB);
  619. Builder->SizeLevel = SizeLevel;
  620. }
  621. void
  622. LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
  623. LLVMBool Value) {
  624. PassManagerBuilder *Builder = unwrap(PMB);
  625. Builder->DisableUnitAtATime = Value;
  626. }
  627. void
  628. LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
  629. LLVMBool Value) {
  630. PassManagerBuilder *Builder = unwrap(PMB);
  631. Builder->DisableUnrollLoops = Value;
  632. }
  633. void
  634. LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
  635. LLVMBool Value) {
  636. // NOTE: The simplify-libcalls pass has been removed.
  637. }
  638. void
  639. LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
  640. unsigned Threshold) {
  641. PassManagerBuilder *Builder = unwrap(PMB);
  642. Builder->Inliner = createFunctionInliningPass(Threshold);
  643. }
  644. void
  645. LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
  646. LLVMPassManagerRef PM) {
  647. PassManagerBuilder *Builder = unwrap(PMB);
  648. legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
  649. Builder->populateFunctionPassManager(*FPM);
  650. }
  651. void
  652. LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
  653. LLVMPassManagerRef PM) {
  654. PassManagerBuilder *Builder = unwrap(PMB);
  655. legacy::PassManagerBase *MPM = unwrap(PM);
  656. Builder->populateModulePassManager(*MPM);
  657. }
  658. void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
  659. LLVMPassManagerRef PM,
  660. LLVMBool Internalize,
  661. LLVMBool RunInliner) {
  662. PassManagerBuilder *Builder = unwrap(PMB);
  663. legacy::PassManagerBase *LPM = unwrap(PM);
  664. // A small backwards compatibility hack. populateLTOPassManager used to take
  665. // an RunInliner option.
  666. if (RunInliner && !Builder->Inliner)
  667. Builder->Inliner = createFunctionInliningPass();
  668. Builder->populateLTOPassManager(*LPM);
  669. }