opt.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. llvm::sys::fs::MSFileSystem* msfPtr;
  254. if (FAILED(CreateMSFileSystemForDisk(&msfPtr))) return 1;
  255. std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr);
  256. llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
  257. //llvm::STDStreamCloser stdStreamCloser;
  258. // HLSL Change Ends
  259. //sys::PrintStackTraceOnErrorSignal(); // HLSL Change
  260. //llvm::PrettyStackTraceProgram X(argc, argv); // HLSL Change
  261. // Enable debug stream buffering.
  262. EnableDebugBuffering = true;
  263. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  264. LLVMContext &Context = getGlobalContext();
  265. InitializeAllTargets();
  266. // InitializeAllTargetMCs(); // HLSL Change: remove MC targets
  267. InitializeAllAsmPrinters();
  268. // Initialize passes
  269. PassRegistry &Registry = *PassRegistry::getPassRegistry();
  270. initializeCore(Registry);
  271. initializeScalarOpts(Registry);
  272. initializeReducibilityAnalysisPass(Registry); // HLSL Change: add ReducibilityAnalysis pass
  273. // initializeObjCARCOpts(Registry); // HLSL Change: remove ObjC ARC passes
  274. // initializeVectorization(Registry); // HLSL Change: remove vectorization passes
  275. initializeIPO(Registry);
  276. initializeAnalysis(Registry);
  277. initializeIPA(Registry);
  278. initializeTransformUtils(Registry);
  279. initializeInstCombine(Registry);
  280. // initializeInstrumentation(Registry); // HLSL Change: remove instrumentation
  281. initializeTarget(Registry);
  282. // For codegen passes, only passes that do IR to IR transformation are
  283. // supported.
  284. // initializeCodeGenPreparePass(Registry); // HLSL Change: remove EH passes
  285. //initializeAtomicExpandPass(Registry); // HLSL Change: remove EH passes
  286. initializeRewriteSymbolsPass(Registry);
  287. //initializeWinEHPreparePass(Registry); // HLSL Change: remove EH passes
  288. //initializeDwarfEHPreparePass(Registry); // HLSL Change: remove EH passes
  289. //initializeSjLjEHPreparePass(Registry); // HLSL Change: remove EH passes
  290. // MS Change Starts
  291. initializeReducibilityAnalysisPass(Registry);
  292. #if HLSL_INTERNAL
  293. void initializeHlslInternalPasses(PassRegistry &);
  294. initializeHlslInternalPasses(Registry);
  295. #endif
  296. // MS Change Ends
  297. #ifdef LINK_POLLY_INTO_TOOLS
  298. polly::initializePollyPasses(Registry);
  299. #endif
  300. cl::ParseCommandLineOptions(argc, argv,
  301. "llvm .bc -> .bc modular optimizer and analysis printer\n");
  302. if (AnalyzeOnly && NoOutput) {
  303. errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
  304. return 1;
  305. }
  306. SMDiagnostic Err;
  307. // Load the input module...
  308. std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
  309. if (!M) {
  310. Err.print(argv[0], errs());
  311. return 1;
  312. }
  313. // Strip debug info before running the verifier.
  314. if (StripDebug)
  315. StripDebugInfo(*M);
  316. // Immediately run the verifier to catch any problems before starting up the
  317. // pass pipelines. Otherwise we can crash on broken code during
  318. // doInitialization().
  319. if (!NoVerify && verifyModule(*M, &errs())) {
  320. errs() << argv[0] << ": " << InputFilename
  321. << ": error: input module is broken!\n";
  322. return 1;
  323. }
  324. // If we are supposed to override the target triple, do so now.
  325. if (!TargetTriple.empty())
  326. M->setTargetTriple(Triple::normalize(TargetTriple));
  327. // Figure out what stream we are supposed to write to...
  328. std::unique_ptr<tool_output_file> Out;
  329. if (NoOutput) {
  330. if (!OutputFilename.empty())
  331. errs() << "WARNING: The -o (output filename) option is ignored when\n"
  332. "the --disable-output option is used.\n";
  333. } else {
  334. // Default to standard output.
  335. if (OutputFilename.empty())
  336. OutputFilename = "-";
  337. std::error_code EC;
  338. Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
  339. if (EC) {
  340. errs() << EC.message() << '\n';
  341. return 1;
  342. }
  343. }
  344. Triple ModuleTriple(M->getTargetTriple());
  345. std::string CPUStr, FeaturesStr;
  346. TargetMachine *Machine = nullptr;
  347. const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  348. if (ModuleTriple.getArch()) {
  349. CPUStr = getCPUStr();
  350. FeaturesStr = getFeaturesStr();
  351. Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
  352. }
  353. std::unique_ptr<TargetMachine> TM(Machine);
  354. // Override function attributes based on CPUStr, FeaturesStr, and command line
  355. // flags.
  356. setFunctionAttributes(CPUStr, FeaturesStr, *M);
  357. // If the output is set to be emitted to standard out, and standard out is a
  358. // console, print out a warning message and refuse to do it. We don't
  359. // impress anyone by spewing tons of binary goo to a terminal.
  360. if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
  361. if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
  362. NoOutput = true;
  363. if (PassPipeline.getNumOccurrences() > 0) {
  364. OutputKind OK = OK_NoOutput;
  365. if (!NoOutput)
  366. OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
  367. VerifierKind VK = VK_VerifyInAndOut;
  368. if (NoVerify)
  369. VK = VK_NoVerifier;
  370. else if (VerifyEach)
  371. VK = VK_VerifyEachPass;
  372. // The user has asked to use the new pass manager and provided a pipeline
  373. // string. Hand off the rest of the functionality to the new code for that
  374. // layer.
  375. return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
  376. PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
  377. PreserveBitcodeUseListOrder)
  378. ? 0
  379. : 1;
  380. }
  381. // Create a PassManager to hold and optimize the collection of passes we are
  382. // about to build.
  383. //
  384. legacy::PassManager Passes;
  385. // Add an appropriate TargetLibraryInfo pass for the module's triple.
  386. TargetLibraryInfoImpl TLII(ModuleTriple);
  387. // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  388. if (DisableSimplifyLibCalls)
  389. TLII.disableAllFunctions();
  390. Passes.add(new TargetLibraryInfoWrapperPass(TLII));
  391. // Add an appropriate DataLayout instance for this module.
  392. const DataLayout &DL = M->getDataLayout();
  393. if (DL.isDefault() && !DefaultDataLayout.empty()) {
  394. M->setDataLayout(DefaultDataLayout);
  395. }
  396. // Add internal analysis passes from the target machine.
  397. Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
  398. : TargetIRAnalysis()));
  399. std::unique_ptr<legacy::FunctionPassManager> FPasses;
  400. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  401. FPasses.reset(new legacy::FunctionPassManager(M.get()));
  402. FPasses->add(createTargetTransformInfoWrapperPass(
  403. TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
  404. }
  405. if (PrintBreakpoints) {
  406. // Default to standard output.
  407. if (!Out) {
  408. if (OutputFilename.empty())
  409. OutputFilename = "-";
  410. std::error_code EC;
  411. Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
  412. sys::fs::F_None);
  413. if (EC) {
  414. errs() << EC.message() << '\n';
  415. return 1;
  416. }
  417. }
  418. Passes.add(createBreakpointPrinter(Out->os()));
  419. NoOutput = true;
  420. }
  421. // Create a new optimization pass for each one specified on the command line
  422. for (unsigned i = 0; i < PassList.size(); ++i) {
  423. if (StandardLinkOpts &&
  424. StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
  425. AddStandardLinkPasses(Passes);
  426. StandardLinkOpts = false;
  427. }
  428. if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
  429. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  430. OptLevelO1 = false;
  431. }
  432. if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
  433. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  434. OptLevelO2 = false;
  435. }
  436. if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
  437. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  438. OptLevelOs = false;
  439. }
  440. if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
  441. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  442. OptLevelOz = false;
  443. }
  444. if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
  445. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  446. OptLevelO3 = false;
  447. }
  448. const PassInfo *PassInf = PassList[i];
  449. Pass *P = nullptr;
  450. if (PassInf->getTargetMachineCtor())
  451. P = PassInf->getTargetMachineCtor()(TM.get());
  452. else if (PassInf->getNormalCtor())
  453. P = PassInf->getNormalCtor()();
  454. else
  455. errs() << argv[0] << ": cannot create pass: "
  456. << PassInf->getPassName() << "\n";
  457. if (P) {
  458. PassKind Kind = P->getPassKind();
  459. addPass(Passes, P);
  460. if (AnalyzeOnly) {
  461. switch (Kind) {
  462. case PT_BasicBlock:
  463. Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
  464. break;
  465. case PT_Region:
  466. Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
  467. break;
  468. case PT_Loop:
  469. Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
  470. break;
  471. case PT_Function:
  472. Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
  473. break;
  474. case PT_CallGraphSCC:
  475. Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
  476. break;
  477. default:
  478. Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
  479. break;
  480. }
  481. }
  482. }
  483. if (PrintEachXForm)
  484. Passes.add(
  485. createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
  486. }
  487. if (StandardLinkOpts) {
  488. AddStandardLinkPasses(Passes);
  489. StandardLinkOpts = false;
  490. }
  491. if (OptLevelO1)
  492. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  493. if (OptLevelO2)
  494. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  495. if (OptLevelOs)
  496. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  497. if (OptLevelOz)
  498. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  499. if (OptLevelO3)
  500. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  501. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  502. FPasses->doInitialization();
  503. for (Function &F : *M)
  504. FPasses->run(F);
  505. FPasses->doFinalization();
  506. }
  507. // Check that the module is well formed on completion of optimization
  508. if (!NoVerify && !VerifyEach)
  509. Passes.add(createVerifierPass());
  510. // Write bitcode or assembly to the output as the last step...
  511. if (!NoOutput && !AnalyzeOnly) {
  512. if (OutputAssembly)
  513. Passes.add(
  514. createPrintModulePass(Out->os(), "", PreserveAssemblyUseListOrder));
  515. else
  516. Passes.add(
  517. createBitcodeWriterPass(Out->os(), PreserveBitcodeUseListOrder));
  518. }
  519. // Before executing passes, print the final values of the LLVM options.
  520. cl::PrintOptionValues();
  521. // Now that we have all of the passes ready, run them.
  522. // HLSL Change Starts - wrap in try-catch
  523. try {
  524. Passes.run(*M);
  525. }
  526. catch(...) {
  527. exit(1);
  528. }
  529. // HLSL Change Ends
  530. // Declare success.
  531. if (!NoOutput || PrintBreakpoints)
  532. Out->keep();
  533. return 0;
  534. }