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