PassManagerBuilder.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. }
  219. // HLSL Change Ends
  220. void PassManagerBuilder::populateModulePassManager(
  221. legacy::PassManagerBase &MPM) {
  222. // If all optimizations are disabled, just run the always-inline pass and,
  223. // if enabled, the function merging pass.
  224. if (OptLevel == 0) {
  225. if (!HLSLHighLevel) {
  226. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  227. }
  228. if (Inliner) {
  229. MPM.add(Inliner);
  230. Inliner = nullptr;
  231. }
  232. // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
  233. // creates a CGSCC pass manager, but we don't want to add extensions into
  234. // that pass manager. To prevent this we insert a no-op module pass to reset
  235. // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
  236. // builds. The function merging pass is
  237. if (MergeFunctions)
  238. MPM.add(createMergeFunctionsPass());
  239. else if (!Extensions.empty()) // HLSL Change - GlobalExtensions not considered
  240. MPM.add(createBarrierNoopPass());
  241. addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
  242. // HLSL Change Begins.
  243. addHLSLPasses(HLSLHighLevel, true/*NoOpt*/, HLSLExtensionsCodeGen, MPM); // HLSL Change
  244. if (!HLSLHighLevel) {
  245. MPM.add(createMultiDimArrayToOneDimArrayPass());// HLSL Change
  246. MPM.add(createDxilCondenseResourcesPass()); // HLSL Change
  247. MPM.add(createDxilLegalizeSampleOffsetPass()); // HLSL Change
  248. MPM.add(createDxilFinalizeModulePass()); // HLSL Change
  249. MPM.add(createComputeViewIdStatePass()); // HLSL Change
  250. MPM.add(createDxilDeadFunctionEliminationPass()); // HLSL Change
  251. MPM.add(createDxilEmitMetadataPass()); // HLSL Change
  252. }
  253. // HLSL Change Ends.
  254. return;
  255. }
  256. if (!HLSLHighLevel) {
  257. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  258. }
  259. // HLSL Change Begins
  260. MPM.add(createAlwaysInlinerPass(/*InsertLifeTime*/false));
  261. if (Inliner) {
  262. delete Inliner;
  263. Inliner = nullptr;
  264. }
  265. addHLSLPasses(HLSLHighLevel, false/*NoOpt*/, HLSLExtensionsCodeGen, MPM); // HLSL Change
  266. // HLSL Change Ends
  267. // Add LibraryInfo if we have some.
  268. if (LibraryInfo)
  269. MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  270. addInitialAliasAnalysisPasses(MPM);
  271. if (!DisableUnitAtATime) {
  272. addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
  273. MPM.add(createIPSCCPPass()); // IP SCCP
  274. MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
  275. MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
  276. MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
  277. addExtensionsToPM(EP_Peephole, MPM);
  278. MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
  279. }
  280. // Start of CallGraph SCC passes.
  281. if (!DisableUnitAtATime)
  282. MPM.add(createPruneEHPass()); // Remove dead EH info
  283. if (Inliner) {
  284. MPM.add(Inliner);
  285. Inliner = nullptr;
  286. }
  287. if (!DisableUnitAtATime)
  288. MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
  289. if (OptLevel > 2)
  290. MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
  291. // Start of function pass.
  292. // Break up aggregate allocas, using SSAUpdater.
  293. // HLSL Change - don't run SROA.
  294. // HLSL uses special SROA added in addHLSLPasses.
  295. if (HLSLHighLevel) // HLSL Change
  296. if (UseNewSROA)
  297. MPM.add(createSROAPass(/*RequiresDomTree*/ false));
  298. else
  299. MPM.add(createScalarReplAggregatesPass(-1, false));
  300. // HLSL Change. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  301. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps.
  302. MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
  303. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  304. MPM.add(createInstructionCombiningPass()); // Combine silly seq's
  305. addExtensionsToPM(EP_Peephole, MPM);
  306. // HLSL Change Begins.
  307. // HLSL does not allow recursize functions.
  308. //MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
  309. // HLSL Change Ends.
  310. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  311. MPM.add(createReassociatePass()); // Reassociate expressions
  312. // Rotate Loop - disable header duplication at -Oz
  313. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  314. MPM.add(createLICMPass()); // Hoist loop invariants
  315. //MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); // HLSL Change - may move barrier inside divergent if.
  316. MPM.add(createInstructionCombiningPass());
  317. MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
  318. MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
  319. MPM.add(createLoopDeletionPass()); // Delete dead loops
  320. if (EnableLoopInterchange) {
  321. MPM.add(createLoopInterchangePass()); // Interchange loops
  322. MPM.add(createCFGSimplificationPass());
  323. }
  324. if (!DisableUnrollLoops)
  325. MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
  326. addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
  327. if (OptLevel > 1) {
  328. if (EnableMLSM)
  329. MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
  330. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  331. }
  332. // HLSL Change Begins.
  333. // HLSL don't allow memcpy and memset.
  334. //MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
  335. // HLSL Change Ends.
  336. MPM.add(createSCCPPass()); // Constant prop with SCCP
  337. // Delete dead bit computations (instcombine runs after to fold away the dead
  338. // computations, and then ADCE will run later to exploit any new DCE
  339. // opportunities that creates).
  340. MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
  341. // Run instcombine after redundancy elimination to exploit opportunities
  342. // opened up by them.
  343. MPM.add(createInstructionCombiningPass());
  344. addExtensionsToPM(EP_Peephole, MPM);
  345. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps
  346. MPM.add(createCorrelatedValuePropagationPass());
  347. MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
  348. MPM.add(createLICMPass());
  349. addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
  350. if (RerollLoops)
  351. MPM.add(createLoopRerollPass());
  352. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  353. if (!RunSLPAfterLoopVectorization) {
  354. if (SLPVectorize)
  355. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  356. if (BBVectorize) {
  357. MPM.add(createBBVectorizePass());
  358. MPM.add(createInstructionCombiningPass());
  359. addExtensionsToPM(EP_Peephole, MPM);
  360. if (OptLevel > 1 && UseGVNAfterVectorization)
  361. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  362. else
  363. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  364. // BBVectorize may have significantly shortened a loop body; unroll again.
  365. if (!DisableUnrollLoops)
  366. MPM.add(createLoopUnrollPass());
  367. }
  368. }
  369. #endif
  370. if (LoadCombine)
  371. MPM.add(createLoadCombinePass());
  372. MPM.add(createHoistConstantArrayPass()); // HLSL change
  373. MPM.add(createAggressiveDCEPass()); // Delete dead instructions
  374. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  375. MPM.add(createInstructionCombiningPass()); // Clean up after everything.
  376. addExtensionsToPM(EP_Peephole, MPM);
  377. // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
  378. // pass manager that we are specifically trying to avoid. To prevent this
  379. // we must insert a no-op module pass to reset the pass manager.
  380. MPM.add(createBarrierNoopPass());
  381. if (RunFloat2Int)
  382. MPM.add(createFloat2IntPass());
  383. // Re-rotate loops in all our loop nests. These may have fallout out of
  384. // rotated form due to GVN or other transformations, and the vectorizer relies
  385. // on the rotated form. Disable header duplication at -Oz.
  386. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  387. // Distribute loops to allow partial vectorization. I.e. isolate dependences
  388. // into separate loop that would otherwise inhibit vectorization.
  389. if (EnableLoopDistribute)
  390. MPM.add(createLoopDistributePass());
  391. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  392. MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
  393. #endif
  394. // FIXME: Because of #pragma vectorize enable, the passes below are always
  395. // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
  396. // on -O1 and no #pragma is found). Would be good to have these two passes
  397. // as function calls, so that we can only pass them when the vectorizer
  398. // changed the code.
  399. MPM.add(createInstructionCombiningPass());
  400. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  401. if (OptLevel > 1 && ExtraVectorizerPasses) {
  402. // At higher optimization levels, try to clean up any runtime overlap and
  403. // alignment checks inserted by the vectorizer. We want to track correllated
  404. // runtime checks for two inner loops in the same outer loop, fold any
  405. // common computations, hoist loop-invariant aspects out of any outer loop,
  406. // and unswitch the runtime checks if possible. Once hoisted, we may have
  407. // dead (or speculatable) control flows or more combining opportunities.
  408. MPM.add(createEarlyCSEPass());
  409. MPM.add(createCorrelatedValuePropagationPass());
  410. MPM.add(createInstructionCombiningPass());
  411. MPM.add(createLICMPass());
  412. MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
  413. MPM.add(createCFGSimplificationPass());
  414. MPM.add(createInstructionCombiningPass());
  415. }
  416. if (RunSLPAfterLoopVectorization) {
  417. if (SLPVectorize) {
  418. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  419. if (OptLevel > 1 && ExtraVectorizerPasses) {
  420. MPM.add(createEarlyCSEPass());
  421. }
  422. }
  423. if (BBVectorize) {
  424. MPM.add(createBBVectorizePass());
  425. MPM.add(createInstructionCombiningPass());
  426. addExtensionsToPM(EP_Peephole, MPM);
  427. if (OptLevel > 1 && UseGVNAfterVectorization)
  428. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  429. else
  430. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  431. // BBVectorize may have significantly shortened a loop body; unroll again.
  432. if (!DisableUnrollLoops)
  433. MPM.add(createLoopUnrollPass());
  434. }
  435. }
  436. #endif // HLSL Change - don't build vectorization passes
  437. addExtensionsToPM(EP_Peephole, MPM);
  438. MPM.add(createCFGSimplificationPass());
  439. MPM.add(createInstructionCombiningPass());
  440. if (!DisableUnrollLoops) {
  441. MPM.add(createLoopUnrollPass()); // Unroll small loops
  442. // LoopUnroll may generate some redundency to cleanup.
  443. MPM.add(createInstructionCombiningPass());
  444. // Runtime unrolling will introduce runtime check in loop prologue. If the
  445. // unrolled loop is a inner loop, then the prologue will be inside the
  446. // outer loop. LICM pass can help to promote the runtime check out if the
  447. // checked value is loop invariant.
  448. MPM.add(createLICMPass());
  449. }
  450. // After vectorization and unrolling, assume intrinsics may tell us more
  451. // about pointer alignments.
  452. MPM.add(createAlignmentFromAssumptionsPass());
  453. if (!DisableUnitAtATime) {
  454. // FIXME: We shouldn't bother with this anymore.
  455. MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
  456. // GlobalOpt already deletes dead functions and globals, at -O2 try a
  457. // late pass of GlobalDCE. It is capable of deleting dead cycles.
  458. if (OptLevel > 1) {
  459. if (!PrepareForLTO) {
  460. // Remove avail extern fns and globals definitions if we aren't
  461. // compiling an object file for later LTO. For LTO we want to preserve
  462. // these so they are eligible for inlining at link-time. Note if they
  463. // are unreferenced they will be removed by GlobalDCE below, so
  464. // this only impacts referenced available externally globals.
  465. // Eventually they will be suppressed during codegen, but eliminating
  466. // here enables more opportunity for GlobalDCE as it may make
  467. // globals referenced by available external functions dead.
  468. MPM.add(createEliminateAvailableExternallyPass());
  469. }
  470. MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
  471. MPM.add(createConstantMergePass()); // Merge dup global constants
  472. }
  473. }
  474. if (MergeFunctions)
  475. MPM.add(createMergeFunctionsPass());
  476. // HLSL Change Begins.
  477. if (!HLSLHighLevel) {
  478. MPM.add(createMultiDimArrayToOneDimArrayPass());// HLSL Change
  479. MPM.add(createDxilCondenseResourcesPass());
  480. if (DisableUnrollLoops)
  481. MPM.add(createDxilLegalizeSampleOffsetPass()); // HLSL Change
  482. MPM.add(createDxilFinalizeModulePass());
  483. MPM.add(createComputeViewIdStatePass()); // HLSL Change
  484. MPM.add(createDxilDeadFunctionEliminationPass()); // HLSL Change
  485. MPM.add(createDxilEmitMetadataPass());
  486. }
  487. // HLSL Change Ends.
  488. addExtensionsToPM(EP_OptimizerLast, MPM);
  489. }
  490. void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
  491. // Provide AliasAnalysis services for optimizations.
  492. addInitialAliasAnalysisPasses(PM);
  493. // Propagate constants at call sites into the functions they call. This
  494. // opens opportunities for globalopt (and inlining) by substituting function
  495. // pointers passed as arguments to direct uses of functions.
  496. PM.add(createIPSCCPPass());
  497. // Now that we internalized some globals, see if we can hack on them!
  498. PM.add(createGlobalOptimizerPass());
  499. // Linking modules together can lead to duplicated global constants, only
  500. // keep one copy of each constant.
  501. PM.add(createConstantMergePass());
  502. // Remove unused arguments from functions.
  503. PM.add(createDeadArgEliminationPass());
  504. // Reduce the code after globalopt and ipsccp. Both can open up significant
  505. // simplification opportunities, and both can propagate functions through
  506. // function pointers. When this happens, we often have to resolve varargs
  507. // calls, etc, so let instcombine do this.
  508. PM.add(createInstructionCombiningPass());
  509. addExtensionsToPM(EP_Peephole, PM);
  510. // Inline small functions
  511. bool RunInliner = Inliner;
  512. if (RunInliner) {
  513. PM.add(Inliner);
  514. Inliner = nullptr;
  515. }
  516. PM.add(createPruneEHPass()); // Remove dead EH info.
  517. // Optimize globals again if we ran the inliner.
  518. if (RunInliner)
  519. PM.add(createGlobalOptimizerPass());
  520. PM.add(createGlobalDCEPass()); // Remove dead functions.
  521. // If we didn't decide to inline a function, check to see if we can
  522. // transform it to pass arguments by value instead of by reference.
  523. PM.add(createArgumentPromotionPass());
  524. // The IPO passes may leave cruft around. Clean up after them.
  525. PM.add(createInstructionCombiningPass());
  526. addExtensionsToPM(EP_Peephole, PM);
  527. // HLSL Change. PM.add(createJumpThreadingPass());
  528. // Break up allocas
  529. if (UseNewSROA)
  530. PM.add(createSROAPass());
  531. else
  532. PM.add(createScalarReplAggregatesPass());
  533. // Run a few AA driven optimizations here and now, to cleanup the code.
  534. PM.add(createFunctionAttrsPass()); // Add nocapture.
  535. PM.add(createGlobalsModRefPass()); // IP alias analysis.
  536. PM.add(createLICMPass()); // Hoist loop invariants.
  537. if (EnableMLSM)
  538. PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
  539. PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
  540. PM.add(createMemCpyOptPass()); // Remove dead memcpys.
  541. // Nuke dead stores.
  542. PM.add(createDeadStoreEliminationPass());
  543. // More loops are countable; try to optimize them.
  544. PM.add(createIndVarSimplifyPass());
  545. PM.add(createLoopDeletionPass());
  546. if (EnableLoopInterchange)
  547. PM.add(createLoopInterchangePass());
  548. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  549. PM.add(createLoopVectorizePass(true, LoopVectorize));
  550. // More scalar chains could be vectorized due to more alias information
  551. if (RunSLPAfterLoopVectorization)
  552. if (SLPVectorize)
  553. PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  554. // After vectorization, assume intrinsics may tell us more about pointer
  555. // alignments.
  556. PM.add(createAlignmentFromAssumptionsPass());
  557. #endif
  558. if (LoadCombine)
  559. PM.add(createLoadCombinePass());
  560. // Cleanup and simplify the code after the scalar optimizations.
  561. PM.add(createInstructionCombiningPass());
  562. addExtensionsToPM(EP_Peephole, PM);
  563. // HLSL Change. PM.add(createJumpThreadingPass());
  564. }
  565. void PassManagerBuilder::addLateLTOOptimizationPasses(
  566. legacy::PassManagerBase &PM) {
  567. // Delete basic blocks, which optimization passes may have killed.
  568. PM.add(createCFGSimplificationPass());
  569. // Now that we have optimized the program, discard unreachable functions.
  570. PM.add(createGlobalDCEPass());
  571. // FIXME: this is profitable (for compiler time) to do at -O0 too, but
  572. // currently it damages debug info.
  573. if (MergeFunctions)
  574. PM.add(createMergeFunctionsPass());
  575. }
  576. void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
  577. if (LibraryInfo)
  578. PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  579. if (VerifyInput)
  580. PM.add(createVerifierPass());
  581. if (OptLevel > 1)
  582. addLTOOptimizationPasses(PM);
  583. // Lower bit sets to globals. This pass supports Clang's control flow
  584. // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
  585. // is enabled. The pass does nothing if CFI is disabled.
  586. PM.add(createLowerBitSetsPass());
  587. if (OptLevel != 0)
  588. addLateLTOOptimizationPasses(PM);
  589. if (VerifyOutput)
  590. PM.add(createVerifierPass());
  591. }
  592. inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
  593. return reinterpret_cast<PassManagerBuilder*>(P);
  594. }
  595. inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
  596. return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
  597. }
  598. LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
  599. PassManagerBuilder *PMB = new PassManagerBuilder();
  600. return wrap(PMB);
  601. }
  602. void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
  603. PassManagerBuilder *Builder = unwrap(PMB);
  604. delete Builder;
  605. }
  606. void
  607. LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
  608. unsigned OptLevel) {
  609. PassManagerBuilder *Builder = unwrap(PMB);
  610. Builder->OptLevel = OptLevel;
  611. }
  612. void
  613. LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
  614. unsigned SizeLevel) {
  615. PassManagerBuilder *Builder = unwrap(PMB);
  616. Builder->SizeLevel = SizeLevel;
  617. }
  618. void
  619. LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
  620. LLVMBool Value) {
  621. PassManagerBuilder *Builder = unwrap(PMB);
  622. Builder->DisableUnitAtATime = Value;
  623. }
  624. void
  625. LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
  626. LLVMBool Value) {
  627. PassManagerBuilder *Builder = unwrap(PMB);
  628. Builder->DisableUnrollLoops = Value;
  629. }
  630. void
  631. LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
  632. LLVMBool Value) {
  633. // NOTE: The simplify-libcalls pass has been removed.
  634. }
  635. void
  636. LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
  637. unsigned Threshold) {
  638. PassManagerBuilder *Builder = unwrap(PMB);
  639. Builder->Inliner = createFunctionInliningPass(Threshold);
  640. }
  641. void
  642. LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
  643. LLVMPassManagerRef PM) {
  644. PassManagerBuilder *Builder = unwrap(PMB);
  645. legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
  646. Builder->populateFunctionPassManager(*FPM);
  647. }
  648. void
  649. LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
  650. LLVMPassManagerRef PM) {
  651. PassManagerBuilder *Builder = unwrap(PMB);
  652. legacy::PassManagerBase *MPM = unwrap(PM);
  653. Builder->populateModulePassManager(*MPM);
  654. }
  655. void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
  656. LLVMPassManagerRef PM,
  657. LLVMBool Internalize,
  658. LLVMBool RunInliner) {
  659. PassManagerBuilder *Builder = unwrap(PMB);
  660. legacy::PassManagerBase *LPM = unwrap(PM);
  661. // A small backwards compatibility hack. populateLTOPassManager used to take
  662. // an RunInliner option.
  663. if (RunInliner && !Builder->Inliner)
  664. Builder->Inliner = createFunctionInliningPass();
  665. Builder->populateLTOPassManager(*LPM);
  666. }