opt.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
  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. // Optimizations may be specified an arbitrary number of times on the command
  11. // line, They are run in the order specified.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "BreakpointPrinter.h"
  15. #include "NewPMDriver.h"
  16. #include "PassPrinters.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/Analysis/CallGraph.h"
  19. #include "llvm/Analysis/CallGraphSCCPass.h"
  20. #include "llvm/Analysis/LoopPass.h"
  21. #include "llvm/Analysis/RegionPass.h"
  22. #include "llvm/Analysis/TargetLibraryInfo.h"
  23. #include "llvm/Analysis/TargetTransformInfo.h"
  24. #include "llvm/Bitcode/BitcodeWriterPass.h"
  25. #include "llvm/CodeGen/CommandFlags.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DebugInfo.h"
  28. #include "llvm/IR/IRPrintingPasses.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/LegacyPassNameParser.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Verifier.h"
  33. #include "llvm/IRReader/IRReader.h"
  34. #include "llvm/InitializePasses.h"
  35. #include "llvm/LinkAllIR.h"
  36. #include "llvm/LinkAllPasses.h"
  37. #include "llvm/MC/SubtargetFeature.h"
  38. #include "llvm/IR/LegacyPassManager.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Host.h"
  42. #include "llvm/Support/ManagedStatic.h"
  43. #include "llvm/Support/PluginLoader.h"
  44. #include "llvm/Support/PrettyStackTrace.h"
  45. #include "llvm/Support/Signals.h"
  46. #include "llvm/Support/SourceMgr.h"
  47. #include "llvm/Support/SystemUtils.h"
  48. #include "llvm/Support/TargetRegistry.h"
  49. #include "llvm/Support/TargetSelect.h"
  50. #include "llvm/Support/ToolOutputFile.h"
  51. #include "llvm/Target/TargetMachine.h"
  52. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  53. // HLSL Change Starts
  54. #include "dxc/Support/Global.h"
  55. #include "dxc/HLSL/ReducibilityAnalysis.h"
  56. #include "dxc/Support/WinIncludes.h"
  57. #include "llvm/Support/MSFileSystem.h"
  58. // HLSL Change Ends
  59. #include <algorithm>
  60. #include <memory>
  61. using namespace llvm;
  62. using namespace opt_tool;
  63. // The OptimizationList is automatically populated with registered Passes by the
  64. // PassNameParser.
  65. //
  66. static cl::list<const PassInfo*, bool, PassNameParser>
  67. PassList(cl::desc("Optimizations available:"));
  68. // This flag specifies a textual description of the optimization pass pipeline
  69. // to run over the module. This flag switches opt to use the new pass manager
  70. // infrastructure, completely disabling all of the flags specific to the old
  71. // pass management.
  72. static cl::opt<std::string> PassPipeline(
  73. "passes",
  74. cl::desc("A textual description of the pass pipeline for optimizing"),
  75. cl::Hidden);
  76. // Other command line options...
  77. //
  78. static cl::opt<std::string>
  79. InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
  80. cl::init("-"), cl::value_desc("filename"));
  81. static cl::opt<std::string>
  82. OutputFilename("o", cl::desc("Override output filename"),
  83. cl::value_desc("filename"));
  84. static cl::opt<bool>
  85. Force("f", cl::desc("Enable binary output on terminals"));
  86. static cl::opt<bool>
  87. PrintEachXForm("p", cl::desc("Print module after each transformation"));
  88. static cl::opt<bool>
  89. NoOutput("disable-output",
  90. cl::desc("Do not write result bitcode file"), cl::Hidden);
  91. static cl::opt<bool>
  92. OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
  93. static cl::opt<bool>
  94. NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
  95. static cl::opt<bool>
  96. VerifyEach("verify-each", cl::desc("Verify after each transform"));
  97. static cl::opt<bool>
  98. StripDebug("strip-debug",
  99. cl::desc("Strip debugger symbol info from translation unit"));
  100. static cl::opt<bool>
  101. DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
  102. static cl::opt<bool>
  103. DisableOptimizations("disable-opt",
  104. cl::desc("Do not run any optimization passes"));
  105. static cl::opt<bool>
  106. StandardLinkOpts("std-link-opts",
  107. cl::desc("Include the standard link time optimizations"));
  108. static cl::opt<bool>
  109. OptLevelO1("O1",
  110. cl::desc("Optimization level 1. Similar to clang -O1"));
  111. static cl::opt<bool>
  112. OptLevelO2("O2",
  113. cl::desc("Optimization level 2. Similar to clang -O2"));
  114. static cl::opt<bool>
  115. OptLevelOs("Os",
  116. cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
  117. static cl::opt<bool>
  118. OptLevelOz("Oz",
  119. cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
  120. static cl::opt<bool>
  121. OptLevelO3("O3",
  122. cl::desc("Optimization level 3. Similar to clang -O3"));
  123. static cl::opt<std::string>
  124. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  125. static cl::opt<bool>
  126. UnitAtATime("funit-at-a-time",
  127. cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
  128. cl::init(true));
  129. static cl::opt<bool>
  130. DisableLoopUnrolling("disable-loop-unrolling",
  131. cl::desc("Disable loop unrolling in all relevant passes"),
  132. cl::init(false));
  133. static cl::opt<bool>
  134. DisableLoopVectorization("disable-loop-vectorization",
  135. cl::desc("Disable the loop vectorization pass"),
  136. cl::init(false));
  137. static cl::opt<bool>
  138. DisableSLPVectorization("disable-slp-vectorization",
  139. cl::desc("Disable the slp vectorization pass"),
  140. cl::init(false));
  141. static cl::opt<bool>
  142. DisableSimplifyLibCalls("disable-simplify-libcalls",
  143. cl::desc("Disable simplify-libcalls"));
  144. static cl::opt<bool>
  145. Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
  146. static cl::alias
  147. QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
  148. static cl::opt<bool>
  149. AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
  150. static cl::opt<bool>
  151. PrintBreakpoints("print-breakpoints-for-testing",
  152. cl::desc("Print select breakpoints location for testing"));
  153. static cl::opt<std::string>
  154. DefaultDataLayout("default-data-layout",
  155. cl::desc("data layout string to use if not specified by module"),
  156. cl::value_desc("layout-string"), cl::init(""));
  157. static cl::opt<bool> PreserveBitcodeUseListOrder(
  158. "preserve-bc-uselistorder",
  159. cl::desc("Preserve use-list order when writing LLVM bitcode."),
  160. cl::init(true), cl::Hidden);
  161. static cl::opt<bool> PreserveAssemblyUseListOrder(
  162. "preserve-ll-uselistorder",
  163. cl::desc("Preserve use-list order when writing LLVM assembly."),
  164. cl::init(false), cl::Hidden);
  165. static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
  166. // Add the pass to the pass manager...
  167. PM.add(P);
  168. // If we are verifying all of the intermediate steps, add the verifier...
  169. if (VerifyEach)
  170. PM.add(createVerifierPass());
  171. }
  172. /// This routine adds optimization passes based on selected optimization level,
  173. /// OptLevel.
  174. ///
  175. /// OptLevel - Optimization Level
  176. static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
  177. legacy::FunctionPassManager &FPM,
  178. unsigned OptLevel, unsigned SizeLevel) {
  179. FPM.add(createVerifierPass()); // Verify that input is correct
  180. PassManagerBuilder Builder;
  181. Builder.OptLevel = OptLevel;
  182. Builder.SizeLevel = SizeLevel;
  183. if (DisableInline) {
  184. // No inlining pass
  185. } else if (OptLevel > 1) {
  186. Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
  187. } else {
  188. Builder.Inliner = createAlwaysInlinerPass();
  189. }
  190. Builder.DisableUnitAtATime = !UnitAtATime;
  191. Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
  192. DisableLoopUnrolling : OptLevel == 0;
  193. // This is final, unless there is a #pragma vectorize enable
  194. if (DisableLoopVectorization)
  195. Builder.LoopVectorize = false;
  196. // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
  197. else if (!Builder.LoopVectorize)
  198. Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
  199. // When #pragma vectorize is on for SLP, do the same as above
  200. Builder.SLPVectorize =
  201. DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
  202. Builder.populateFunctionPassManager(FPM);
  203. Builder.populateModulePassManager(MPM);
  204. }
  205. static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
  206. PassManagerBuilder Builder;
  207. Builder.VerifyInput = true;
  208. if (DisableOptimizations)
  209. Builder.OptLevel = 0;
  210. if (!DisableInline)
  211. Builder.Inliner = createFunctionInliningPass();
  212. Builder.populateLTOPassManager(PM);
  213. }
  214. //===----------------------------------------------------------------------===//
  215. // CodeGen-related helper functions.
  216. //
  217. static CodeGenOpt::Level GetCodeGenOptLevel() {
  218. if (OptLevelO1)
  219. return CodeGenOpt::Less;
  220. if (OptLevelO2)
  221. return CodeGenOpt::Default;
  222. if (OptLevelO3)
  223. return CodeGenOpt::Aggressive;
  224. return CodeGenOpt::None;
  225. }
  226. // Returns the TargetMachine instance or zero if no triple is provided.
  227. static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
  228. StringRef FeaturesStr,
  229. const TargetOptions &Options) {
  230. std::string Error;
  231. const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
  232. Error);
  233. // Some modules don't specify a triple, and this is okay.
  234. if (!TheTarget) {
  235. return nullptr;
  236. }
  237. return TheTarget->createTargetMachine(TheTriple.getTriple(),
  238. CPUStr, FeaturesStr, Options,
  239. RelocModel, CMModel,
  240. GetCodeGenOptLevel());
  241. }
  242. #ifdef LINK_POLLY_INTO_TOOLS
  243. namespace polly {
  244. void initializePollyPasses(llvm::PassRegistry &Registry);
  245. }
  246. #endif
  247. //===----------------------------------------------------------------------===//
  248. // main for opt
  249. //
  250. // HLSL Change: changed calling convention to __cdecl
  251. int __cdecl main(int argc, char **argv) {
  252. // HLSL Change Starts
  253. if (llvm::sys::fs::SetupPerThreadFileSystem())
  254. return 1;
  255. llvm::sys::fs::AutoCleanupPerThreadFileSystem auto_cleanup_fs;
  256. if (FAILED(DxcInitThreadMalloc())) return 1;
  257. DxcSetThreadMallocOrDefault(nullptr);
  258. llvm::sys::fs::MSFileSystem* msfPtr;
  259. if (FAILED(CreateMSFileSystemForDisk(&msfPtr))) return 1;
  260. std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr);
  261. llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
  262. //llvm::STDStreamCloser stdStreamCloser;
  263. // HLSL Change Ends
  264. //sys::PrintStackTraceOnErrorSignal(); // HLSL Change
  265. //llvm::PrettyStackTraceProgram X(argc, argv); // HLSL Change
  266. // Enable debug stream buffering.
  267. EnableDebugBuffering = true;
  268. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  269. LLVMContext &Context = getGlobalContext();
  270. InitializeAllTargets();
  271. // InitializeAllTargetMCs(); // HLSL Change: remove MC targets
  272. InitializeAllAsmPrinters();
  273. // Initialize passes
  274. PassRegistry &Registry = *PassRegistry::getPassRegistry();
  275. initializeCore(Registry);
  276. initializeScalarOpts(Registry);
  277. initializeReducibilityAnalysisPass(Registry); // HLSL Change: add ReducibilityAnalysis pass
  278. // initializeObjCARCOpts(Registry); // HLSL Change: remove ObjC ARC passes
  279. // initializeVectorization(Registry); // HLSL Change: remove vectorization passes
  280. initializeIPO(Registry);
  281. initializeAnalysis(Registry);
  282. initializeIPA(Registry);
  283. initializeTransformUtils(Registry);
  284. initializeInstCombine(Registry);
  285. // initializeInstrumentation(Registry); // HLSL Change: remove instrumentation
  286. initializeTarget(Registry);
  287. // For codegen passes, only passes that do IR to IR transformation are
  288. // supported.
  289. // initializeCodeGenPreparePass(Registry); // HLSL Change: remove EH passes
  290. //initializeAtomicExpandPass(Registry); // HLSL Change: remove EH passes
  291. initializeRewriteSymbolsPass(Registry);
  292. //initializeWinEHPreparePass(Registry); // HLSL Change: remove EH passes
  293. //initializeDwarfEHPreparePass(Registry); // HLSL Change: remove EH passes
  294. //initializeSjLjEHPreparePass(Registry); // HLSL Change: remove EH passes
  295. // MS Change Starts
  296. initializeReducibilityAnalysisPass(Registry);
  297. #if HLSL_INTERNAL
  298. void initializeHlslInternalPasses(PassRegistry &);
  299. initializeHlslInternalPasses(Registry);
  300. #endif
  301. // MS Change Ends
  302. #ifdef LINK_POLLY_INTO_TOOLS
  303. polly::initializePollyPasses(Registry);
  304. #endif
  305. cl::ParseCommandLineOptions(argc, argv,
  306. "llvm .bc -> .bc modular optimizer and analysis printer\n");
  307. if (AnalyzeOnly && NoOutput) {
  308. errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
  309. return 1;
  310. }
  311. SMDiagnostic Err;
  312. // Load the input module...
  313. std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
  314. if (!M) {
  315. Err.print(argv[0], errs());
  316. return 1;
  317. }
  318. // Strip debug info before running the verifier.
  319. if (StripDebug)
  320. StripDebugInfo(*M);
  321. // Immediately run the verifier to catch any problems before starting up the
  322. // pass pipelines. Otherwise we can crash on broken code during
  323. // doInitialization().
  324. if (!NoVerify && verifyModule(*M, &errs())) {
  325. errs() << argv[0] << ": " << InputFilename
  326. << ": error: input module is broken!\n";
  327. return 1;
  328. }
  329. // If we are supposed to override the target triple, do so now.
  330. if (!TargetTriple.empty())
  331. M->setTargetTriple(Triple::normalize(TargetTriple));
  332. // Figure out what stream we are supposed to write to...
  333. std::unique_ptr<tool_output_file> Out;
  334. if (NoOutput) {
  335. if (!OutputFilename.empty())
  336. errs() << "WARNING: The -o (output filename) option is ignored when\n"
  337. "the --disable-output option is used.\n";
  338. } else {
  339. // Default to standard output.
  340. if (OutputFilename.empty())
  341. OutputFilename = "-";
  342. std::error_code EC;
  343. Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
  344. if (EC) {
  345. errs() << EC.message() << '\n';
  346. return 1;
  347. }
  348. }
  349. Triple ModuleTriple(M->getTargetTriple());
  350. std::string CPUStr, FeaturesStr;
  351. TargetMachine *Machine = nullptr;
  352. const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  353. if (ModuleTriple.getArch()) {
  354. CPUStr = getCPUStr();
  355. FeaturesStr = getFeaturesStr();
  356. Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
  357. }
  358. std::unique_ptr<TargetMachine> TM(Machine);
  359. // Override function attributes based on CPUStr, FeaturesStr, and command line
  360. // flags.
  361. setFunctionAttributes(CPUStr, FeaturesStr, *M);
  362. // If the output is set to be emitted to standard out, and standard out is a
  363. // console, print out a warning message and refuse to do it. We don't
  364. // impress anyone by spewing tons of binary goo to a terminal.
  365. if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
  366. if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
  367. NoOutput = true;
  368. if (PassPipeline.getNumOccurrences() > 0) {
  369. OutputKind OK = OK_NoOutput;
  370. if (!NoOutput)
  371. OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
  372. VerifierKind VK = VK_VerifyInAndOut;
  373. if (NoVerify)
  374. VK = VK_NoVerifier;
  375. else if (VerifyEach)
  376. VK = VK_VerifyEachPass;
  377. // The user has asked to use the new pass manager and provided a pipeline
  378. // string. Hand off the rest of the functionality to the new code for that
  379. // layer.
  380. return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
  381. PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
  382. PreserveBitcodeUseListOrder)
  383. ? 0
  384. : 1;
  385. }
  386. // Create a PassManager to hold and optimize the collection of passes we are
  387. // about to build.
  388. //
  389. legacy::PassManager Passes;
  390. // Add an appropriate TargetLibraryInfo pass for the module's triple.
  391. TargetLibraryInfoImpl TLII(ModuleTriple);
  392. // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  393. if (DisableSimplifyLibCalls)
  394. TLII.disableAllFunctions();
  395. Passes.add(new TargetLibraryInfoWrapperPass(TLII));
  396. // Add an appropriate DataLayout instance for this module.
  397. const DataLayout &DL = M->getDataLayout();
  398. if (DL.isDefault() && !DefaultDataLayout.empty()) {
  399. M->setDataLayout(DefaultDataLayout);
  400. }
  401. // Add internal analysis passes from the target machine.
  402. Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
  403. : TargetIRAnalysis()));
  404. std::unique_ptr<legacy::FunctionPassManager> FPasses;
  405. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  406. FPasses.reset(new legacy::FunctionPassManager(M.get()));
  407. FPasses->add(createTargetTransformInfoWrapperPass(
  408. TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
  409. }
  410. if (PrintBreakpoints) {
  411. // Default to standard output.
  412. if (!Out) {
  413. if (OutputFilename.empty())
  414. OutputFilename = "-";
  415. std::error_code EC;
  416. Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
  417. sys::fs::F_None);
  418. if (EC) {
  419. errs() << EC.message() << '\n';
  420. return 1;
  421. }
  422. }
  423. Passes.add(createBreakpointPrinter(Out->os()));
  424. NoOutput = true;
  425. }
  426. // Create a new optimization pass for each one specified on the command line
  427. for (unsigned i = 0; i < PassList.size(); ++i) {
  428. if (StandardLinkOpts &&
  429. StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
  430. AddStandardLinkPasses(Passes);
  431. StandardLinkOpts = false;
  432. }
  433. if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
  434. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  435. OptLevelO1 = false;
  436. }
  437. if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
  438. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  439. OptLevelO2 = false;
  440. }
  441. if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
  442. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  443. OptLevelOs = false;
  444. }
  445. if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
  446. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  447. OptLevelOz = false;
  448. }
  449. if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
  450. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  451. OptLevelO3 = false;
  452. }
  453. const PassInfo *PassInf = PassList[i];
  454. Pass *P = nullptr;
  455. if (PassInf->getTargetMachineCtor())
  456. P = PassInf->getTargetMachineCtor()(TM.get());
  457. else if (PassInf->getNormalCtor())
  458. P = PassInf->getNormalCtor()();
  459. else
  460. errs() << argv[0] << ": cannot create pass: "
  461. << PassInf->getPassName() << "\n";
  462. if (P) {
  463. PassKind Kind = P->getPassKind();
  464. addPass(Passes, P);
  465. if (AnalyzeOnly) {
  466. switch (Kind) {
  467. case PT_BasicBlock:
  468. Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
  469. break;
  470. case PT_Region:
  471. Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
  472. break;
  473. case PT_Loop:
  474. Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
  475. break;
  476. case PT_Function:
  477. Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
  478. break;
  479. case PT_CallGraphSCC:
  480. Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
  481. break;
  482. default:
  483. Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
  484. break;
  485. }
  486. }
  487. }
  488. if (PrintEachXForm)
  489. Passes.add(
  490. createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
  491. }
  492. if (StandardLinkOpts) {
  493. AddStandardLinkPasses(Passes);
  494. StandardLinkOpts = false;
  495. }
  496. if (OptLevelO1)
  497. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  498. if (OptLevelO2)
  499. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  500. if (OptLevelOs)
  501. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  502. if (OptLevelOz)
  503. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  504. if (OptLevelO3)
  505. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  506. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  507. FPasses->doInitialization();
  508. for (Function &F : *M)
  509. FPasses->run(F);
  510. FPasses->doFinalization();
  511. }
  512. // Check that the module is well formed on completion of optimization
  513. if (!NoVerify && !VerifyEach)
  514. Passes.add(createVerifierPass());
  515. // Write bitcode or assembly to the output as the last step...
  516. if (!NoOutput && !AnalyzeOnly) {
  517. if (OutputAssembly)
  518. Passes.add(
  519. createPrintModulePass(Out->os(), "", PreserveAssemblyUseListOrder));
  520. else
  521. Passes.add(
  522. createBitcodeWriterPass(Out->os(), PreserveBitcodeUseListOrder));
  523. }
  524. // Before executing passes, print the final values of the LLVM options.
  525. cl::PrintOptionValues();
  526. // Now that we have all of the passes ready, run them.
  527. // HLSL Change Starts - wrap in try-catch
  528. try {
  529. Passes.run(*M);
  530. }
  531. catch(...) {
  532. exit(1);
  533. }
  534. // HLSL Change Ends
  535. // Declare success.
  536. if (!NoOutput || PrintBreakpoints)
  537. Out->keep();
  538. return 0;
  539. }