xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 2bf7c51d)
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 
15 #include "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.inc"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/LegacyPassNameParser.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LinkAllIR.h"
39 #include "llvm/LinkAllPasses.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/InitLLVM.h"
45 #include "llvm/Support/PluginLoader.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/Support/YAMLTraits.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Transforms/Coroutines.h"
54 #include "llvm/Transforms/IPO/AlwaysInliner.h"
55 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 #include "llvm/Transforms/Utils/Cloning.h"
57 #include <algorithm>
58 #include <memory>
59 using namespace llvm;
60 using namespace opt_tool;
61 
62 // The OptimizationList is automatically populated with registered Passes by the
63 // PassNameParser.
64 //
65 static cl::list<const PassInfo*, bool, PassNameParser>
66 PassList(cl::desc("Optimizations available:"));
67 
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 
77 // Other command line options...
78 //
79 static cl::opt<std::string>
80 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
81     cl::init("-"), cl::value_desc("filename"));
82 
83 static cl::opt<std::string>
84 OutputFilename("o", cl::desc("Override output filename"),
85                cl::value_desc("filename"));
86 
87 static cl::opt<bool>
88 Force("f", cl::desc("Enable binary output on terminals"));
89 
90 static cl::opt<bool>
91 PrintEachXForm("p", cl::desc("Print module after each transformation"));
92 
93 static cl::opt<bool>
94 NoOutput("disable-output",
95          cl::desc("Do not write result bitcode file"), cl::Hidden);
96 
97 static cl::opt<bool>
98 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
99 
100 static cl::opt<bool>
101     OutputThinLTOBC("thinlto-bc",
102                     cl::desc("Write output as ThinLTO-ready bitcode"));
103 
104 static cl::opt<std::string> ThinLinkBitcodeFile(
105     "thin-link-bitcode-file", cl::value_desc("filename"),
106     cl::desc(
107         "A file in which to write minimized bitcode for the thin link only"));
108 
109 static cl::opt<bool>
110 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
111 
112 static cl::opt<bool>
113 VerifyEach("verify-each", cl::desc("Verify after each transform"));
114 
115 static cl::opt<bool>
116     DisableDITypeMap("disable-debug-info-type-map",
117                      cl::desc("Don't use a uniquing type map for debug info"));
118 
119 static cl::opt<bool>
120 StripDebug("strip-debug",
121            cl::desc("Strip debugger symbol info from translation unit"));
122 
123 static cl::opt<bool>
124 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
125 
126 static cl::opt<bool>
127 DisableOptimizations("disable-opt",
128                      cl::desc("Do not run any optimization passes"));
129 
130 static cl::opt<bool>
131 StandardLinkOpts("std-link-opts",
132                  cl::desc("Include the standard link time optimizations"));
133 
134 static cl::opt<bool>
135 OptLevelO0("O0",
136   cl::desc("Optimization level 0. Similar to clang -O0"));
137 
138 static cl::opt<bool>
139 OptLevelO1("O1",
140            cl::desc("Optimization level 1. Similar to clang -O1"));
141 
142 static cl::opt<bool>
143 OptLevelO2("O2",
144            cl::desc("Optimization level 2. Similar to clang -O2"));
145 
146 static cl::opt<bool>
147 OptLevelOs("Os",
148            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
149 
150 static cl::opt<bool>
151 OptLevelOz("Oz",
152            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
153 
154 static cl::opt<bool>
155 OptLevelO3("O3",
156            cl::desc("Optimization level 3. Similar to clang -O3"));
157 
158 static cl::opt<unsigned>
159 CodeGenOptLevel("codegen-opt-level",
160                 cl::desc("Override optimization level for codegen hooks"));
161 
162 static cl::opt<std::string>
163 TargetTriple("mtriple", cl::desc("Override target triple for module"));
164 
165 static cl::opt<bool>
166 UnitAtATime("funit-at-a-time",
167             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
168             cl::init(true));
169 
170 static cl::opt<bool>
171 DisableLoopUnrolling("disable-loop-unrolling",
172                      cl::desc("Disable loop unrolling in all relevant passes"),
173                      cl::init(false));
174 static cl::opt<bool>
175 DisableLoopVectorization("disable-loop-vectorization",
176                      cl::desc("Disable the loop vectorization pass"),
177                      cl::init(false));
178 
179 static cl::opt<bool>
180 DisableSLPVectorization("disable-slp-vectorization",
181                         cl::desc("Disable the slp vectorization pass"),
182                         cl::init(false));
183 
184 static cl::opt<bool> EmitSummaryIndex("module-summary",
185                                       cl::desc("Emit module summary index"),
186                                       cl::init(false));
187 
188 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
189                                     cl::init(false));
190 
191 static cl::opt<bool>
192 DisableSimplifyLibCalls("disable-simplify-libcalls",
193                         cl::desc("Disable simplify-libcalls"));
194 
195 static cl::opt<bool>
196 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
197 
198 static cl::alias
199 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
200 
201 static cl::opt<bool>
202 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
203 
204 static cl::opt<bool> EnableDebugify(
205     "enable-debugify",
206     cl::desc(
207         "Start the pipeline with debugify and end it with check-debugify"));
208 
209 static cl::opt<bool>
210 PrintBreakpoints("print-breakpoints-for-testing",
211                  cl::desc("Print select breakpoints location for testing"));
212 
213 static cl::opt<std::string> ClDataLayout("data-layout",
214                                          cl::desc("data layout string to use"),
215                                          cl::value_desc("layout-string"),
216                                          cl::init(""));
217 
218 static cl::opt<bool> PreserveBitcodeUseListOrder(
219     "preserve-bc-uselistorder",
220     cl::desc("Preserve use-list order when writing LLVM bitcode."),
221     cl::init(true), cl::Hidden);
222 
223 static cl::opt<bool> PreserveAssemblyUseListOrder(
224     "preserve-ll-uselistorder",
225     cl::desc("Preserve use-list order when writing LLVM assembly."),
226     cl::init(false), cl::Hidden);
227 
228 static cl::opt<bool>
229     RunTwice("run-twice",
230              cl::desc("Run all passes twice, re-using the same pass manager."),
231              cl::init(false), cl::Hidden);
232 
233 static cl::opt<bool> DiscardValueNames(
234     "discard-value-names",
235     cl::desc("Discard names from Value (other than GlobalValue)."),
236     cl::init(false), cl::Hidden);
237 
238 static cl::opt<bool> Coroutines(
239   "enable-coroutines",
240   cl::desc("Enable coroutine passes."),
241   cl::init(false), cl::Hidden);
242 
243 static cl::opt<bool> PassRemarksWithHotness(
244     "pass-remarks-with-hotness",
245     cl::desc("With PGO, include profile count in optimization remarks"),
246     cl::Hidden);
247 
248 static cl::opt<unsigned> PassRemarksHotnessThreshold(
249     "pass-remarks-hotness-threshold",
250     cl::desc("Minimum profile count required for an optimization remark to be output"),
251     cl::Hidden);
252 
253 static cl::opt<std::string>
254     RemarksFilename("pass-remarks-output",
255                     cl::desc("YAML output filename for pass remarks"),
256                     cl::value_desc("filename"));
257 
258 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
259   // Add the pass to the pass manager...
260   PM.add(P);
261 
262   // If we are verifying all of the intermediate steps, add the verifier...
263   if (VerifyEach)
264     PM.add(createVerifierPass());
265 }
266 
267 /// This routine adds optimization passes based on selected optimization level,
268 /// OptLevel.
269 ///
270 /// OptLevel - Optimization Level
271 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
272                                   legacy::FunctionPassManager &FPM,
273                                   TargetMachine *TM, unsigned OptLevel,
274                                   unsigned SizeLevel) {
275   if (!NoVerify || VerifyEach)
276     FPM.add(createVerifierPass()); // Verify that input is correct
277 
278   PassManagerBuilder Builder;
279   Builder.OptLevel = OptLevel;
280   Builder.SizeLevel = SizeLevel;
281 
282   if (DisableInline) {
283     // No inlining pass
284   } else if (OptLevel > 1) {
285     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
286   } else {
287     Builder.Inliner = createAlwaysInlinerLegacyPass();
288   }
289   Builder.DisableUnitAtATime = !UnitAtATime;
290   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
291                                DisableLoopUnrolling : OptLevel == 0;
292 
293   // This is final, unless there is a #pragma vectorize enable
294   if (DisableLoopVectorization)
295     Builder.LoopVectorize = false;
296   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
297   else if (!Builder.LoopVectorize)
298     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
299 
300   // When #pragma vectorize is on for SLP, do the same as above
301   Builder.SLPVectorize =
302       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
303 
304   if (TM)
305     TM->adjustPassManager(Builder);
306 
307   if (Coroutines)
308     addCoroutinePassesToExtensionPoints(Builder);
309 
310   Builder.populateFunctionPassManager(FPM);
311   Builder.populateModulePassManager(MPM);
312 }
313 
314 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
315   PassManagerBuilder Builder;
316   Builder.VerifyInput = true;
317   if (DisableOptimizations)
318     Builder.OptLevel = 0;
319 
320   if (!DisableInline)
321     Builder.Inliner = createFunctionInliningPass();
322   Builder.populateLTOPassManager(PM);
323 }
324 
325 //===----------------------------------------------------------------------===//
326 // CodeGen-related helper functions.
327 //
328 
329 static CodeGenOpt::Level GetCodeGenOptLevel() {
330   if (CodeGenOptLevel.getNumOccurrences())
331     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
332   if (OptLevelO1)
333     return CodeGenOpt::Less;
334   if (OptLevelO2)
335     return CodeGenOpt::Default;
336   if (OptLevelO3)
337     return CodeGenOpt::Aggressive;
338   return CodeGenOpt::None;
339 }
340 
341 // Returns the TargetMachine instance or zero if no triple is provided.
342 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
343                                        StringRef FeaturesStr,
344                                        const TargetOptions &Options) {
345   std::string Error;
346   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
347                                                          Error);
348   // Some modules don't specify a triple, and this is okay.
349   if (!TheTarget) {
350     return nullptr;
351   }
352 
353   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
354                                         FeaturesStr, Options, getRelocModel(),
355                                         getCodeModel(), GetCodeGenOptLevel());
356 }
357 
358 #ifdef LINK_POLLY_INTO_TOOLS
359 namespace polly {
360 void initializePollyPasses(llvm::PassRegistry &Registry);
361 }
362 #endif
363 
364 //===----------------------------------------------------------------------===//
365 // main for opt
366 //
367 int main(int argc, char **argv) {
368   InitLLVM X(argc, argv);
369 
370   // Enable debug stream buffering.
371   EnableDebugBuffering = true;
372 
373   LLVMContext Context;
374 
375   InitializeAllTargets();
376   InitializeAllTargetMCs();
377   InitializeAllAsmPrinters();
378   InitializeAllAsmParsers();
379 
380   // Initialize passes
381   PassRegistry &Registry = *PassRegistry::getPassRegistry();
382   initializeCore(Registry);
383   initializeCoroutines(Registry);
384   initializeScalarOpts(Registry);
385   initializeObjCARCOpts(Registry);
386   initializeVectorization(Registry);
387   initializeIPO(Registry);
388   initializeAnalysis(Registry);
389   initializeTransformUtils(Registry);
390   initializeInstCombine(Registry);
391   initializeAggressiveInstCombinerLegacyPassPass(Registry);
392   initializeInstrumentation(Registry);
393   initializeTarget(Registry);
394   // For codegen passes, only passes that do IR to IR transformation are
395   // supported.
396   initializeExpandMemCmpPassPass(Registry);
397   initializeScalarizeMaskedMemIntrinPass(Registry);
398   initializeCodeGenPreparePass(Registry);
399   initializeAtomicExpandPass(Registry);
400   initializeRewriteSymbolsLegacyPassPass(Registry);
401   initializeWinEHPreparePass(Registry);
402   initializeDwarfEHPreparePass(Registry);
403   initializeSafeStackLegacyPassPass(Registry);
404   initializeSjLjEHPreparePass(Registry);
405   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
406   initializeGlobalMergePass(Registry);
407   initializeIndirectBrExpandPassPass(Registry);
408   initializeInterleavedAccessPass(Registry);
409   initializeEntryExitInstrumenterPass(Registry);
410   initializePostInlineEntryExitInstrumenterPass(Registry);
411   initializeUnreachableBlockElimLegacyPassPass(Registry);
412   initializeExpandReductionsPass(Registry);
413   initializeWriteBitcodePassPass(Registry);
414 
415 #ifdef LINK_POLLY_INTO_TOOLS
416   polly::initializePollyPasses(Registry);
417 #endif
418 
419   cl::ParseCommandLineOptions(argc, argv,
420     "llvm .bc -> .bc modular optimizer and analysis printer\n");
421 
422   if (AnalyzeOnly && NoOutput) {
423     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
424     return 1;
425   }
426 
427   SMDiagnostic Err;
428 
429   Context.setDiscardValueNames(DiscardValueNames);
430   if (!DisableDITypeMap)
431     Context.enableDebugTypeODRUniquing();
432 
433   if (PassRemarksWithHotness)
434     Context.setDiagnosticsHotnessRequested(true);
435 
436   if (PassRemarksHotnessThreshold)
437     Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
438 
439   std::unique_ptr<ToolOutputFile> OptRemarkFile;
440   if (RemarksFilename != "") {
441     std::error_code EC;
442     OptRemarkFile =
443         llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
444     if (EC) {
445       errs() << EC.message() << '\n';
446       return 1;
447     }
448     Context.setDiagnosticsOutputFile(
449         llvm::make_unique<yaml::Output>(OptRemarkFile->os()));
450   }
451 
452   // Load the input module...
453   std::unique_ptr<Module> M =
454       parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
455 
456   if (!M) {
457     Err.print(argv[0], errs());
458     return 1;
459   }
460 
461   // Strip debug info before running the verifier.
462   if (StripDebug)
463     StripDebugInfo(*M);
464 
465   // If we are supposed to override the target triple or data layout, do so now.
466   if (!TargetTriple.empty())
467     M->setTargetTriple(Triple::normalize(TargetTriple));
468 
469   // Immediately run the verifier to catch any problems before starting up the
470   // pass pipelines.  Otherwise we can crash on broken code during
471   // doInitialization().
472   if (!NoVerify && verifyModule(*M, &errs())) {
473     errs() << argv[0] << ": " << InputFilename
474            << ": error: input module is broken!\n";
475     return 1;
476   }
477 
478   // Figure out what stream we are supposed to write to...
479   std::unique_ptr<ToolOutputFile> Out;
480   std::unique_ptr<ToolOutputFile> ThinLinkOut;
481   if (NoOutput) {
482     if (!OutputFilename.empty())
483       errs() << "WARNING: The -o (output filename) option is ignored when\n"
484                 "the --disable-output option is used.\n";
485   } else {
486     // Default to standard output.
487     if (OutputFilename.empty())
488       OutputFilename = "-";
489 
490     std::error_code EC;
491     Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
492     if (EC) {
493       errs() << EC.message() << '\n';
494       return 1;
495     }
496 
497     if (!ThinLinkBitcodeFile.empty()) {
498       ThinLinkOut.reset(
499           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::F_None));
500       if (EC) {
501         errs() << EC.message() << '\n';
502         return 1;
503       }
504     }
505   }
506 
507   Triple ModuleTriple(M->getTargetTriple());
508   std::string CPUStr, FeaturesStr;
509   TargetMachine *Machine = nullptr;
510   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
511 
512   if (ModuleTriple.getArch()) {
513     CPUStr = getCPUStr();
514     FeaturesStr = getFeaturesStr();
515     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
516   }
517 
518   std::unique_ptr<TargetMachine> TM(Machine);
519 
520   // Override function attributes based on CPUStr, FeaturesStr, and command line
521   // flags.
522   setFunctionAttributes(CPUStr, FeaturesStr, *M);
523 
524   // If the output is set to be emitted to standard out, and standard out is a
525   // console, print out a warning message and refuse to do it.  We don't
526   // impress anyone by spewing tons of binary goo to a terminal.
527   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
528     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
529       NoOutput = true;
530 
531   if (PassPipeline.getNumOccurrences() > 0) {
532     OutputKind OK = OK_NoOutput;
533     if (!NoOutput)
534       OK = OutputAssembly
535                ? OK_OutputAssembly
536                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
537 
538     VerifierKind VK = VK_VerifyInAndOut;
539     if (NoVerify)
540       VK = VK_NoVerifier;
541     else if (VerifyEach)
542       VK = VK_VerifyEachPass;
543 
544     // The user has asked to use the new pass manager and provided a pipeline
545     // string. Hand off the rest of the functionality to the new code for that
546     // layer.
547     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
548                            OptRemarkFile.get(), PassPipeline, OK, VK,
549                            PreserveAssemblyUseListOrder,
550                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
551                            EmitModuleHash, EnableDebugify)
552                ? 0
553                : 1;
554   }
555 
556   // Create a PassManager to hold and optimize the collection of passes we are
557   // about to build.
558   //
559   legacy::PassManager Passes;
560 
561   // Add an appropriate TargetLibraryInfo pass for the module's triple.
562   TargetLibraryInfoImpl TLII(ModuleTriple);
563 
564   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
565   if (DisableSimplifyLibCalls)
566     TLII.disableAllFunctions();
567   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
568 
569   // Add internal analysis passes from the target machine.
570   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
571                                                      : TargetIRAnalysis()));
572 
573   if (EnableDebugify)
574     Passes.add(createDebugifyPass());
575 
576   std::unique_ptr<legacy::FunctionPassManager> FPasses;
577   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
578       OptLevelO3) {
579     FPasses.reset(new legacy::FunctionPassManager(M.get()));
580     FPasses->add(createTargetTransformInfoWrapperPass(
581         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
582   }
583 
584   if (PrintBreakpoints) {
585     // Default to standard output.
586     if (!Out) {
587       if (OutputFilename.empty())
588         OutputFilename = "-";
589 
590       std::error_code EC;
591       Out = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
592                                               sys::fs::F_None);
593       if (EC) {
594         errs() << EC.message() << '\n';
595         return 1;
596       }
597     }
598     Passes.add(createBreakpointPrinter(Out->os()));
599     NoOutput = true;
600   }
601 
602   if (TM) {
603     // FIXME: We should dyn_cast this when supported.
604     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
605     Pass *TPC = LTM.createPassConfig(Passes);
606     Passes.add(TPC);
607   }
608 
609   // Create a new optimization pass for each one specified on the command line
610   for (unsigned i = 0; i < PassList.size(); ++i) {
611     if (StandardLinkOpts &&
612         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
613       AddStandardLinkPasses(Passes);
614       StandardLinkOpts = false;
615     }
616 
617     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
618       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
619       OptLevelO0 = false;
620     }
621 
622     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
623       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
624       OptLevelO1 = false;
625     }
626 
627     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
628       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
629       OptLevelO2 = false;
630     }
631 
632     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
633       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
634       OptLevelOs = false;
635     }
636 
637     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
638       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
639       OptLevelOz = false;
640     }
641 
642     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
643       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
644       OptLevelO3 = false;
645     }
646 
647     const PassInfo *PassInf = PassList[i];
648     Pass *P = nullptr;
649     if (PassInf->getNormalCtor())
650       P = PassInf->getNormalCtor()();
651     else
652       errs() << argv[0] << ": cannot create pass: "
653              << PassInf->getPassName() << "\n";
654     if (P) {
655       PassKind Kind = P->getPassKind();
656       addPass(Passes, P);
657 
658       if (AnalyzeOnly) {
659         switch (Kind) {
660         case PT_BasicBlock:
661           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
662           break;
663         case PT_Region:
664           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
665           break;
666         case PT_Loop:
667           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
668           break;
669         case PT_Function:
670           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
671           break;
672         case PT_CallGraphSCC:
673           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
674           break;
675         default:
676           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
677           break;
678         }
679       }
680     }
681 
682     if (PrintEachXForm)
683       Passes.add(
684           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
685   }
686 
687   if (StandardLinkOpts) {
688     AddStandardLinkPasses(Passes);
689     StandardLinkOpts = false;
690   }
691 
692   if (OptLevelO0)
693     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
694 
695   if (OptLevelO1)
696     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
697 
698   if (OptLevelO2)
699     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
700 
701   if (OptLevelOs)
702     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
703 
704   if (OptLevelOz)
705     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
706 
707   if (OptLevelO3)
708     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
709 
710   if (FPasses) {
711     FPasses->doInitialization();
712     for (Function &F : *M)
713       FPasses->run(F);
714     FPasses->doFinalization();
715   }
716 
717   // Check that the module is well formed on completion of optimization
718   if (!NoVerify && !VerifyEach)
719     Passes.add(createVerifierPass());
720 
721   if (EnableDebugify)
722     Passes.add(createCheckDebugifyPass());
723 
724   // In run twice mode, we want to make sure the output is bit-by-bit
725   // equivalent if we run the pass manager again, so setup two buffers and
726   // a stream to write to them. Note that llc does something similar and it
727   // may be worth to abstract this out in the future.
728   SmallVector<char, 0> Buffer;
729   SmallVector<char, 0> FirstRunBuffer;
730   std::unique_ptr<raw_svector_ostream> BOS;
731   raw_ostream *OS = nullptr;
732 
733   // Write bitcode or assembly to the output as the last step...
734   if (!NoOutput && !AnalyzeOnly) {
735     assert(Out);
736     OS = &Out->os();
737     if (RunTwice) {
738       BOS = make_unique<raw_svector_ostream>(Buffer);
739       OS = BOS.get();
740     }
741     if (OutputAssembly) {
742       if (EmitSummaryIndex)
743         report_fatal_error("Text output is incompatible with -module-summary");
744       if (EmitModuleHash)
745         report_fatal_error("Text output is incompatible with -module-hash");
746       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
747     } else if (OutputThinLTOBC)
748       Passes.add(createWriteThinLTOBitcodePass(
749           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
750     else
751       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
752                                          EmitSummaryIndex, EmitModuleHash));
753   }
754 
755   // Before executing passes, print the final values of the LLVM options.
756   cl::PrintOptionValues();
757 
758   if (!RunTwice) {
759     // Now that we have all of the passes ready, run them.
760     Passes.run(*M);
761   } else {
762     // If requested, run all passes twice with the same pass manager to catch
763     // bugs caused by persistent state in the passes.
764     std::unique_ptr<Module> M2(CloneModule(*M));
765     // Run all passes on the original module first, so the second run processes
766     // the clone to catch CloneModule bugs.
767     Passes.run(*M);
768     FirstRunBuffer = Buffer;
769     Buffer.clear();
770 
771     Passes.run(*M2);
772 
773     // Compare the two outputs and make sure they're the same
774     assert(Out);
775     if (Buffer.size() != FirstRunBuffer.size() ||
776         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
777       errs()
778           << "Running the pass manager twice changed the output.\n"
779              "Writing the result of the second run to the specified output.\n"
780              "To generate the one-run comparison binary, just run without\n"
781              "the compile-twice option\n";
782       Out->os() << BOS->str();
783       Out->keep();
784       if (OptRemarkFile)
785         OptRemarkFile->keep();
786       return 1;
787     }
788     Out->os() << BOS->str();
789   }
790 
791   // Declare success.
792   if (!NoOutput || PrintBreakpoints)
793     Out->keep();
794 
795   if (OptRemarkFile)
796     OptRemarkFile->keep();
797 
798   if (ThinLinkOut)
799     ThinLinkOut->keep();
800 
801   return 0;
802 }
803