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