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