xref: /freebsd/contrib/llvm-project/llvm/tools/llc/llc.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
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"
16349cc55cSDimitry Andric #include "llvm/ADT/ScopeExit.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/LLVMContext.h"
315ffd83dbSDimitry Andric #include "llvm/IR/LLVMRemarkStreamer.h"
320b57cec5SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
330b57cec5SDimitry Andric #include "llvm/IR/Module.h"
340b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
350b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
36480093f4SDimitry Andric #include "llvm/InitializePasses.h"
3781ad6265SDimitry Andric #include "llvm/MC/MCTargetOptionsCommandFlags.h"
38349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.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/InitLLVM.h"
460b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h"
470b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
480b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
49349cc55cSDimitry Andric #include "llvm/Support/TimeProfiler.h"
500b57cec5SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
510b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
525ffd83dbSDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
530b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
5406c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
5506c3fb27SDimitry Andric #include "llvm/TargetParser/SubtargetFeature.h"
5606c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
570b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
580b57cec5SDimitry Andric #include <memory>
59bdd1243dSDimitry Andric #include <optional>
600b57cec5SDimitry Andric using namespace llvm;
610b57cec5SDimitry Andric 
625ffd83dbSDimitry Andric static codegen::RegisterCodeGenFlags CGF;
635ffd83dbSDimitry Andric 
640b57cec5SDimitry Andric // General options for llc.  Other pass-specific options are specified
650b57cec5SDimitry Andric // within the corresponding llc passes, and target-specific options
660b57cec5SDimitry Andric // and back-end code generation options are specified with the target machine.
670b57cec5SDimitry Andric //
680b57cec5SDimitry Andric static cl::opt<std::string>
690b57cec5SDimitry Andric InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric static cl::opt<std::string>
720b57cec5SDimitry Andric InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric static cl::opt<std::string>
750b57cec5SDimitry Andric OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static cl::opt<std::string>
780b57cec5SDimitry Andric     SplitDwarfOutputFile("split-dwarf-output",
790b57cec5SDimitry Andric                          cl::desc(".dwo output filename"),
800b57cec5SDimitry Andric                          cl::value_desc("filename"));
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric static cl::opt<unsigned>
830b57cec5SDimitry Andric TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
840b57cec5SDimitry Andric                  cl::value_desc("N"),
850b57cec5SDimitry Andric                  cl::desc("Repeat compilation N times for timing"));
860b57cec5SDimitry Andric 
87349cc55cSDimitry Andric static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
88349cc55cSDimitry Andric 
89349cc55cSDimitry Andric static cl::opt<unsigned> TimeTraceGranularity(
90349cc55cSDimitry Andric     "time-trace-granularity",
91349cc55cSDimitry Andric     cl::desc(
92349cc55cSDimitry Andric         "Minimum time granularity (in microseconds) traced by time profiler"),
93349cc55cSDimitry Andric     cl::init(500), cl::Hidden);
94349cc55cSDimitry Andric 
95349cc55cSDimitry Andric static cl::opt<std::string>
96349cc55cSDimitry Andric     TimeTraceFile("time-trace-file",
97349cc55cSDimitry Andric                   cl::desc("Specify time trace file destination"),
98349cc55cSDimitry Andric                   cl::value_desc("filename"));
99349cc55cSDimitry Andric 
100e8d8bef9SDimitry Andric static cl::opt<std::string>
101e8d8bef9SDimitry Andric     BinutilsVersion("binutils-version", cl::Hidden,
102e8d8bef9SDimitry Andric                     cl::desc("Produced object files can use all ELF features "
103e8d8bef9SDimitry Andric                              "supported by this binutils version and newer."
104e8d8bef9SDimitry Andric                              "If -no-integrated-as is specified, the generated "
105e8d8bef9SDimitry Andric                              "assembly will consider GNU as support."
106e8d8bef9SDimitry Andric                              "'none' means that all ELF features can be used, "
107e8d8bef9SDimitry Andric                              "regardless of binutils support"));
108e8d8bef9SDimitry Andric 
1090b57cec5SDimitry Andric static cl::opt<bool>
1100b57cec5SDimitry Andric     PreserveComments("preserve-as-comments", cl::Hidden,
1110b57cec5SDimitry Andric                      cl::desc("Preserve Comments in outputted assembly"),
1120b57cec5SDimitry Andric                      cl::init(true));
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric // Determine optimization level.
1150b57cec5SDimitry Andric static cl::opt<char>
1160b57cec5SDimitry Andric     OptLevel("O",
1170b57cec5SDimitry Andric              cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
1180b57cec5SDimitry Andric                       "(default = '-O2')"),
119bdd1243dSDimitry Andric              cl::Prefix, cl::init('2'));
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric static cl::opt<std::string>
1220b57cec5SDimitry Andric TargetTriple("mtriple", cl::desc("Override target triple for module"));
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric static cl::opt<std::string> SplitDwarfFile(
1250b57cec5SDimitry Andric     "split-dwarf-file",
1260b57cec5SDimitry Andric     cl::desc(
1270b57cec5SDimitry Andric         "Specify the name of the .dwo file to encode in the DWARF output"));
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
1300b57cec5SDimitry Andric                               cl::desc("Do not verify input module"));
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
1330b57cec5SDimitry Andric                                              cl::desc("Disable simplify-libcalls"));
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
1360b57cec5SDimitry Andric                                     cl::desc("Show encoding in .s output"));
1370b57cec5SDimitry Andric 
138fe6060f1SDimitry Andric static cl::opt<bool>
139fe6060f1SDimitry Andric     DwarfDirectory("dwarf-directory", cl::Hidden,
140fe6060f1SDimitry Andric                    cl::desc("Use .file directives with an explicit directory"),
141fe6060f1SDimitry Andric                    cl::init(true));
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric static cl::opt<bool> AsmVerbose("asm-verbose",
1440b57cec5SDimitry Andric                                 cl::desc("Add comments to directives."),
1450b57cec5SDimitry Andric                                 cl::init(true));
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric static cl::opt<bool>
1480b57cec5SDimitry Andric     CompileTwice("compile-twice", cl::Hidden,
1490b57cec5SDimitry Andric                  cl::desc("Run everything twice, re-using the same pass "
1500b57cec5SDimitry Andric                           "manager and verify the result is the same."),
1510b57cec5SDimitry Andric                  cl::init(false));
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric static cl::opt<bool> DiscardValueNames(
1540b57cec5SDimitry Andric     "discard-value-names",
1550b57cec5SDimitry Andric     cl::desc("Discard names from Value (other than GlobalValue)."),
1560b57cec5SDimitry Andric     cl::init(false), cl::Hidden);
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric static cl::opt<bool> RemarksWithHotness(
1610b57cec5SDimitry Andric     "pass-remarks-with-hotness",
1620b57cec5SDimitry Andric     cl::desc("With PGO, include profile count in optimization remarks"),
1630b57cec5SDimitry Andric     cl::Hidden);
1640b57cec5SDimitry Andric 
165bdd1243dSDimitry Andric static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
166e8d8bef9SDimitry Andric     RemarksHotnessThreshold(
167e8d8bef9SDimitry Andric         "pass-remarks-hotness-threshold",
1680b57cec5SDimitry Andric         cl::desc("Minimum profile count required for "
169e8d8bef9SDimitry Andric                  "an optimization remark to be output. "
170e8d8bef9SDimitry Andric                  "Use 'auto' to apply the threshold from profile summary."),
171e8d8bef9SDimitry Andric         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric static cl::opt<std::string>
1740b57cec5SDimitry Andric     RemarksFilename("pass-remarks-output",
1750b57cec5SDimitry Andric                     cl::desc("Output filename for pass remarks"),
1760b57cec5SDimitry Andric                     cl::value_desc("filename"));
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric static cl::opt<std::string>
1790b57cec5SDimitry Andric     RemarksPasses("pass-remarks-filter",
1800b57cec5SDimitry Andric                   cl::desc("Only record optimization remarks from passes whose "
1810b57cec5SDimitry Andric                            "names match the given regular expression"),
1820b57cec5SDimitry Andric                   cl::value_desc("regex"));
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric static cl::opt<std::string> RemarksFormat(
1850b57cec5SDimitry Andric     "pass-remarks-format",
1860b57cec5SDimitry Andric     cl::desc("The format used for serializing remarks (default: YAML)"),
1870b57cec5SDimitry Andric     cl::value_desc("format"), cl::init("yaml"));
1880b57cec5SDimitry Andric 
1895f757f3fSDimitry Andric static cl::opt<bool> TryUseNewDbgInfoFormat(
1905f757f3fSDimitry Andric     "try-experimental-debuginfo-iterators",
1915f757f3fSDimitry Andric     cl::desc("Enable debuginfo iterator positions, if they're built in"),
1925f757f3fSDimitry Andric     cl::init(false));
1935f757f3fSDimitry Andric 
1945f757f3fSDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
1955f757f3fSDimitry Andric 
1960b57cec5SDimitry Andric namespace {
197753f127fSDimitry Andric 
198753f127fSDimitry Andric std::vector<std::string> &getRunPassNames() {
199753f127fSDimitry Andric   static std::vector<std::string> RunPassNames;
200753f127fSDimitry Andric   return RunPassNames;
201753f127fSDimitry Andric }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric struct RunPassOption {
2040b57cec5SDimitry Andric   void operator=(const std::string &Val) const {
2050b57cec5SDimitry Andric     if (Val.empty())
2060b57cec5SDimitry Andric       return;
2070b57cec5SDimitry Andric     SmallVector<StringRef, 8> PassNames;
2080b57cec5SDimitry Andric     StringRef(Val).split(PassNames, ',', -1, false);
2090b57cec5SDimitry Andric     for (auto PassName : PassNames)
210753f127fSDimitry Andric       getRunPassNames().push_back(std::string(PassName));
2110b57cec5SDimitry Andric   }
2120b57cec5SDimitry Andric };
2135f757f3fSDimitry Andric } // namespace
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric static RunPassOption RunPassOpt;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
2180b57cec5SDimitry Andric     "run-pass",
2190b57cec5SDimitry Andric     cl::desc("Run compiler only for specified passes (comma separated list)"),
22081ad6265SDimitry Andric     cl::value_desc("pass-name"), cl::location(RunPassOpt));
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric static int compileModule(char **, LLVMContext &);
2230b57cec5SDimitry Andric 
224349cc55cSDimitry Andric [[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
225e8d8bef9SDimitry Andric   SmallString<256> Prefix;
226e8d8bef9SDimitry Andric   if (!Filename.empty()) {
227e8d8bef9SDimitry Andric     if (Filename == "-")
228e8d8bef9SDimitry Andric       Filename = "<stdin>";
229e8d8bef9SDimitry Andric     ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
230e8d8bef9SDimitry Andric   }
231e8d8bef9SDimitry Andric   WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
232e8d8bef9SDimitry Andric   exit(1);
233e8d8bef9SDimitry Andric }
234e8d8bef9SDimitry Andric 
235349cc55cSDimitry Andric [[noreturn]] static void reportError(Error Err, StringRef Filename) {
236e8d8bef9SDimitry Andric   assert(Err);
237e8d8bef9SDimitry Andric   handleAllErrors(createFileError(Filename, std::move(Err)),
238e8d8bef9SDimitry Andric                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
239e8d8bef9SDimitry Andric   llvm_unreachable("reportError() should not return");
240e8d8bef9SDimitry Andric }
241e8d8bef9SDimitry Andric 
2420b57cec5SDimitry Andric static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
2430b57cec5SDimitry Andric                                                        Triple::OSType OS,
2440b57cec5SDimitry Andric                                                        const char *ProgName) {
2450b57cec5SDimitry Andric   // If we don't yet have an output filename, make one.
2460b57cec5SDimitry Andric   if (OutputFilename.empty()) {
2470b57cec5SDimitry Andric     if (InputFilename == "-")
2480b57cec5SDimitry Andric       OutputFilename = "-";
2490b57cec5SDimitry Andric     else {
2500b57cec5SDimitry Andric       // If InputFilename ends in .bc or .ll, remove it.
2510b57cec5SDimitry Andric       StringRef IFN = InputFilename;
2525f757f3fSDimitry Andric       if (IFN.ends_with(".bc") || IFN.ends_with(".ll"))
2535ffd83dbSDimitry Andric         OutputFilename = std::string(IFN.drop_back(3));
2545f757f3fSDimitry Andric       else if (IFN.ends_with(".mir"))
2555ffd83dbSDimitry Andric         OutputFilename = std::string(IFN.drop_back(4));
2560b57cec5SDimitry Andric       else
2575ffd83dbSDimitry Andric         OutputFilename = std::string(IFN);
2580b57cec5SDimitry Andric 
2595ffd83dbSDimitry Andric       switch (codegen::getFileType()) {
2605f757f3fSDimitry Andric       case CodeGenFileType::AssemblyFile:
2610b57cec5SDimitry Andric         if (TargetName[0] == 'c') {
2620b57cec5SDimitry Andric           if (TargetName[1] == 0)
2630b57cec5SDimitry Andric             OutputFilename += ".cbe.c";
2640b57cec5SDimitry Andric           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
2650b57cec5SDimitry Andric             OutputFilename += ".cpp";
2660b57cec5SDimitry Andric           else
2670b57cec5SDimitry Andric             OutputFilename += ".s";
2680b57cec5SDimitry Andric         } else
2690b57cec5SDimitry Andric           OutputFilename += ".s";
2700b57cec5SDimitry Andric         break;
2715f757f3fSDimitry Andric       case CodeGenFileType::ObjectFile:
2720b57cec5SDimitry Andric         if (OS == Triple::Win32)
2730b57cec5SDimitry Andric           OutputFilename += ".obj";
2740b57cec5SDimitry Andric         else
2750b57cec5SDimitry Andric           OutputFilename += ".o";
2760b57cec5SDimitry Andric         break;
2775f757f3fSDimitry Andric       case CodeGenFileType::Null:
278e8d8bef9SDimitry Andric         OutputFilename = "-";
2790b57cec5SDimitry Andric         break;
2800b57cec5SDimitry Andric       }
2810b57cec5SDimitry Andric     }
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   // Decide if we need "binary" output.
2850b57cec5SDimitry Andric   bool Binary = false;
2865ffd83dbSDimitry Andric   switch (codegen::getFileType()) {
2875f757f3fSDimitry Andric   case CodeGenFileType::AssemblyFile:
2880b57cec5SDimitry Andric     break;
2895f757f3fSDimitry Andric   case CodeGenFileType::ObjectFile:
2905f757f3fSDimitry Andric   case CodeGenFileType::Null:
2910b57cec5SDimitry Andric     Binary = true;
2920b57cec5SDimitry Andric     break;
2930b57cec5SDimitry Andric   }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   // Open the file.
2960b57cec5SDimitry Andric   std::error_code EC;
2978bcb0991SDimitry Andric   sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
2980b57cec5SDimitry Andric   if (!Binary)
299fe6060f1SDimitry Andric     OpenFlags |= sys::fs::OF_TextWithCRLF;
3008bcb0991SDimitry Andric   auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
3010b57cec5SDimitry Andric   if (EC) {
302e8d8bef9SDimitry Andric     reportError(EC.message());
3030b57cec5SDimitry Andric     return nullptr;
3040b57cec5SDimitry Andric   }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric   return FDOut;
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric struct LLCDiagnosticHandler : public DiagnosticHandler {
3100b57cec5SDimitry Andric   bool handleDiagnostics(const DiagnosticInfo &DI) override {
311*cb14a3feSDimitry Andric     DiagnosticHandler::handleDiagnostics(DI);
312fe6060f1SDimitry Andric     if (DI.getKind() == llvm::DK_SrcMgr) {
313fe6060f1SDimitry Andric       const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
314fe6060f1SDimitry Andric       const SMDiagnostic &SMD = DISM.getSMDiag();
315fe6060f1SDimitry Andric 
316fe6060f1SDimitry Andric       SMD.print(nullptr, errs());
317fe6060f1SDimitry Andric 
318fe6060f1SDimitry Andric       // For testing purposes, we print the LocCookie here.
319fe6060f1SDimitry Andric       if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
320fe6060f1SDimitry Andric         WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
321fe6060f1SDimitry Andric 
322fe6060f1SDimitry Andric       return true;
323fe6060f1SDimitry Andric     }
324fe6060f1SDimitry Andric 
3250b57cec5SDimitry Andric     if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
3260b57cec5SDimitry Andric       if (!Remark->isEnabled())
3270b57cec5SDimitry Andric         return true;
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric     DiagnosticPrinterRawOStream DP(errs());
3300b57cec5SDimitry Andric     errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
3310b57cec5SDimitry Andric     DI.print(DP);
3320b57cec5SDimitry Andric     errs() << "\n";
3330b57cec5SDimitry Andric     return true;
3340b57cec5SDimitry Andric   }
3350b57cec5SDimitry Andric };
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric // main - Entry point for the llc compiler.
3380b57cec5SDimitry Andric //
3390b57cec5SDimitry Andric int main(int argc, char **argv) {
3400b57cec5SDimitry Andric   InitLLVM X(argc, argv);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   // Enable debug stream buffering.
3430b57cec5SDimitry Andric   EnableDebugBuffering = true;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   // Initialize targets first, so that --version shows registered targets.
3460b57cec5SDimitry Andric   InitializeAllTargets();
3470b57cec5SDimitry Andric   InitializeAllTargetMCs();
3480b57cec5SDimitry Andric   InitializeAllAsmPrinters();
3490b57cec5SDimitry Andric   InitializeAllAsmParsers();
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   // Initialize codegen and IR passes used by llc so that the -print-after,
3520b57cec5SDimitry Andric   // -print-before, and -stop-after options work.
3530b57cec5SDimitry Andric   PassRegistry *Registry = PassRegistry::getPassRegistry();
3540b57cec5SDimitry Andric   initializeCore(*Registry);
3550b57cec5SDimitry Andric   initializeCodeGen(*Registry);
3560b57cec5SDimitry Andric   initializeLoopStrengthReducePass(*Registry);
3570b57cec5SDimitry Andric   initializeLowerIntrinsicsPass(*Registry);
3580b57cec5SDimitry Andric   initializeUnreachableBlockElimLegacyPassPass(*Registry);
3590b57cec5SDimitry Andric   initializeConstantHoistingLegacyPassPass(*Registry);
3600b57cec5SDimitry Andric   initializeScalarOpts(*Registry);
3610b57cec5SDimitry Andric   initializeVectorization(*Registry);
362e8d8bef9SDimitry Andric   initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
3630b57cec5SDimitry Andric   initializeExpandReductionsPass(*Registry);
364fe6060f1SDimitry Andric   initializeExpandVectorPredicationPass(*Registry);
36506c3fb27SDimitry Andric   initializeHardwareLoopsLegacyPass(*Registry);
3665ffd83dbSDimitry Andric   initializeTransformUtils(*Registry);
367fe6060f1SDimitry Andric   initializeReplaceWithVeclibLegacyPass(*Registry);
36881ad6265SDimitry Andric   initializeTLSVariableHoistLegacyPassPass(*Registry);
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   // Initialize debugging passes.
3710b57cec5SDimitry Andric   initializeScavengerTestPass(*Registry);
3720b57cec5SDimitry Andric 
373bdd1243dSDimitry Andric   // Register the Target and CPU printer for --version.
374bdd1243dSDimitry Andric   cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
3750b57cec5SDimitry Andric   // Register the target printer for --version.
3760b57cec5SDimitry Andric   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
3790b57cec5SDimitry Andric 
3805f757f3fSDimitry Andric   // RemoveDIs debug-info transition: tests may request that we /try/ to use the
3815f757f3fSDimitry Andric   // new debug-info format, if it's built in.
3825f757f3fSDimitry Andric #ifdef EXPERIMENTAL_DEBUGINFO_ITERATORS
3835f757f3fSDimitry Andric   if (TryUseNewDbgInfoFormat) {
3845f757f3fSDimitry Andric     // If LLVM was built with support for this, turn the new debug-info format
3855f757f3fSDimitry Andric     // on.
3865f757f3fSDimitry Andric     UseNewDbgInfoFormat = true;
3875f757f3fSDimitry Andric   }
3885f757f3fSDimitry Andric #endif
3895f757f3fSDimitry Andric   (void)TryUseNewDbgInfoFormat;
3905f757f3fSDimitry Andric 
391349cc55cSDimitry Andric   if (TimeTrace)
392349cc55cSDimitry Andric     timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
393349cc55cSDimitry Andric   auto TimeTraceScopeExit = make_scope_exit([]() {
394349cc55cSDimitry Andric     if (TimeTrace) {
395349cc55cSDimitry Andric       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
396349cc55cSDimitry Andric         handleAllErrors(std::move(E), [&](const StringError &SE) {
397349cc55cSDimitry Andric           errs() << SE.getMessage() << "\n";
398349cc55cSDimitry Andric         });
399349cc55cSDimitry Andric         return;
400349cc55cSDimitry Andric       }
401349cc55cSDimitry Andric       timeTraceProfilerCleanup();
402349cc55cSDimitry Andric     }
403349cc55cSDimitry Andric   });
404349cc55cSDimitry Andric 
405349cc55cSDimitry Andric   LLVMContext Context;
4060b57cec5SDimitry Andric   Context.setDiscardValueNames(DiscardValueNames);
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   // Set a diagnostic handler that doesn't exit on the first error
409*cb14a3feSDimitry Andric   Context.setDiagnosticHandler(std::make_unique<LLCDiagnosticHandler>());
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
4125ffd83dbSDimitry Andric       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
4130b57cec5SDimitry Andric                                    RemarksFormat, RemarksWithHotness,
4140b57cec5SDimitry Andric                                    RemarksHotnessThreshold);
415e8d8bef9SDimitry Andric   if (Error E = RemarksFileOrErr.takeError())
416e8d8bef9SDimitry Andric     reportError(std::move(E), RemarksFilename);
4170b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
4180b57cec5SDimitry Andric 
419e8d8bef9SDimitry Andric   if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
420e8d8bef9SDimitry Andric     reportError("input language must be '', 'IR' or 'MIR'");
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   // Compile the module TimeCompilations times to give better compile time
4230b57cec5SDimitry Andric   // metrics.
4240b57cec5SDimitry Andric   for (unsigned I = TimeCompilations; I; --I)
4250b57cec5SDimitry Andric     if (int RetVal = compileModule(argv, Context))
4260b57cec5SDimitry Andric       return RetVal;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   if (RemarksFile)
4290b57cec5SDimitry Andric     RemarksFile->keep();
4300b57cec5SDimitry Andric   return 0;
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric static bool addPass(PassManagerBase &PM, const char *argv0,
4340b57cec5SDimitry Andric                     StringRef PassName, TargetPassConfig &TPC) {
4350b57cec5SDimitry Andric   if (PassName == "none")
4360b57cec5SDimitry Andric     return false;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   const PassRegistry *PR = PassRegistry::getPassRegistry();
4390b57cec5SDimitry Andric   const PassInfo *PI = PR->getPassInfo(PassName);
4400b57cec5SDimitry Andric   if (!PI) {
4410b57cec5SDimitry Andric     WithColor::error(errs(), argv0)
4420b57cec5SDimitry Andric         << "run-pass " << PassName << " is not registered.\n";
4430b57cec5SDimitry Andric     return true;
4440b57cec5SDimitry Andric   }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   Pass *P;
4470b57cec5SDimitry Andric   if (PI->getNormalCtor())
4480b57cec5SDimitry Andric     P = PI->getNormalCtor()();
4490b57cec5SDimitry Andric   else {
4500b57cec5SDimitry Andric     WithColor::error(errs(), argv0)
4510b57cec5SDimitry Andric         << "cannot create pass: " << PI->getPassName() << "\n";
4520b57cec5SDimitry Andric     return true;
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric   std::string Banner = std::string("After ") + std::string(P->getPassName());
4555ffd83dbSDimitry Andric   TPC.addMachinePrePasses();
4560b57cec5SDimitry Andric   PM.add(P);
4575ffd83dbSDimitry Andric   TPC.addMachinePostPasses(Banner);
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   return false;
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric static int compileModule(char **argv, LLVMContext &Context) {
4630b57cec5SDimitry Andric   // Load the module to be compiled...
4640b57cec5SDimitry Andric   SMDiagnostic Err;
4650b57cec5SDimitry Andric   std::unique_ptr<Module> M;
4660b57cec5SDimitry Andric   std::unique_ptr<MIRParser> MIR;
4670b57cec5SDimitry Andric   Triple TheTriple;
4685ffd83dbSDimitry Andric   std::string CPUStr = codegen::getCPUStr(),
4695ffd83dbSDimitry Andric               FeaturesStr = codegen::getFeaturesStr();
470480093f4SDimitry Andric 
471480093f4SDimitry Andric   // Set attributes on functions as loaded from MIR from command line arguments.
472480093f4SDimitry Andric   auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
4735ffd83dbSDimitry Andric     codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
474480093f4SDimitry Andric   };
4750b57cec5SDimitry Andric 
4765ffd83dbSDimitry Andric   auto MAttrs = codegen::getMAttrs();
477bdd1243dSDimitry Andric   bool SkipModule =
478bdd1243dSDimitry Andric       CPUStr == "help" || (!MAttrs.empty() && MAttrs.front() == "help");
4790b57cec5SDimitry Andric 
4805f757f3fSDimitry Andric   CodeGenOptLevel OLvl;
481bdd1243dSDimitry Andric   if (auto Level = CodeGenOpt::parseLevel(OptLevel)) {
482bdd1243dSDimitry Andric     OLvl = *Level;
483bdd1243dSDimitry Andric   } else {
4840b57cec5SDimitry Andric     WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
4850b57cec5SDimitry Andric     return 1;
4860b57cec5SDimitry Andric   }
4870b57cec5SDimitry Andric 
488e8d8bef9SDimitry Andric   // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
489e8d8bef9SDimitry Andric   // use that to indicate the MC default.
490e8d8bef9SDimitry Andric   if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
491e8d8bef9SDimitry Andric     StringRef V = BinutilsVersion.getValue();
492e8d8bef9SDimitry Andric     unsigned Num;
493e8d8bef9SDimitry Andric     if (V.consumeInteger(10, Num) || Num == 0 ||
494e8d8bef9SDimitry Andric         !(V.empty() ||
495e8d8bef9SDimitry Andric           (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
496e8d8bef9SDimitry Andric       WithColor::error(errs(), argv[0])
497e8d8bef9SDimitry Andric           << "invalid -binutils-version, accepting 'none' or major.minor\n";
498e8d8bef9SDimitry Andric       return 1;
499e8d8bef9SDimitry Andric     }
500e8d8bef9SDimitry Andric   }
501e8d8bef9SDimitry Andric   TargetOptions Options;
502e8d8bef9SDimitry Andric   auto InitializeOptions = [&](const Triple &TheTriple) {
503e8d8bef9SDimitry Andric     Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
50406c3fb27SDimitry Andric 
50506c3fb27SDimitry Andric     if (Options.XCOFFReadOnlyPointers) {
50606c3fb27SDimitry Andric       if (!TheTriple.isOSAIX())
50706c3fb27SDimitry Andric         reportError("-mxcoff-roptr option is only supported on AIX",
50806c3fb27SDimitry Andric                     InputFilename);
50906c3fb27SDimitry Andric 
51006c3fb27SDimitry Andric       // Since the storage mapping class is specified per csect,
51106c3fb27SDimitry Andric       // without using data sections, it is less effective to use read-only
51206c3fb27SDimitry Andric       // pointers. Using read-only pointers may cause other RO variables in the
51306c3fb27SDimitry Andric       // same csect to become RW when the linker acts upon `-bforceimprw`;
51406c3fb27SDimitry Andric       // therefore, we require that separate data sections are used in the
51506c3fb27SDimitry Andric       // presence of ReadOnlyPointers. We respect the setting of data-sections
51606c3fb27SDimitry Andric       // since we have not found reasons to do otherwise that overcome the user
51706c3fb27SDimitry Andric       // surprise of not respecting the setting.
51806c3fb27SDimitry Andric       if (!Options.DataSections)
51906c3fb27SDimitry Andric         reportError("-mxcoff-roptr option must be used with -data-sections",
52006c3fb27SDimitry Andric                     InputFilename);
52106c3fb27SDimitry Andric     }
52206c3fb27SDimitry Andric 
523e8d8bef9SDimitry Andric     Options.BinutilsVersion =
524e8d8bef9SDimitry Andric         TargetMachine::parseBinutilsVersion(BinutilsVersion);
5250b57cec5SDimitry Andric     Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
5260b57cec5SDimitry Andric     Options.MCOptions.AsmVerbose = AsmVerbose;
5270b57cec5SDimitry Andric     Options.MCOptions.PreserveAsmComments = PreserveComments;
5280b57cec5SDimitry Andric     Options.MCOptions.IASSearchPaths = IncludeDirs;
5290b57cec5SDimitry Andric     Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
53081ad6265SDimitry Andric     if (DwarfDirectory.getPosition()) {
53181ad6265SDimitry Andric       Options.MCOptions.MCUseDwarfDirectory =
53281ad6265SDimitry Andric           DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
53381ad6265SDimitry Andric                          : MCTargetOptions::DisableDwarfDirectory;
53481ad6265SDimitry Andric     } else {
53581ad6265SDimitry Andric       // -dwarf-directory is not set explicitly. Some assemblers
53681ad6265SDimitry Andric       // (e.g. GNU as or ptxas) do not support `.file directory'
53781ad6265SDimitry Andric       // syntax prior to DWARFv5. Let the target decide the default
53881ad6265SDimitry Andric       // value.
53981ad6265SDimitry Andric       Options.MCOptions.MCUseDwarfDirectory =
54081ad6265SDimitry Andric           MCTargetOptions::DefaultDwarfDirectory;
54181ad6265SDimitry Andric     }
542e8d8bef9SDimitry Andric   };
5430b57cec5SDimitry Andric 
544bdd1243dSDimitry Andric   std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
545bdd1243dSDimitry Andric   std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
5460b57cec5SDimitry Andric 
5475ffd83dbSDimitry Andric   const Target *TheTarget = nullptr;
5485ffd83dbSDimitry Andric   std::unique_ptr<TargetMachine> Target;
5495ffd83dbSDimitry Andric 
5505ffd83dbSDimitry Andric   // If user just wants to list available options, skip module loading
5515ffd83dbSDimitry Andric   if (!SkipModule) {
552bdd1243dSDimitry Andric     auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,
553bdd1243dSDimitry Andric                              StringRef OldDLStr) -> std::optional<std::string> {
5545ffd83dbSDimitry Andric       // If we are supposed to override the target triple, do so now.
5555ffd83dbSDimitry Andric       std::string IRTargetTriple = DataLayoutTargetTriple.str();
5565ffd83dbSDimitry Andric       if (!TargetTriple.empty())
5575ffd83dbSDimitry Andric         IRTargetTriple = Triple::normalize(TargetTriple);
5585ffd83dbSDimitry Andric       TheTriple = Triple(IRTargetTriple);
5595ffd83dbSDimitry Andric       if (TheTriple.getTriple().empty())
5605ffd83dbSDimitry Andric         TheTriple.setTriple(sys::getDefaultTargetTriple());
5615ffd83dbSDimitry Andric 
5625ffd83dbSDimitry Andric       std::string Error;
5635ffd83dbSDimitry Andric       TheTarget =
5645ffd83dbSDimitry Andric           TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
5655ffd83dbSDimitry Andric       if (!TheTarget) {
5665ffd83dbSDimitry Andric         WithColor::error(errs(), argv[0]) << Error;
5675ffd83dbSDimitry Andric         exit(1);
5685ffd83dbSDimitry Andric       }
5695ffd83dbSDimitry Andric 
570e8d8bef9SDimitry Andric       InitializeOptions(TheTriple);
5715ffd83dbSDimitry Andric       Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
57281ad6265SDimitry Andric           TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
5735ffd83dbSDimitry Andric       assert(Target && "Could not allocate target machine!");
5745ffd83dbSDimitry Andric 
5755ffd83dbSDimitry Andric       return Target->createDataLayout().getStringRepresentation();
5765ffd83dbSDimitry Andric     };
5775ffd83dbSDimitry Andric     if (InputLanguage == "mir" ||
5785f757f3fSDimitry Andric         (InputLanguage == "" && StringRef(InputFilename).ends_with(".mir"))) {
5795ffd83dbSDimitry Andric       MIR = createMIRParserFromFile(InputFilename, Err, Context,
5805ffd83dbSDimitry Andric                                     setMIRFunctionAttributes);
5815ffd83dbSDimitry Andric       if (MIR)
5825ffd83dbSDimitry Andric         M = MIR->parseIRModule(SetDataLayout);
5835ffd83dbSDimitry Andric     } else {
584bdd1243dSDimitry Andric       M = parseIRFile(InputFilename, Err, Context,
585bdd1243dSDimitry Andric                       ParserCallbacks(SetDataLayout));
5865ffd83dbSDimitry Andric     }
5875ffd83dbSDimitry Andric     if (!M) {
5885ffd83dbSDimitry Andric       Err.print(argv[0], WithColor::error(errs(), argv[0]));
5895ffd83dbSDimitry Andric       return 1;
5905ffd83dbSDimitry Andric     }
5915ffd83dbSDimitry Andric     if (!TargetTriple.empty())
5925ffd83dbSDimitry Andric       M->setTargetTriple(Triple::normalize(TargetTriple));
59381ad6265SDimitry Andric 
594bdd1243dSDimitry Andric     std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
59581ad6265SDimitry Andric     if (!CM && CM_IR)
596bdd1243dSDimitry Andric       Target->setCodeModel(*CM_IR);
5975f757f3fSDimitry Andric     if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
5985f757f3fSDimitry Andric       Target->setLargeDataThreshold(*LDT);
5995ffd83dbSDimitry Andric   } else {
6005ffd83dbSDimitry Andric     TheTriple = Triple(Triple::normalize(TargetTriple));
6015ffd83dbSDimitry Andric     if (TheTriple.getTriple().empty())
6025ffd83dbSDimitry Andric       TheTriple.setTriple(sys::getDefaultTargetTriple());
6035ffd83dbSDimitry Andric 
6045ffd83dbSDimitry Andric     // Get the target specific parser.
6055ffd83dbSDimitry Andric     std::string Error;
6065ffd83dbSDimitry Andric     TheTarget =
6075ffd83dbSDimitry Andric         TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
6085ffd83dbSDimitry Andric     if (!TheTarget) {
6095ffd83dbSDimitry Andric       WithColor::error(errs(), argv[0]) << Error;
6105ffd83dbSDimitry Andric       return 1;
6115ffd83dbSDimitry Andric     }
6125ffd83dbSDimitry Andric 
613e8d8bef9SDimitry Andric     InitializeOptions(TheTriple);
6145ffd83dbSDimitry Andric     Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
61581ad6265SDimitry Andric         TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
6160b57cec5SDimitry Andric     assert(Target && "Could not allocate target machine!");
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric     // If we don't have a module then just exit now. We do this down
6190b57cec5SDimitry Andric     // here since the CPU/Feature help is underneath the target machine
6200b57cec5SDimitry Andric     // creation.
6210b57cec5SDimitry Andric     return 0;
6225ffd83dbSDimitry Andric   }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   assert(M && "Should have exited if we didn't have a module!");
6255ffd83dbSDimitry Andric   if (codegen::getFloatABIForCalls() != FloatABI::Default)
6265f757f3fSDimitry Andric     Target->Options.FloatABIType = codegen::getFloatABIForCalls();
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // Figure out where we are going to send the output.
6290b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> Out =
6300b57cec5SDimitry Andric       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
6310b57cec5SDimitry Andric   if (!Out) return 1;
6320b57cec5SDimitry Andric 
6330eae32dcSDimitry Andric   // Ensure the filename is passed down to CodeViewDebug.
6340eae32dcSDimitry Andric   Target->Options.ObjectFilenameForDebug = Out->outputFilename();
6350eae32dcSDimitry Andric 
6360b57cec5SDimitry Andric   std::unique_ptr<ToolOutputFile> DwoOut;
6370b57cec5SDimitry Andric   if (!SplitDwarfOutputFile.empty()) {
6380b57cec5SDimitry Andric     std::error_code EC;
6398bcb0991SDimitry Andric     DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
6408bcb0991SDimitry Andric                                                sys::fs::OF_None);
641e8d8bef9SDimitry Andric     if (EC)
642e8d8bef9SDimitry Andric       reportError(EC.message(), SplitDwarfOutputFile);
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   // Build up all of the passes that we want to do to the module.
6460b57cec5SDimitry Andric   legacy::PassManager PM;
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   // Add an appropriate TargetLibraryInfo pass for the module's triple.
6490b57cec5SDimitry Andric   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
6520b57cec5SDimitry Andric   if (DisableSimplifyLibCalls)
6530b57cec5SDimitry Andric     TLII.disableAllFunctions();
6540b57cec5SDimitry Andric   PM.add(new TargetLibraryInfoWrapperPass(TLII));
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   // Verify module immediately to catch problems before doInitialization() is
6570b57cec5SDimitry Andric   // called on any passes.
658e8d8bef9SDimitry Andric   if (!NoVerify && verifyModule(*M, &errs()))
659e8d8bef9SDimitry Andric     reportError("input module cannot be verified", InputFilename);
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // Override function attributes based on CPUStr, FeaturesStr, and command line
6620b57cec5SDimitry Andric   // flags.
6635ffd83dbSDimitry Andric   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
6640b57cec5SDimitry Andric 
6655f757f3fSDimitry Andric   if (mc::getExplicitRelaxAll() &&
6665f757f3fSDimitry Andric       codegen::getFileType() != CodeGenFileType::ObjectFile)
6670b57cec5SDimitry Andric     WithColor::warning(errs(), argv[0])
6680b57cec5SDimitry Andric         << ": warning: ignoring -mc-relax-all because filetype != obj";
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   {
6710b57cec5SDimitry Andric     raw_pwrite_stream *OS = &Out->os();
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric     // Manually do the buffering rather than using buffer_ostream,
6740b57cec5SDimitry Andric     // so we can memcmp the contents in CompileTwice mode
6750b57cec5SDimitry Andric     SmallVector<char, 0> Buffer;
6760b57cec5SDimitry Andric     std::unique_ptr<raw_svector_ostream> BOS;
6775f757f3fSDimitry Andric     if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
6780b57cec5SDimitry Andric          !Out->os().supportsSeeking()) ||
6790b57cec5SDimitry Andric         CompileTwice) {
6808bcb0991SDimitry Andric       BOS = std::make_unique<raw_svector_ostream>(Buffer);
6810b57cec5SDimitry Andric       OS = BOS.get();
6820b57cec5SDimitry Andric     }
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric     const char *argv0 = argv[0];
6850b57cec5SDimitry Andric     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
6868bcb0991SDimitry Andric     MachineModuleInfoWrapperPass *MMIWP =
6878bcb0991SDimitry Andric         new MachineModuleInfoWrapperPass(&LLVMTM);
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric     // Construct a custom pass pipeline that starts after instruction
6900b57cec5SDimitry Andric     // selection.
691753f127fSDimitry Andric     if (!getRunPassNames().empty()) {
6920b57cec5SDimitry Andric       if (!MIR) {
6930b57cec5SDimitry Andric         WithColor::warning(errs(), argv[0])
6940b57cec5SDimitry Andric             << "run-pass is for .mir file only.\n";
69506c3fb27SDimitry Andric         delete MMIWP;
6960b57cec5SDimitry Andric         return 1;
6970b57cec5SDimitry Andric       }
69806c3fb27SDimitry Andric       TargetPassConfig *PTPC = LLVMTM.createPassConfig(PM);
69906c3fb27SDimitry Andric       TargetPassConfig &TPC = *PTPC;
7000b57cec5SDimitry Andric       if (TPC.hasLimitedCodeGenPipeline()) {
7010b57cec5SDimitry Andric         WithColor::warning(errs(), argv[0])
7020b57cec5SDimitry Andric             << "run-pass cannot be used with "
7030b57cec5SDimitry Andric             << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
70406c3fb27SDimitry Andric         delete PTPC;
70506c3fb27SDimitry Andric         delete MMIWP;
7060b57cec5SDimitry Andric         return 1;
7070b57cec5SDimitry Andric       }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric       TPC.setDisableVerify(NoVerify);
7100b57cec5SDimitry Andric       PM.add(&TPC);
7118bcb0991SDimitry Andric       PM.add(MMIWP);
7120b57cec5SDimitry Andric       TPC.printAndVerify("");
713753f127fSDimitry Andric       for (const std::string &RunPassName : getRunPassNames()) {
7140b57cec5SDimitry Andric         if (addPass(PM, argv0, RunPassName, TPC))
7150b57cec5SDimitry Andric           return 1;
7160b57cec5SDimitry Andric       }
7170b57cec5SDimitry Andric       TPC.setInitialized();
7180b57cec5SDimitry Andric       PM.add(createPrintMIRPass(*OS));
7190b57cec5SDimitry Andric       PM.add(createFreeMachineFunctionPass());
7205ffd83dbSDimitry Andric     } else if (Target->addPassesToEmitFile(
7215ffd83dbSDimitry Andric                    PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
7225ffd83dbSDimitry Andric                    codegen::getFileType(), NoVerify, MMIWP)) {
723e8d8bef9SDimitry Andric       reportError("target does not support generation of this file type");
7240b57cec5SDimitry Andric     }
7250b57cec5SDimitry Andric 
7265ffd83dbSDimitry Andric     const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
7275ffd83dbSDimitry Andric         ->Initialize(MMIWP->getMMI().getContext(), *Target);
7280b57cec5SDimitry Andric     if (MIR) {
7298bcb0991SDimitry Andric       assert(MMIWP && "Forgot to create MMIWP?");
7308bcb0991SDimitry Andric       if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
7310b57cec5SDimitry Andric         return 1;
7320b57cec5SDimitry Andric     }
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     // Before executing passes, print the final values of the LLVM options.
7350b57cec5SDimitry Andric     cl::PrintOptionValues();
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric     // If requested, run the pass manager over the same module again,
7380b57cec5SDimitry Andric     // to catch any bugs due to persistent state in the passes. Note that
7390b57cec5SDimitry Andric     // opt has the same functionality, so it may be worth abstracting this out
7400b57cec5SDimitry Andric     // in the future.
7410b57cec5SDimitry Andric     SmallVector<char, 0> CompileTwiceBuffer;
7420b57cec5SDimitry Andric     if (CompileTwice) {
7430b57cec5SDimitry Andric       std::unique_ptr<Module> M2(llvm::CloneModule(*M));
7440b57cec5SDimitry Andric       PM.run(*M2);
7450b57cec5SDimitry Andric       CompileTwiceBuffer = Buffer;
7460b57cec5SDimitry Andric       Buffer.clear();
7470b57cec5SDimitry Andric     }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     PM.run(*M);
7500b57cec5SDimitry Andric 
751*cb14a3feSDimitry Andric     if (Context.getDiagHandlerPtr()->HasErrors)
7520b57cec5SDimitry Andric       return 1;
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric     // Compare the two outputs and make sure they're the same
7550b57cec5SDimitry Andric     if (CompileTwice) {
7560b57cec5SDimitry Andric       if (Buffer.size() != CompileTwiceBuffer.size() ||
7570b57cec5SDimitry Andric           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
7580b57cec5SDimitry Andric            0)) {
7590b57cec5SDimitry Andric         errs()
7600b57cec5SDimitry Andric             << "Running the pass manager twice changed the output.\n"
7610b57cec5SDimitry Andric                "Writing the result of the second run to the specified output\n"
7620b57cec5SDimitry Andric                "To generate the one-run comparison binary, just run without\n"
7630b57cec5SDimitry Andric                "the compile-twice option\n";
7640b57cec5SDimitry Andric         Out->os() << Buffer;
7650b57cec5SDimitry Andric         Out->keep();
7660b57cec5SDimitry Andric         return 1;
7670b57cec5SDimitry Andric       }
7680b57cec5SDimitry Andric     }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric     if (BOS) {
7710b57cec5SDimitry Andric       Out->os() << Buffer;
7720b57cec5SDimitry Andric     }
7730b57cec5SDimitry Andric   }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   // Declare success.
7760b57cec5SDimitry Andric   Out->keep();
7770b57cec5SDimitry Andric   if (DwoOut)
7780b57cec5SDimitry Andric     DwoOut->keep();
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   return 0;
7810b57cec5SDimitry Andric }
782