PassManagerBuilder.cpp 32 KB

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