xref: /freebsd/contrib/llvm-project/llvm/tools/llc/llc.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
10b57cec5SDimitry Andric //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This is the llc code generator driver. It provides a convenient
100b57cec5SDimitry Andric // command-line interface for generating native assembly-language code
110b57cec5SDimitry Andric // or C code, given LLVM bitcode.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
185ffd83dbSDimitry Andric #include "llvm/CodeGen/CommandFlags.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllCodegenComponents.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MIRParser/MIRParser.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
260b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
270b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
280b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
290b57cec5SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
300b57cec5SDimitry Andric #include "llvm/IR/IRPrintingPasses.h"
310b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
325ffd83dbSDimitry Andric #include "llvm/IR/LLVMRemarkStreamer.h"
330b57cec5SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
340b57cec5SDimitry Andric #include "llvm/IR/Module.h"
350b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
360b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
37480093f4SDimitry Andric #include "llvm/InitializePasses.h"
380b57cec5SDimitry Andric #include "llvm/MC/SubtargetFeature.h"
390b57cec5SDimitry Andric #include "llvm/Pass.h"
40e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
410b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
420b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
430b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
440b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
450b57cec5SDimitry Andric #include "llvm/Support/Host.h"
460b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h"
470b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
480b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h"
490b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
500b57cec5SDimitry Andric #include "llvm/Support/TargetRegistry.h"
510b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
520b57cec5SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
530b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
545ffd83dbSDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
550b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
560b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
570b57cec5SDimitry Andric #include <memory>
580b57cec5SDimitry Andric using namespace llvm;
590b57cec5SDimitry Andric 
605ffd83dbSDimitry Andric static codegen::RegisterCodeGenFlags CGF;
615ffd83dbSDimitry Andric 
620b57cec5SDimitry Andric // General options for llc.  Other pass-specific options are specified
630b57cec5SDimitry Andric // within the corresponding llc passes, and target-specific options
640b57cec5SDimitry Andric // and back-end code generation options are specified with the target machine.
650b57cec5SDimitry Andric //
660b57cec5SDimitry Andric static cl::opt<std::string>
670b57cec5SDimitry Andric InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric static cl::opt<std::string>
700b57cec5SDimitry Andric InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static cl::opt<std::string>
730b57cec5SDimitry Andric OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static cl::opt<std::string>
760b57cec5SDimitry Andric     SplitDwarfOutputFile("split-dwarf-output",
770b57cec5SDimitry Andric                          cl::desc(".dwo output filename"),
780b57cec5SDimitry Andric                          cl::value_desc("filename"));
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric static cl::opt<unsigned>
810b57cec5SDimitry Andric TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
820b57cec5SDimitry Andric                  cl::value_desc("N"),
830b57cec5SDimitry Andric                  cl::desc("Repeat compilation N times for timing"));
840b57cec5SDimitry Andric 
85e8d8bef9SDimitry Andric static cl::opt<std::string>
86e8d8bef9SDimitry Andric     BinutilsVersion("binutils-version", cl::Hidden,
87e8d8bef9SDimitry Andric                     cl::desc("Produced object files can use all ELF features "
88e8d8bef9SDimitry Andric                              "supported by this binutils version and newer."
89e8d8bef9SDimitry Andric                              "If -no-integrated-as is specified, the generated "
90e8d8bef9SDimitry Andric                              "assembly will consider GNU as support."
91e8d8bef9SDimitry Andric                              "'none' means that all ELF features can be used, "
92e8d8bef9SDimitry Andric                              "regardless of binutils support"));
93e8d8bef9SDimitry Andric 
940b57cec5SDimitry Andric static cl::opt<bool>
950b57cec5SDimitry Andric NoIntegratedAssembler("no-integrated-as", cl::Hidden,
960b57cec5SDimitry Andric                       cl::desc("Disable integrated assembler"));
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric static cl::opt<bool>
990b57cec5SDimitry Andric     PreserveComments("preserve-as-comments", cl::Hidden,
1000b57cec5SDimitry Andric                      cl::desc("Preserve Comments in outputted assembly"),
1010b57cec5SDimitry Andric                      cl::init(true));
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric // Determine optimization level.
1040b57cec5SDimitry Andric static cl::opt<char>
1050b57cec5SDimitry Andric OptLevel("O",
1060b57cec5SDimitry Andric          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
1070b57cec5SDimitry Andric                   "(default = '-O2')"),
1080b57cec5SDimitry Andric          cl::Prefix,
1090b57cec5SDimitry Andric          cl::ZeroOrMore,
1100b57cec5SDimitry Andric          cl::init(' '));
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric static cl::opt<std::string>
1130b57cec5SDimitry Andric TargetTriple("mtriple", cl::desc("Override target triple for module"));
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric static cl::opt<std::string> SplitDwarfFile(
1160b57cec5SDimitry Andric     "split-dwarf-file",
1170b57cec5SDimitry Andric     cl::desc(
1180b57cec5SDimitry Andric         "Specify the name of the .dwo file to encode in the DWARF output"));
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
1210b57cec5SDimitry Andric                               cl::desc("Do not verify input module"));
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
1240b57cec5SDimitry Andric                                              cl::desc("Disable simplify-libcalls"));
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
1270b57cec5SDimitry Andric                                     cl::desc("Show encoding in .s output"));
1280b57cec5SDimitry Andric 
129*fe6060f1SDimitry Andric static cl::opt<bool>
130*fe6060f1SDimitry Andric     DwarfDirectory("dwarf-directory", cl::Hidden,
131*fe6060f1SDimitry Andric                    cl::desc("Use .file directives with an explicit directory"),
132*fe6060f1SDimitry Andric                    cl::init(true));
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric static cl::opt<bool> AsmVerbose("asm-verbose",
1350b57cec5SDimitry Andric                                 cl::desc("Add comments to directives."),
1360b57cec5SDimitry Andric                                 cl::init(true));
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric static cl::opt<bool>
1390b57cec5SDimitry Andric     CompileTwice("compile-twice", cl::Hidden,
1400b57cec5SDimitry Andric                  cl::desc("Run everything twice, re-using the same pass "
1410b57cec5SDimitry Andric                           "manager and verify the result is the same."),
1420b57cec5SDimitry Andric                  cl::init(false));
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric static cl::opt<bool> DiscardValueNames(
1450b57cec5SDimitry Andric     "discard-value-names",
1460b57cec5SDimitry Andric     cl::desc("Discard names from Value (other than GlobalValue)."),
1470b57cec5SDimitry Andric     cl::init(false), cl::Hidden);
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric static cl::opt<bool> RemarksWithHotness(
1520b57cec5SDimitry Andric     "pass-remarks-with-hotness",
1530b57cec5SDimitry Andric     cl::desc("With PGO, include profile count in optimization remarks"),
1540b57cec5SDimitry Andric     cl::Hidden);
1550b57cec5SDimitry Andric 
156e8d8bef9SDimitry Andric static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
157e8d8bef9SDimitry Andric     RemarksHotnessThreshold(
158e8d8bef9SDimitry Andric         "pass-remarks-hotness-threshold",
1590b57cec5SDimitry Andric         cl::desc("Minimum profile count required for "
160e8d8bef9SDimitry Andric                  "an optimization remark to be output. "
161e8d8bef9SDimitry Andric                  "Use 'auto' to apply the threshold from profile summary."),
162e8d8bef9SDimitry Andric         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric static cl::opt<std::string>
1650b57cec5SDimitry Andric     RemarksFilename("pass-remarks-output",
1660b57cec5SDimitry Andric                     cl::desc("Output filename for pass remarks"),
1670b57cec5SDimitry Andric                     cl::value_desc("filename"));
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric static cl::opt<std::string>
1700b57cec5SDimitry Andric     RemarksPasses("pass-remarks-filter",
1710b57cec5SDimitry Andric                   cl::desc("Only record optimization remarks from passes whose "
1720b57cec5SDimitry Andric                            "names match the given regular expression"),
1730b57cec5SDimitry Andric                   cl::value_desc("regex"));
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric static cl::opt<std::string> RemarksFormat(
1760b57cec5SDimitry Andric     "pass-remarks-format",
1770b57cec5SDimitry Andric     cl::desc("The format used for serializing remarks (default: YAML)"),
1780b57cec5SDimitry Andric     cl::value_desc("format"), cl::init("yaml"));
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric namespace {
1810b57cec5SDimitry Andric static ManagedStatic<std::vector<std::string>> RunPassNames;
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric struct RunPassOption {
1840b57cec5SDimitry Andric   void operator=(const std::string &Val) const {
1850b57cec5SDimitry Andric     if (Val.empty())
1860b57cec5SDimitry Andric       return;
1870b57cec5SDimitry Andric     SmallVector<StringRef, 8> PassNames;
1880b57cec5SDimitry Andric     StringRef(Val).split(PassNames, ',', -1, false);
1890b57cec5SDimitry Andric     for (auto PassName : PassNames)
1905ffd83dbSDimitry Andric       RunPassNames->push_back(std::string(PassName));
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric };
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric static RunPassOption RunPassOpt;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
1980b57cec5SDimitry Andric     "run-pass",
1990b57cec5SDimitry Andric     cl::desc("Run compiler only for specified passes (comma separated list)"),
2000b57cec5SDimitry Andric     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric static int compileModule(char **, LLVMContext &);
2030b57cec5SDimitry Andric 
204e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_NORETURN static void reportError(Twine Msg,
205e8d8bef9SDimitry Andric                                                 StringRef Filename = "") {
206e8d8bef9SDimitry Andric   SmallString<256> Prefix;
207e8d8bef9SDimitry Andric   if (!Filename.empty()) {
208e8d8bef9SDimitry Andric     if (Filename == "-")
209e8d8bef9SDimitry Andric       Filename = "<stdin>";
210e8d8bef9SDimitry Andric     ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
211e8d8bef9SDimitry Andric   }
212e8d8bef9SDimitry Andric   WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
213e8d8bef9SDimitry Andric   exit(1);
214e8d8bef9SDimitry Andric }
215e8d8bef9SDimitry Andric 
216e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_NORETURN static void reportError(Error Err, StringRef Filename) {
217e8d8bef9SDimitry Andric   assert(Err);
218e8d8bef9SDimitry Andric   handleAllErrors(createFileError(Filename, std::move(Err)),
219e8d8bef9SDimitry Andric                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
220e8d8bef9SDimitry Andric   llvm_unreachable("reportError() should not return");
221e8d8bef9SDimitry Andric }
222e8d8bef9SDimitry Andric 
2230b57cec5SDimitry Andric static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
2240b57cec5SDimitry Andric                                                        Triple::OSType OS,
2250b57cec5SDimitry Andric                                                        const char *ProgName) {
2260b57cec5SDimitry Andric   // If we don't yet have an output filename, make one.
2270b57cec5SDimitry Andric   if (OutputFilename.empty()) {
2280b57cec5SDimitry Andric     if (InputFilename == "-")
2290b57cec5SDimitry Andric       OutputFilename = "-";
2300b57cec5SDimitry Andric     else {
2310b57cec5SDimitry Andric       // If InputFilename ends in .bc or .ll, remove it.
2320b57cec5SDimitry Andric       StringRef IFN = InputFilename;
2330b57cec5SDimitry Andric       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
2345ffd83dbSDimitry Andric         OutputFilename = std::string(IFN.drop_back(3));
2350b57cec5SDimitry Andric       else if (IFN.endswith(".mir"))
2365ffd83dbSDimitry Andric         OutputFilename = std::string(IFN.drop_back(4));
2370b57cec5SDimitry Andric       else
2385ffd83dbSDimitry Andric         OutputFilename = std::string(IFN);
2390b57cec5SDimitry Andric 
2405ffd83dbSDimitry Andric       switch (codegen::getFileType()) {
241480093f4SDimitry Andric       case CGFT_AssemblyFile:
2420b57cec5SDimitry Andric         if (TargetName[0] == 'c') {
2430b57cec5SDimitry Andric           if (TargetName[1] == 0)
2440b57cec5SDimitry Andric             OutputFilename += ".cbe.c";
2450b57cec5SDimitry Andric           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
2460b57cec5SDimitry Andric             OutputFilename += ".cpp";
2470b57cec5SDimitry Andric           else
2480b57cec5SDimitry Andric             OutputFilename += ".s";
2490b57cec5SDimitry Andric         } else
2500b57cec5SDimitry Andric           OutputFilename += ".s";
2510b57cec5SDimitry Andric         break;
252480093f4SDimitry Andric       case CGFT_ObjectFile:
2530b57cec5SDimitry Andric         if (OS == Triple::Win32)
2540b57cec5SDimitry Andric           OutputFilename += ".obj";
2550b57cec5SDimitry Andric         else
2560b57cec5SDimitry Andric           OutputFilename += ".o";
2570b57cec5SDimitry Andric         break;
258480093f4SDimitry Andric       case CGFT_Null:
259e8d8bef9SDimitry Andric         OutputFilename = "-";
2600b57cec5SDimitry Andric         break;
2610b57cec5SDimitry Andric       }
2620b57cec5SDimitry Andric     }
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   // Decide if we need "binary" output.
2660b57cec5SDimitry Andric   bool Binary = false;
2675ffd83dbSDimitry Andric   switch (codegen::getFileType()) {
268480093f4SDimitry Andric   case CGFT_AssemblyFile:
2690b57cec5SDimitry Andric     break;
270480093f4SDimitry Andric   case CGFT_ObjectFile:
271480093f4SDimitry Andric   case CGFT_Null:
2720b57cec5SDimitry Andric     Binary = true;
2730b57cec5SDimitry Andric     break;
2740b57cec5SDimitry Andric   }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   // Open the file.
2770b57cec5SDimitry Andric   std::error_code EC;
2788bcb0991SDimitry Andric   sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
2790b57cec5SDimitry Andric   if (!Binary)
280*fe6060f1SDimitry Andric     OpenFlags |= sys::fs::OF_TextWithCRLF;
2818bcb0991SDimitry Andric   auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
2820b57cec5SDimitry Andric   if (EC) {
283e8d8bef9SDimitry Andric     reportError(EC.message());
2840b57cec5SDimitry Andric     return nullptr;
2850b57cec5SDimitry Andric   }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   return FDOut;
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric struct LLCDiagnosticHandler : public DiagnosticHandler {
2910b57cec5SDimitry Andric   bool *HasError;
2920b57cec5SDimitry Andric   LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
2930b57cec5SDimitry Andric   bool handleDiagnostics(const DiagnosticInfo &DI) override {
294*fe6060f1SDimitry Andric     if (DI.getKind() == llvm::DK_SrcMgr) {
295*fe6060f1SDimitry Andric       const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
296*fe6060f1SDimitry Andric       const SMDiagnostic &SMD = DISM.getSMDiag();
297*fe6060f1SDimitry Andric 
298*fe6060f1SDimitry Andric       if (SMD.getKind() == SourceMgr::DK_Error)
299*fe6060f1SDimitry Andric         *HasError = true;
300*fe6060f1SDimitry Andric 
301*fe6060f1SDimitry Andric       SMD.print(nullptr, errs());
302*fe6060f1SDimitry Andric 
303*fe6060f1SDimitry Andric       // For testing purposes, we print the LocCookie here.
304*fe6060f1SDimitry Andric       if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
305*fe6060f1SDimitry Andric         WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
306*fe6060f1SDimitry Andric 
307*fe6060f1SDimitry Andric       return true;
308*fe6060f1SDimitry Andric     }
309*fe6060f1SDimitry Andric 
3100b57cec5SDimitry Andric     if (DI.getSeverity() == DS_Error)
3110b57cec5SDimitry Andric       *HasError = true;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric     if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
3140b57cec5SDimitry Andric       if (!Remark->isEnabled())
3150b57cec5SDimitry Andric         return true;
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric     DiagnosticPrinterRawOStream DP(errs());
3180b57cec5SDimitry Andric     errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
3190b57cec5SDimitry Andric     DI.print(DP);
3200b57cec5SDimitry Andric     errs() << "\n";
3210b57cec5SDimitry Andric     return true;
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric };
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric // main - Entry point for the llc compiler.
3260b57cec5SDimitry Andric //
3270b57cec5SDimitry Andric int main(int argc, char **argv) {
3280b57cec5SDimitry Andric   InitLLVM X(argc, argv);
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric   // Enable debug stream buffering.
3310b57cec5SDimitry Andric   EnableDebugBuffering = true;
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   LLVMContext Context;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric   // Initialize targets first, so that --version shows registered targets.
3360b57cec5SDimitry Andric   InitializeAllTargets();
3370b57cec5SDimitry Andric   InitializeAllTargetMCs();
3380b57cec5SDimitry Andric   InitializeAllAsmPrinters();
3390b57cec5SDimitry Andric   InitializeAllAsmParsers();
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   // Initialize codegen and IR passes used by llc so that the -print-after,
3420b57cec5SDimitry Andric   // -print-before, and -stop-after options work.
3430b57cec5SDimitry Andric   PassRegistry *Registry = PassRegistry::getPassRegistry();
3440b57cec5SDimitry Andric   initializeCore(*Registry);
3450b57cec5SDimitry Andric   initializeCodeGen(*Registry);
3460b57cec5SDimitry Andric   initializeLoopStrengthReducePass(*Registry);
3470b57cec5SDimitry Andric   initializeLowerIntrinsicsPass(*Registry);
3480b57cec5SDimitry Andric   initializeEntryExitInstrumenterPass(*Registry);
3490b57cec5SDimitry Andric   initializePostInlineEntryExitInstrumenterPass(*Registry);
3500b57cec5SDimitry Andric   initializeUnreachableBlockElimLegacyPassPass(*Registry);
3510b57cec5SDimitry Andric   initializeConstantHoistingLegacyPassPass(*Registry);
3520b57cec5SDimitry Andric   initializeScalarOpts(*Registry);
3530b57cec5SDimitry Andric   initializeVectorization(*Registry);
354e8d8bef9SDimitry Andric   initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
3550b57cec5SDimitry Andric   initializeExpandReductionsPass(*Registry);
356*fe6060f1SDimitry Andric   initializeExpandVectorPredicationPass(*Registry);
3570b57cec5SDimitry Andric   initializeHardwareLoopsPass(*Registry);
3585ffd83dbSDimitry Andric   initializeTransformUtils(*Registry);
359*fe6060f1SDimitry Andric   initializeReplaceWithVeclibLegacyPass(*Registry);
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // Initialize debugging passes.
3620b57cec5SDimitry Andric   initializeScavengerTestPass(*Registry);
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Register the target printer for --version.
3650b57cec5SDimitry Andric   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   Context.setDiscardValueNames(DiscardValueNames);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Set a diagnostic handler that doesn't exit on the first error
3720b57cec5SDimitry Andric   bool HasError = false;
3730b57cec5SDimitry Andric   Context.setDiagnosticHandler(
3748bcb0991SDimitry Andric       std::make_unique<LLCDiagnosticHandler>(&HasError));
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
3775ffd83dbSDimitry Andric       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
3780b57cec5SDimitry Andric                                    RemarksFormat, RemarksWithHotness,
3790b57cec5SDimitry Andric                                    RemarksHotnessThreshold);
380e8d8bef9SDimitry Andric   if (Error E = RemarksFileOrErr.takeError())
381e8d8bef9SDimitry Andric     reportError(std::move(E), RemarksFilename);
3820b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
3830b57cec5SDimitry Andric 
384e8d8bef9SDimitry Andric   if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
385e8d8bef9SDimitry Andric     reportError("input language must be '', 'IR' or 'MIR'");
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   // Compile the module TimeCompilations times to give better compile time
3880b57cec5SDimitry Andric   // metrics.
3890b57cec5SDimitry Andric   for (unsigned I = TimeCompilations; I; --I)
3900b57cec5SDimitry Andric     if (int RetVal = compileModule(argv, Context))
3910b57cec5SDimitry Andric       return RetVal;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   if (RemarksFile)
3940b57cec5SDimitry Andric     RemarksFile->keep();
3950b57cec5SDimitry Andric   return 0;
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric static bool addPass(PassManagerBase &PM, const char *argv0,
3990b57cec5SDimitry Andric                     StringRef PassName, TargetPassConfig &TPC) {
4000b57cec5SDimitry Andric   if (PassName == "none")
4010b57cec5SDimitry Andric     return false;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   const PassRegistry *PR = PassRegistry::getPassRegistry();
4040b57cec5SDimitry Andric   const PassInfo *PI = PR->getPassInfo(PassName);
4050b57cec5SDimitry Andric   if (!PI) {
4060b57cec5SDimitry Andric     WithColor::error(errs(), argv0)
4070b57cec5SDimitry Andric         << "run-pass " << PassName << " is not registered.\n";
4080b57cec5SDimitry Andric     return true;
4090b57cec5SDimitry Andric   }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   Pass *P;
4120b57cec5SDimitry Andric   if (PI->getNormalCtor())
4130b57cec5SDimitry Andric     P = PI->getNormalCtor()();
4140b57cec5SDimitry Andric   else {
4150b57cec5SDimitry Andric     WithColor::error(errs(), argv0)
4160b57cec5SDimitry Andric         << "cannot create pass: " << PI->getPassName() << "\n";
4170b57cec5SDimitry Andric     return true;
4180b57cec5SDimitry Andric   }
4190b57cec5SDimitry Andric   std::string Banner = std::string("After ") + std::string(P->getPassName());
4205ffd83dbSDimitry Andric   TPC.addMachinePrePasses();
4210b57cec5SDimitry Andric   PM.add(P);
4225ffd83dbSDimitry Andric   TPC.addMachinePostPasses(Banner);
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   return false;
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric static int compileModule(char **argv, LLVMContext &Context) {
4280b57cec5SDimitry Andric   // Load the module to be compiled...
4290b57cec5SDimitry Andric   SMDiagnostic Err;
4300b57cec5SDimitry Andric   std::unique_ptr<Module> M;
4310b57cec5SDimitry Andric   std::unique_ptr<MIRParser> MIR;
4320b57cec5SDimitry Andric   Triple TheTriple;
4335ffd83dbSDimitry Andric   std::string CPUStr = codegen::getCPUStr(),
4345ffd83dbSDimitry Andric               FeaturesStr = codegen::getFeaturesStr();
435480093f4SDimitry Andric 
436480093f4SDimitry Andric   // Set attributes on functions as loaded from MIR from command line arguments.
437480093f4SDimitry Andric   auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
4385ffd83dbSDimitry Andric     codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
439480093f4SDimitry Andric   };
4400b57cec5SDimitry Andric 
4415ffd83dbSDimitry Andric   auto MAttrs = codegen::getMAttrs();
4425ffd83dbSDimitry Andric   bool SkipModule = codegen::getMCPU() == "help" ||
4430b57cec5SDimitry Andric                     (!MAttrs.empty() && MAttrs.front() == "help");
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
4460b57cec5SDimitry Andric   switch (OptLevel) {
4470b57cec5SDimitry Andric   default:
4480b57cec5SDimitry Andric     WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
4490b57cec5SDimitry Andric     return 1;
4500b57cec5SDimitry Andric   case ' ': break;
4510b57cec5SDimitry Andric   case '0': OLvl = CodeGenOpt::None; break;
4520b57cec5SDimitry Andric   case '1': OLvl = CodeGenOpt::Less; break;
4530b57cec5SDimitry Andric   case '2': OLvl = CodeGenOpt::Default; break;
4540b57cec5SDimitry Andric   case '3': OLvl = CodeGenOpt::Aggressive; break;
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric 
457e8d8bef9SDimitry Andric   // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
458e8d8bef9SDimitry Andric   // use that to indicate the MC default.
459e8d8bef9SDimitry Andric   if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
460e8d8bef9SDimitry Andric     StringRef V = BinutilsVersion.getValue();
461e8d8bef9SDimitry Andric     unsigned Num;
462e8d8bef9SDimitry Andric     if (V.consumeInteger(10, Num) || Num == 0 ||
463e8d8bef9SDimitry Andric         !(V.empty() ||
464e8d8bef9SDimitry Andric           (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
465e8d8bef9SDimitry Andric       WithColor::error(errs(), argv[0])
466e8d8bef9SDimitry Andric           << "invalid -binutils-version, accepting 'none' or major.minor\n";
467e8d8bef9SDimitry Andric       return 1;
468e8d8bef9SDimitry Andric     }
469e8d8bef9SDimitry Andric   }
470e8d8bef9SDimitry Andric   TargetOptions Options;
471e8d8bef9SDimitry Andric   auto InitializeOptions = [&](const Triple &TheTriple) {
472e8d8bef9SDimitry Andric     Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
473e8d8bef9SDimitry Andric     Options.BinutilsVersion =
474e8d8bef9SDimitry Andric         TargetMachine::parseBinutilsVersion(BinutilsVersion);
4750b57cec5SDimitry Andric     Options.DisableIntegratedAS = NoIntegratedAssembler;
4760b57cec5SDimitry Andric     Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
477*fe6060f1SDimitry Andric     Options.MCOptions.MCUseDwarfDirectory = DwarfDirectory;
4780b57cec5SDimitry Andric     Options.MCOptions.AsmVerbose = AsmVerbose;
4790b57cec5SDimitry Andric     Options.MCOptions.PreserveAsmComments = PreserveComments;
4800b57cec5SDimitry Andric     Options.MCOptions.IASSearchPaths = IncludeDirs;
4810b57cec5SDimitry Andric     Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
482e8d8bef9SDimitry Andric   };
4830b57cec5SDimitry Andric 
4845ffd83dbSDimitry Andric   Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
4850b57cec5SDimitry Andric 
4865ffd83dbSDimitry Andric   const Target *TheTarget = nullptr;
4875ffd83dbSDimitry Andric   std::unique_ptr<TargetMachine> Target;
4885ffd83dbSDimitry Andric 
4895ffd83dbSDimitry Andric   // If user just wants to list available options, skip module loading
4905ffd83dbSDimitry Andric   if (!SkipModule) {
4915ffd83dbSDimitry Andric     auto SetDataLayout =
4925ffd83dbSDimitry Andric         [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
4935ffd83dbSDimitry Andric       // If we are supposed to override the target triple, do so now.
4945ffd83dbSDimitry Andric       std::string IRTargetTriple = DataLayoutTargetTriple.str();
4955ffd83dbSDimitry Andric       if (!TargetTriple.empty())
4965ffd83dbSDimitry Andric         IRTargetTriple = Triple::normalize(TargetTriple);
4975ffd83dbSDimitry Andric       TheTriple = Triple(IRTargetTriple);
4985ffd83dbSDimitry Andric       if (TheTriple.getTriple().empty())
4995ffd83dbSDimitry Andric         TheTriple.setTriple(sys::getDefaultTargetTriple());
5005ffd83dbSDimitry Andric 
5015ffd83dbSDimitry Andric       std::string Error;
5025ffd83dbSDimitry Andric       TheTarget =
5035ffd83dbSDimitry Andric           TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
5045ffd83dbSDimitry Andric       if (!TheTarget) {
5055ffd83dbSDimitry Andric         WithColor::error(errs(), argv[0]) << Error;
5065ffd83dbSDimitry Andric         exit(1);
5075ffd83dbSDimitry Andric       }
5085ffd83dbSDimitry Andric 
5095ffd83dbSDimitry Andric       // On AIX, setting the relocation model to anything other than PIC is
5105ffd83dbSDimitry Andric       // considered a user error.
511e8d8bef9SDimitry Andric       if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
512e8d8bef9SDimitry Andric         reportError("invalid relocation model, AIX only supports PIC",
513e8d8bef9SDimitry Andric                     InputFilename);
5145ffd83dbSDimitry Andric 
515e8d8bef9SDimitry Andric       InitializeOptions(TheTriple);
5165ffd83dbSDimitry Andric       Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
5175ffd83dbSDimitry Andric           TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
5185ffd83dbSDimitry Andric           codegen::getExplicitCodeModel(), OLvl));
5195ffd83dbSDimitry Andric       assert(Target && "Could not allocate target machine!");
5205ffd83dbSDimitry Andric 
5215ffd83dbSDimitry Andric       return Target->createDataLayout().getStringRepresentation();
5225ffd83dbSDimitry Andric     };
5235ffd83dbSDimitry Andric     if (InputLanguage == "mir" ||
5245ffd83dbSDimitry Andric         (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
5255ffd83dbSDimitry Andric       MIR = createMIRParserFromFile(InputFilename, Err, Context,
5265ffd83dbSDimitry Andric                                     setMIRFunctionAttributes);
5275ffd83dbSDimitry Andric       if (MIR)
5285ffd83dbSDimitry Andric         M = MIR->parseIRModule(SetDataLayout);
5295ffd83dbSDimitry Andric     } else {
5305ffd83dbSDimitry Andric       M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
5315ffd83dbSDimitry Andric     }
5325ffd83dbSDimitry Andric     if (!M) {
5335ffd83dbSDimitry Andric       Err.print(argv[0], WithColor::error(errs(), argv[0]));
5345ffd83dbSDimitry Andric       return 1;
5355ffd83dbSDimitry Andric     }
5365ffd83dbSDimitry Andric     if (!TargetTriple.empty())
5375ffd83dbSDimitry Andric       M->setTargetTriple(Triple::normalize(TargetTriple));
5385ffd83dbSDimitry Andric   } else {
5395ffd83dbSDimitry Andric     TheTriple = Triple(Triple::normalize(TargetTriple));
5405ffd83dbSDimitry Andric     if (TheTriple.getTriple().empty())
5415ffd83dbSDimitry Andric       TheTriple.setTriple(sys::getDefaultTargetTriple());
5425ffd83dbSDimitry Andric 
5435ffd83dbSDimitry Andric     // Get the target specific parser.
5445ffd83dbSDimitry Andric     std::string Error;
5455ffd83dbSDimitry Andric     TheTarget =
5465ffd83dbSDimitry Andric         TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
5475ffd83dbSDimitry Andric     if (!TheTarget) {
5485ffd83dbSDimitry Andric       WithColor::error(errs(), argv[0]) << Error;
5495ffd83dbSDimitry Andric       return 1;
5505ffd83dbSDimitry Andric     }
5515ffd83dbSDimitry Andric 
5525ffd83dbSDimitry Andric     // On AIX, setting the relocation model to anything other than PIC is
5535ffd83dbSDimitry Andric     // considered a user error.
5545ffd83dbSDimitry Andric     if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
5555ffd83dbSDimitry Andric       WithColor::error(errs(), argv[0])
5565ffd83dbSDimitry Andric           << "invalid relocation model, AIX only supports PIC.\n";
5575ffd83dbSDimitry Andric       return 1;
5585ffd83dbSDimitry Andric     }
5595ffd83dbSDimitry Andric 
560e8d8bef9SDimitry Andric     InitializeOptions(TheTriple);
5615ffd83dbSDimitry Andric     Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
5625ffd83dbSDimitry Andric         TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
5635ffd83dbSDimitry Andric         codegen::getExplicitCodeModel(), OLvl));
5640b57cec5SDimitry Andric     assert(Target && "Could not allocate target machine!");
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric     // If we don't have a module then just exit now. We do this down
5670b57cec5SDimitry Andric     // here since the CPU/Feature help is underneath the target machine
5680b57cec5SDimitry Andric     // creation.
5690b57cec5SDimitry Andric     return 0;
5705ffd83dbSDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   assert(M && "Should have exited if we didn't have a module!");
5735ffd83dbSDimitry Andric   if (codegen::getFloatABIForCalls() != FloatABI::Default)
5745ffd83dbSDimitry Andric     Options.FloatABIType = codegen::getFloatABIForCalls();
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   // Figure out where we are going to send the output.
5770b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> Out =
5780b57cec5SDimitry Andric       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
5790b57cec5SDimitry Andric   if (!Out) return 1;
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> DwoOut;
5820b57cec5SDimitry Andric   if (!SplitDwarfOutputFile.empty()) {
5830b57cec5SDimitry Andric     std::error_code EC;
5848bcb0991SDimitry Andric     DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
5858bcb0991SDimitry Andric                                                sys::fs::OF_None);
586e8d8bef9SDimitry Andric     if (EC)
587e8d8bef9SDimitry Andric       reportError(EC.message(), SplitDwarfOutputFile);
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   // Build up all of the passes that we want to do to the module.
5910b57cec5SDimitry Andric   legacy::PassManager PM;
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   // Add an appropriate TargetLibraryInfo pass for the module's triple.
5940b57cec5SDimitry Andric   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
5970b57cec5SDimitry Andric   if (DisableSimplifyLibCalls)
5980b57cec5SDimitry Andric     TLII.disableAllFunctions();
5990b57cec5SDimitry Andric   PM.add(new TargetLibraryInfoWrapperPass(TLII));
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   // Verify module immediately to catch problems before doInitialization() is
6020b57cec5SDimitry Andric   // called on any passes.
603e8d8bef9SDimitry Andric   if (!NoVerify && verifyModule(*M, &errs()))
604e8d8bef9SDimitry Andric     reportError("input module cannot be verified", InputFilename);
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   // Override function attributes based on CPUStr, FeaturesStr, and command line
6070b57cec5SDimitry Andric   // flags.
6085ffd83dbSDimitry Andric   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
6090b57cec5SDimitry Andric 
6105ffd83dbSDimitry Andric   if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
6110b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
6120b57cec5SDimitry Andric         << ": warning: ignoring -mc-relax-all because filetype != obj";
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   {
6150b57cec5SDimitry Andric     raw_pwrite_stream *OS = &Out->os();
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric     // Manually do the buffering rather than using buffer_ostream,
6180b57cec5SDimitry Andric     // so we can memcmp the contents in CompileTwice mode
6190b57cec5SDimitry Andric     SmallVector<char, 0> Buffer;
6200b57cec5SDimitry Andric     std::unique_ptr<raw_svector_ostream> BOS;
6215ffd83dbSDimitry Andric     if ((codegen::getFileType() != CGFT_AssemblyFile &&
6220b57cec5SDimitry Andric          !Out->os().supportsSeeking()) ||
6230b57cec5SDimitry Andric         CompileTwice) {
6248bcb0991SDimitry Andric       BOS = std::make_unique<raw_svector_ostream>(Buffer);
6250b57cec5SDimitry Andric       OS = BOS.get();
6260b57cec5SDimitry Andric     }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     const char *argv0 = argv[0];
6290b57cec5SDimitry Andric     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
6308bcb0991SDimitry Andric     MachineModuleInfoWrapperPass *MMIWP =
6318bcb0991SDimitry Andric         new MachineModuleInfoWrapperPass(&LLVMTM);
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric     // Construct a custom pass pipeline that starts after instruction
6340b57cec5SDimitry Andric     // selection.
6350b57cec5SDimitry Andric     if (!RunPassNames->empty()) {
6360b57cec5SDimitry Andric       if (!MIR) {
6370b57cec5SDimitry Andric         WithColor::warning(errs(), argv[0])
6380b57cec5SDimitry Andric             << "run-pass is for .mir file only.\n";
6390b57cec5SDimitry Andric         return 1;
6400b57cec5SDimitry Andric       }
6410b57cec5SDimitry Andric       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
6420b57cec5SDimitry Andric       if (TPC.hasLimitedCodeGenPipeline()) {
6430b57cec5SDimitry Andric         WithColor::warning(errs(), argv[0])
6440b57cec5SDimitry Andric             << "run-pass cannot be used with "
6450b57cec5SDimitry Andric             << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
6460b57cec5SDimitry Andric         return 1;
6470b57cec5SDimitry Andric       }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric       TPC.setDisableVerify(NoVerify);
6500b57cec5SDimitry Andric       PM.add(&TPC);
6518bcb0991SDimitry Andric       PM.add(MMIWP);
6520b57cec5SDimitry Andric       TPC.printAndVerify("");
6530b57cec5SDimitry Andric       for (const std::string &RunPassName : *RunPassNames) {
6540b57cec5SDimitry Andric         if (addPass(PM, argv0, RunPassName, TPC))
6550b57cec5SDimitry Andric           return 1;
6560b57cec5SDimitry Andric       }
6570b57cec5SDimitry Andric       TPC.setInitialized();
6580b57cec5SDimitry Andric       PM.add(createPrintMIRPass(*OS));
6590b57cec5SDimitry Andric       PM.add(createFreeMachineFunctionPass());
6605ffd83dbSDimitry Andric     } else if (Target->addPassesToEmitFile(
6615ffd83dbSDimitry Andric                    PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
6625ffd83dbSDimitry Andric                    codegen::getFileType(), NoVerify, MMIWP)) {
663e8d8bef9SDimitry Andric       reportError("target does not support generation of this file type");
6640b57cec5SDimitry Andric     }
6650b57cec5SDimitry Andric 
6665ffd83dbSDimitry Andric     const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
6675ffd83dbSDimitry Andric         ->Initialize(MMIWP->getMMI().getContext(), *Target);
6680b57cec5SDimitry Andric     if (MIR) {
6698bcb0991SDimitry Andric       assert(MMIWP && "Forgot to create MMIWP?");
6708bcb0991SDimitry Andric       if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
6710b57cec5SDimitry Andric         return 1;
6720b57cec5SDimitry Andric     }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     // Before executing passes, print the final values of the LLVM options.
6750b57cec5SDimitry Andric     cl::PrintOptionValues();
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric     // If requested, run the pass manager over the same module again,
6780b57cec5SDimitry Andric     // to catch any bugs due to persistent state in the passes. Note that
6790b57cec5SDimitry Andric     // opt has the same functionality, so it may be worth abstracting this out
6800b57cec5SDimitry Andric     // in the future.
6810b57cec5SDimitry Andric     SmallVector<char, 0> CompileTwiceBuffer;
6820b57cec5SDimitry Andric     if (CompileTwice) {
6830b57cec5SDimitry Andric       std::unique_ptr<Module> M2(llvm::CloneModule(*M));
6840b57cec5SDimitry Andric       PM.run(*M2);
6850b57cec5SDimitry Andric       CompileTwiceBuffer = Buffer;
6860b57cec5SDimitry Andric       Buffer.clear();
6870b57cec5SDimitry Andric     }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric     PM.run(*M);
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     auto HasError =
6920b57cec5SDimitry Andric         ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
6930b57cec5SDimitry Andric     if (*HasError)
6940b57cec5SDimitry Andric       return 1;
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric     // Compare the two outputs and make sure they're the same
6970b57cec5SDimitry Andric     if (CompileTwice) {
6980b57cec5SDimitry Andric       if (Buffer.size() != CompileTwiceBuffer.size() ||
6990b57cec5SDimitry Andric           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
7000b57cec5SDimitry Andric            0)) {
7010b57cec5SDimitry Andric         errs()
7020b57cec5SDimitry Andric             << "Running the pass manager twice changed the output.\n"
7030b57cec5SDimitry Andric                "Writing the result of the second run to the specified output\n"
7040b57cec5SDimitry Andric                "To generate the one-run comparison binary, just run without\n"
7050b57cec5SDimitry Andric                "the compile-twice option\n";
7060b57cec5SDimitry Andric         Out->os() << Buffer;
7070b57cec5SDimitry Andric         Out->keep();
7080b57cec5SDimitry Andric         return 1;
7090b57cec5SDimitry Andric       }
7100b57cec5SDimitry Andric     }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric     if (BOS) {
7130b57cec5SDimitry Andric       Out->os() << Buffer;
7140b57cec5SDimitry Andric     }
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   // Declare success.
7180b57cec5SDimitry Andric   Out->keep();
7190b57cec5SDimitry Andric   if (DwoOut)
7200b57cec5SDimitry Andric     DwoOut->keep();
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   return 0;
7230b57cec5SDimitry Andric }
724