xref: /llvm-project-15.0.7/llvm/tools/llc/llc.cpp (revision 8a42bf24)
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the llc code generator driver. It provides a convenient
10 // command-line interface for generating native assembly-language code
11 // or C code, given LLVM bitcode.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/CodeGen/MIRParser/MIRParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LLVMRemarkStreamer.h"
33 #include "llvm/IR/LegacyPassManager.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/MC/SubtargetFeature.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/PluginLoader.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/WithColor.h"
53 #include "llvm/Target/TargetLoweringObjectFile.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Transforms/Utils/Cloning.h"
56 #include <memory>
57 using namespace llvm;
58 
59 static codegen::RegisterCodeGenFlags CGF;
60 
61 // General options for llc.  Other pass-specific options are specified
62 // within the corresponding llc passes, and target-specific options
63 // and back-end code generation options are specified with the target machine.
64 //
65 static cl::opt<std::string>
66 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
67 
68 static cl::opt<std::string>
69 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
70 
71 static cl::opt<std::string>
72 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
73 
74 static cl::opt<std::string>
75     SplitDwarfOutputFile("split-dwarf-output",
76                          cl::desc(".dwo output filename"),
77                          cl::value_desc("filename"));
78 
79 static cl::opt<unsigned>
80 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
81                  cl::value_desc("N"),
82                  cl::desc("Repeat compilation N times for timing"));
83 
84 static cl::opt<bool>
85 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
86                       cl::desc("Disable integrated assembler"));
87 
88 static cl::opt<bool>
89     PreserveComments("preserve-as-comments", cl::Hidden,
90                      cl::desc("Preserve Comments in outputted assembly"),
91                      cl::init(true));
92 
93 // Determine optimization level.
94 static cl::opt<char>
95 OptLevel("O",
96          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
97                   "(default = '-O2')"),
98          cl::Prefix,
99          cl::ZeroOrMore,
100          cl::init(' '));
101 
102 static cl::opt<std::string>
103 TargetTriple("mtriple", cl::desc("Override target triple for module"));
104 
105 static cl::opt<std::string> SplitDwarfFile(
106     "split-dwarf-file",
107     cl::desc(
108         "Specify the name of the .dwo file to encode in the DWARF output"));
109 
110 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
111                               cl::desc("Do not verify input module"));
112 
113 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
114                                              cl::desc("Disable simplify-libcalls"));
115 
116 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
117                                     cl::desc("Show encoding in .s output"));
118 
119 static cl::opt<bool> EnableDwarfDirectory(
120     "enable-dwarf-directory", cl::Hidden,
121     cl::desc("Use .file directives with an explicit directory."));
122 
123 static cl::opt<bool> AsmVerbose("asm-verbose",
124                                 cl::desc("Add comments to directives."),
125                                 cl::init(true));
126 
127 static cl::opt<bool>
128     CompileTwice("compile-twice", cl::Hidden,
129                  cl::desc("Run everything twice, re-using the same pass "
130                           "manager and verify the result is the same."),
131                  cl::init(false));
132 
133 static cl::opt<bool> DiscardValueNames(
134     "discard-value-names",
135     cl::desc("Discard names from Value (other than GlobalValue)."),
136     cl::init(false), cl::Hidden);
137 
138 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
139 
140 static cl::opt<bool> RemarksWithHotness(
141     "pass-remarks-with-hotness",
142     cl::desc("With PGO, include profile count in optimization remarks"),
143     cl::Hidden);
144 
145 static cl::opt<unsigned>
146     RemarksHotnessThreshold("pass-remarks-hotness-threshold",
147                             cl::desc("Minimum profile count required for "
148                                      "an optimization remark to be output"),
149                             cl::Hidden);
150 
151 static cl::opt<std::string>
152     RemarksFilename("pass-remarks-output",
153                     cl::desc("Output filename for pass remarks"),
154                     cl::value_desc("filename"));
155 
156 static cl::opt<std::string>
157     RemarksPasses("pass-remarks-filter",
158                   cl::desc("Only record optimization remarks from passes whose "
159                            "names match the given regular expression"),
160                   cl::value_desc("regex"));
161 
162 static cl::opt<std::string> RemarksFormat(
163     "pass-remarks-format",
164     cl::desc("The format used for serializing remarks (default: YAML)"),
165     cl::value_desc("format"), cl::init("yaml"));
166 
167 namespace {
168 static ManagedStatic<std::vector<std::string>> RunPassNames;
169 
170 struct RunPassOption {
171   void operator=(const std::string &Val) const {
172     if (Val.empty())
173       return;
174     SmallVector<StringRef, 8> PassNames;
175     StringRef(Val).split(PassNames, ',', -1, false);
176     for (auto PassName : PassNames)
177       RunPassNames->push_back(std::string(PassName));
178   }
179 };
180 }
181 
182 static RunPassOption RunPassOpt;
183 
184 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
185     "run-pass",
186     cl::desc("Run compiler only for specified passes (comma separated list)"),
187     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
188 
189 static int compileModule(char **, LLVMContext &);
190 
191 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
192                                                        Triple::OSType OS,
193                                                        const char *ProgName) {
194   // If we don't yet have an output filename, make one.
195   if (OutputFilename.empty()) {
196     if (InputFilename == "-")
197       OutputFilename = "-";
198     else {
199       // If InputFilename ends in .bc or .ll, remove it.
200       StringRef IFN = InputFilename;
201       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
202         OutputFilename = std::string(IFN.drop_back(3));
203       else if (IFN.endswith(".mir"))
204         OutputFilename = std::string(IFN.drop_back(4));
205       else
206         OutputFilename = std::string(IFN);
207 
208       switch (codegen::getFileType()) {
209       case CGFT_AssemblyFile:
210         if (TargetName[0] == 'c') {
211           if (TargetName[1] == 0)
212             OutputFilename += ".cbe.c";
213           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
214             OutputFilename += ".cpp";
215           else
216             OutputFilename += ".s";
217         } else
218           OutputFilename += ".s";
219         break;
220       case CGFT_ObjectFile:
221         if (OS == Triple::Win32)
222           OutputFilename += ".obj";
223         else
224           OutputFilename += ".o";
225         break;
226       case CGFT_Null:
227         OutputFilename += ".null";
228         break;
229       }
230     }
231   }
232 
233   // Decide if we need "binary" output.
234   bool Binary = false;
235   switch (codegen::getFileType()) {
236   case CGFT_AssemblyFile:
237     break;
238   case CGFT_ObjectFile:
239   case CGFT_Null:
240     Binary = true;
241     break;
242   }
243 
244   // Open the file.
245   std::error_code EC;
246   sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
247   if (!Binary)
248     OpenFlags |= sys::fs::OF_Text;
249   auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
250   if (EC) {
251     WithColor::error() << EC.message() << '\n';
252     return nullptr;
253   }
254 
255   return FDOut;
256 }
257 
258 struct LLCDiagnosticHandler : public DiagnosticHandler {
259   bool *HasError;
260   LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
261   bool handleDiagnostics(const DiagnosticInfo &DI) override {
262     if (DI.getSeverity() == DS_Error)
263       *HasError = true;
264 
265     if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
266       if (!Remark->isEnabled())
267         return true;
268 
269     DiagnosticPrinterRawOStream DP(errs());
270     errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
271     DI.print(DP);
272     errs() << "\n";
273     return true;
274   }
275 };
276 
277 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
278                                  unsigned LocCookie) {
279   bool *HasError = static_cast<bool *>(Context);
280   if (SMD.getKind() == SourceMgr::DK_Error)
281     *HasError = true;
282 
283   SMD.print(nullptr, errs());
284 
285   // For testing purposes, we print the LocCookie here.
286   if (LocCookie)
287     WithColor::note() << "!srcloc = " << LocCookie << "\n";
288 }
289 
290 // main - Entry point for the llc compiler.
291 //
292 int main(int argc, char **argv) {
293   InitLLVM X(argc, argv);
294 
295   // Enable debug stream buffering.
296   EnableDebugBuffering = true;
297 
298   LLVMContext Context;
299 
300   // Initialize targets first, so that --version shows registered targets.
301   InitializeAllTargets();
302   InitializeAllTargetMCs();
303   InitializeAllAsmPrinters();
304   InitializeAllAsmParsers();
305 
306   // Initialize codegen and IR passes used by llc so that the -print-after,
307   // -print-before, and -stop-after options work.
308   PassRegistry *Registry = PassRegistry::getPassRegistry();
309   initializeCore(*Registry);
310   initializeCodeGen(*Registry);
311   initializeLoopStrengthReducePass(*Registry);
312   initializeLowerIntrinsicsPass(*Registry);
313   initializeEntryExitInstrumenterPass(*Registry);
314   initializePostInlineEntryExitInstrumenterPass(*Registry);
315   initializeUnreachableBlockElimLegacyPassPass(*Registry);
316   initializeConstantHoistingLegacyPassPass(*Registry);
317   initializeScalarOpts(*Registry);
318   initializeVectorization(*Registry);
319   initializeScalarizeMaskedMemIntrinPass(*Registry);
320   initializeExpandReductionsPass(*Registry);
321   initializeHardwareLoopsPass(*Registry);
322   initializeTransformUtils(*Registry);
323 
324   // Initialize debugging passes.
325   initializeScavengerTestPass(*Registry);
326 
327   // Register the target printer for --version.
328   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
329 
330   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
331 
332   Context.setDiscardValueNames(DiscardValueNames);
333 
334   // Set a diagnostic handler that doesn't exit on the first error
335   bool HasError = false;
336   Context.setDiagnosticHandler(
337       std::make_unique<LLCDiagnosticHandler>(&HasError));
338   Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
339 
340   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
341       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
342                                    RemarksFormat, RemarksWithHotness,
343                                    RemarksHotnessThreshold);
344   if (Error E = RemarksFileOrErr.takeError()) {
345     WithColor::error(errs(), argv[0]) << toString(std::move(E)) << '\n';
346     return 1;
347   }
348   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
349 
350   if (InputLanguage != "" && InputLanguage != "ir" &&
351       InputLanguage != "mir") {
352     WithColor::error(errs(), argv[0])
353         << "input language must be '', 'IR' or 'MIR'\n";
354     return 1;
355   }
356 
357   // Compile the module TimeCompilations times to give better compile time
358   // metrics.
359   for (unsigned I = TimeCompilations; I; --I)
360     if (int RetVal = compileModule(argv, Context))
361       return RetVal;
362 
363   if (RemarksFile)
364     RemarksFile->keep();
365   return 0;
366 }
367 
368 static bool addPass(PassManagerBase &PM, const char *argv0,
369                     StringRef PassName, TargetPassConfig &TPC) {
370   if (PassName == "none")
371     return false;
372 
373   const PassRegistry *PR = PassRegistry::getPassRegistry();
374   const PassInfo *PI = PR->getPassInfo(PassName);
375   if (!PI) {
376     WithColor::error(errs(), argv0)
377         << "run-pass " << PassName << " is not registered.\n";
378     return true;
379   }
380 
381   Pass *P;
382   if (PI->getNormalCtor())
383     P = PI->getNormalCtor()();
384   else {
385     WithColor::error(errs(), argv0)
386         << "cannot create pass: " << PI->getPassName() << "\n";
387     return true;
388   }
389   std::string Banner = std::string("After ") + std::string(P->getPassName());
390   PM.add(P);
391   TPC.printAndVerify(Banner);
392 
393   return false;
394 }
395 
396 static int compileModule(char **argv, LLVMContext &Context) {
397   // Load the module to be compiled...
398   SMDiagnostic Err;
399   std::unique_ptr<Module> M;
400   std::unique_ptr<MIRParser> MIR;
401   Triple TheTriple;
402   std::string CPUStr = codegen::getCPUStr(),
403               FeaturesStr = codegen::getFeaturesStr();
404 
405   // Set attributes on functions as loaded from MIR from command line arguments.
406   auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
407     codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
408   };
409 
410   auto MAttrs = codegen::getMAttrs();
411   bool SkipModule = codegen::getMCPU() == "help" ||
412                     (!MAttrs.empty() && MAttrs.front() == "help");
413 
414   // If user just wants to list available options, skip module loading
415   if (!SkipModule) {
416     if (InputLanguage == "mir" ||
417         (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
418       MIR = createMIRParserFromFile(InputFilename, Err, Context,
419                                     setMIRFunctionAttributes);
420       if (MIR)
421         M = MIR->parseIRModule();
422     } else
423       M = parseIRFile(InputFilename, Err, Context, false);
424     if (!M) {
425       Err.print(argv[0], WithColor::error(errs(), argv[0]));
426       return 1;
427     }
428 
429     // If we are supposed to override the target triple, do so now.
430     if (!TargetTriple.empty())
431       M->setTargetTriple(Triple::normalize(TargetTriple));
432     TheTriple = Triple(M->getTargetTriple());
433   } else {
434     TheTriple = Triple(Triple::normalize(TargetTriple));
435   }
436 
437   if (TheTriple.getTriple().empty())
438     TheTriple.setTriple(sys::getDefaultTargetTriple());
439 
440   // Get the target specific parser.
441   std::string Error;
442   const Target *TheTarget =
443       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
444   if (!TheTarget) {
445     WithColor::error(errs(), argv[0]) << Error;
446     return 1;
447   }
448 
449   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
450   switch (OptLevel) {
451   default:
452     WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
453     return 1;
454   case ' ': break;
455   case '0': OLvl = CodeGenOpt::None; break;
456   case '1': OLvl = CodeGenOpt::Less; break;
457   case '2': OLvl = CodeGenOpt::Default; break;
458   case '3': OLvl = CodeGenOpt::Aggressive; break;
459   }
460 
461   TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
462   Options.DisableIntegratedAS = NoIntegratedAssembler;
463   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
464   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
465   Options.MCOptions.AsmVerbose = AsmVerbose;
466   Options.MCOptions.PreserveAsmComments = PreserveComments;
467   Options.MCOptions.IASSearchPaths = IncludeDirs;
468   Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
469 
470   // On AIX, setting the relocation model to anything other than PIC is considered
471   // a user error.
472   Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
473   if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
474     WithColor::error(errs(), argv[0])
475         << "invalid relocation model, AIX only supports PIC.\n";
476     return 1;
477   }
478 
479   std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
480       TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
481       codegen::getExplicitCodeModel(), OLvl));
482 
483   assert(Target && "Could not allocate target machine!");
484 
485   // If we don't have a module then just exit now. We do this down
486   // here since the CPU/Feature help is underneath the target machine
487   // creation.
488   if (SkipModule)
489     return 0;
490 
491   assert(M && "Should have exited if we didn't have a module!");
492   if (codegen::getFloatABIForCalls() != FloatABI::Default)
493     Options.FloatABIType = codegen::getFloatABIForCalls();
494 
495   // Figure out where we are going to send the output.
496   std::unique_ptr<ToolOutputFile> Out =
497       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
498   if (!Out) return 1;
499 
500   std::unique_ptr<ToolOutputFile> DwoOut;
501   if (!SplitDwarfOutputFile.empty()) {
502     std::error_code EC;
503     DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
504                                                sys::fs::OF_None);
505     if (EC) {
506       WithColor::error(errs(), argv[0]) << EC.message() << '\n';
507       return 1;
508     }
509   }
510 
511   // Build up all of the passes that we want to do to the module.
512   legacy::PassManager PM;
513 
514   // Add an appropriate TargetLibraryInfo pass for the module's triple.
515   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
516 
517   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
518   if (DisableSimplifyLibCalls)
519     TLII.disableAllFunctions();
520   PM.add(new TargetLibraryInfoWrapperPass(TLII));
521 
522   // Add the target data from the target machine, if it exists, or the module.
523   M->setDataLayout(Target->createDataLayout());
524 
525   // This needs to be done after setting datalayout since it calls verifier
526   // to check debug info whereas verifier relies on correct datalayout.
527   UpgradeDebugInfo(*M);
528 
529   // Verify module immediately to catch problems before doInitialization() is
530   // called on any passes.
531   if (!NoVerify && verifyModule(*M, &errs())) {
532     std::string Prefix =
533         (Twine(argv[0]) + Twine(": ") + Twine(InputFilename)).str();
534     WithColor::error(errs(), Prefix) << "input module is broken!\n";
535     return 1;
536   }
537 
538   // Override function attributes based on CPUStr, FeaturesStr, and command line
539   // flags.
540   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
541 
542   if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
543     WithColor::warning(errs(), argv[0])
544         << ": warning: ignoring -mc-relax-all because filetype != obj";
545 
546   {
547     raw_pwrite_stream *OS = &Out->os();
548 
549     // Manually do the buffering rather than using buffer_ostream,
550     // so we can memcmp the contents in CompileTwice mode
551     SmallVector<char, 0> Buffer;
552     std::unique_ptr<raw_svector_ostream> BOS;
553     if ((codegen::getFileType() != CGFT_AssemblyFile &&
554          !Out->os().supportsSeeking()) ||
555         CompileTwice) {
556       BOS = std::make_unique<raw_svector_ostream>(Buffer);
557       OS = BOS.get();
558     }
559 
560     const char *argv0 = argv[0];
561     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
562     MachineModuleInfoWrapperPass *MMIWP =
563         new MachineModuleInfoWrapperPass(&LLVMTM);
564 
565     // Construct a custom pass pipeline that starts after instruction
566     // selection.
567     if (!RunPassNames->empty()) {
568       if (!MIR) {
569         WithColor::warning(errs(), argv[0])
570             << "run-pass is for .mir file only.\n";
571         return 1;
572       }
573       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
574       if (TPC.hasLimitedCodeGenPipeline()) {
575         WithColor::warning(errs(), argv[0])
576             << "run-pass cannot be used with "
577             << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
578         return 1;
579       }
580 
581       TPC.setDisableVerify(NoVerify);
582       PM.add(&TPC);
583       PM.add(MMIWP);
584       TPC.printAndVerify("");
585       for (const std::string &RunPassName : *RunPassNames) {
586         if (addPass(PM, argv0, RunPassName, TPC))
587           return 1;
588       }
589       TPC.setInitialized();
590       PM.add(createPrintMIRPass(*OS));
591       PM.add(createFreeMachineFunctionPass());
592     } else if (Target->addPassesToEmitFile(
593                    PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
594                    codegen::getFileType(), NoVerify, MMIWP)) {
595       WithColor::warning(errs(), argv[0])
596           << "target does not support generation of this"
597           << " file type!\n";
598       return 1;
599     }
600 
601     const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
602         ->Initialize(MMIWP->getMMI().getContext(), *Target);
603     if (MIR) {
604       assert(MMIWP && "Forgot to create MMIWP?");
605       if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
606         return 1;
607     }
608 
609     // Before executing passes, print the final values of the LLVM options.
610     cl::PrintOptionValues();
611 
612     // If requested, run the pass manager over the same module again,
613     // to catch any bugs due to persistent state in the passes. Note that
614     // opt has the same functionality, so it may be worth abstracting this out
615     // in the future.
616     SmallVector<char, 0> CompileTwiceBuffer;
617     if (CompileTwice) {
618       std::unique_ptr<Module> M2(llvm::CloneModule(*M));
619       PM.run(*M2);
620       CompileTwiceBuffer = Buffer;
621       Buffer.clear();
622     }
623 
624     PM.run(*M);
625 
626     auto HasError =
627         ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
628     if (*HasError)
629       return 1;
630 
631     // Compare the two outputs and make sure they're the same
632     if (CompileTwice) {
633       if (Buffer.size() != CompileTwiceBuffer.size() ||
634           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
635            0)) {
636         errs()
637             << "Running the pass manager twice changed the output.\n"
638                "Writing the result of the second run to the specified output\n"
639                "To generate the one-run comparison binary, just run without\n"
640                "the compile-twice option\n";
641         Out->os() << Buffer;
642         Out->keep();
643         return 1;
644       }
645     }
646 
647     if (BOS) {
648       Out->os() << Buffer;
649     }
650   }
651 
652   // Declare success.
653   Out->keep();
654   if (DwoOut)
655     DwoOut->keep();
656 
657   return 0;
658 }
659