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
107a6dacacSDimitry Andric // command-line interface for generating an assembly file or a relocatable file,
117a6dacacSDimitry Andric // given LLVM bitcode.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric
157a6dacacSDimitry Andric #include "NewPMDriver.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
17349cc55cSDimitry Andric #include "llvm/ADT/ScopeExit.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
195ffd83dbSDimitry Andric #include "llvm/CodeGen/CommandFlags.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllCodegenComponents.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MIRParser/MIRParser.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
270b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
280b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
290b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
300b57cec5SDimitry Andric #include "llvm/IR/DiagnosticPrinter.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"
3881ad6265SDimitry Andric #include "llvm/MC/MCTargetOptionsCommandFlags.h"
39349cc55cSDimitry Andric #include "llvm/MC/TargetRegistry.h"
400b57cec5SDimitry Andric #include "llvm/Pass.h"
41e8d8bef9SDimitry Andric #include "llvm/Remarks/HotnessThresholdParser.h"
420b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
430b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
440b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
450b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
460b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h"
470b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h"
480b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
490b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
50349cc55cSDimitry Andric #include "llvm/Support/TimeProfiler.h"
510b57cec5SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
520b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
535ffd83dbSDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
540b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
5506c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
5606c3fb27SDimitry Andric #include "llvm/TargetParser/SubtargetFeature.h"
5706c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
580b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
590b57cec5SDimitry Andric #include <memory>
60bdd1243dSDimitry Andric #include <optional>
610b57cec5SDimitry Andric using namespace llvm;
620b57cec5SDimitry Andric
635ffd83dbSDimitry Andric static codegen::RegisterCodeGenFlags CGF;
645ffd83dbSDimitry Andric
650b57cec5SDimitry Andric // General options for llc. Other pass-specific options are specified
660b57cec5SDimitry Andric // within the corresponding llc passes, and target-specific options
670b57cec5SDimitry Andric // and back-end code generation options are specified with the target machine.
680b57cec5SDimitry Andric //
690b57cec5SDimitry Andric static cl::opt<std::string>
700b57cec5SDimitry Andric InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
710b57cec5SDimitry Andric
720b57cec5SDimitry Andric static cl::opt<std::string>
730b57cec5SDimitry Andric InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric static cl::opt<std::string>
760b57cec5SDimitry Andric OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric static cl::opt<std::string>
790b57cec5SDimitry Andric SplitDwarfOutputFile("split-dwarf-output",
800b57cec5SDimitry Andric cl::desc(".dwo output filename"),
810b57cec5SDimitry Andric cl::value_desc("filename"));
820b57cec5SDimitry Andric
830b57cec5SDimitry Andric static cl::opt<unsigned>
840b57cec5SDimitry Andric TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
850b57cec5SDimitry Andric cl::value_desc("N"),
860b57cec5SDimitry Andric cl::desc("Repeat compilation N times for timing"));
870b57cec5SDimitry Andric
88349cc55cSDimitry Andric static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
89349cc55cSDimitry Andric
90349cc55cSDimitry Andric static cl::opt<unsigned> TimeTraceGranularity(
91349cc55cSDimitry Andric "time-trace-granularity",
92349cc55cSDimitry Andric cl::desc(
93349cc55cSDimitry Andric "Minimum time granularity (in microseconds) traced by time profiler"),
94349cc55cSDimitry Andric cl::init(500), cl::Hidden);
95349cc55cSDimitry Andric
96349cc55cSDimitry Andric static cl::opt<std::string>
97349cc55cSDimitry Andric TimeTraceFile("time-trace-file",
98349cc55cSDimitry Andric cl::desc("Specify time trace file destination"),
99349cc55cSDimitry Andric cl::value_desc("filename"));
100349cc55cSDimitry Andric
101e8d8bef9SDimitry Andric static cl::opt<std::string>
102e8d8bef9SDimitry Andric BinutilsVersion("binutils-version", cl::Hidden,
103e8d8bef9SDimitry Andric cl::desc("Produced object files can use all ELF features "
104e8d8bef9SDimitry Andric "supported by this binutils version and newer."
105e8d8bef9SDimitry Andric "If -no-integrated-as is specified, the generated "
106e8d8bef9SDimitry Andric "assembly will consider GNU as support."
107e8d8bef9SDimitry Andric "'none' means that all ELF features can be used, "
108e8d8bef9SDimitry Andric "regardless of binutils support"));
109e8d8bef9SDimitry Andric
1100b57cec5SDimitry Andric static cl::opt<bool>
1110b57cec5SDimitry Andric PreserveComments("preserve-as-comments", cl::Hidden,
1120b57cec5SDimitry Andric cl::desc("Preserve Comments in outputted assembly"),
1130b57cec5SDimitry Andric cl::init(true));
1140b57cec5SDimitry Andric
1150b57cec5SDimitry Andric // Determine optimization level.
1160b57cec5SDimitry Andric static cl::opt<char>
1170b57cec5SDimitry Andric OptLevel("O",
1180b57cec5SDimitry Andric cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
1190b57cec5SDimitry Andric "(default = '-O2')"),
120bdd1243dSDimitry Andric cl::Prefix, cl::init('2'));
1210b57cec5SDimitry Andric
1220b57cec5SDimitry Andric static cl::opt<std::string>
1230b57cec5SDimitry Andric TargetTriple("mtriple", cl::desc("Override target triple for module"));
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric static cl::opt<std::string> SplitDwarfFile(
1260b57cec5SDimitry Andric "split-dwarf-file",
1270b57cec5SDimitry Andric cl::desc(
1280b57cec5SDimitry Andric "Specify the name of the .dwo file to encode in the DWARF output"));
1290b57cec5SDimitry Andric
1300b57cec5SDimitry Andric static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
1310b57cec5SDimitry Andric cl::desc("Do not verify input module"));
1320b57cec5SDimitry Andric
1330b57cec5SDimitry Andric static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
1340b57cec5SDimitry Andric cl::desc("Disable simplify-libcalls"));
1350b57cec5SDimitry Andric
1360b57cec5SDimitry Andric static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
1370b57cec5SDimitry Andric cl::desc("Show encoding in .s output"));
1380b57cec5SDimitry Andric
139fe6060f1SDimitry Andric static cl::opt<bool>
140fe6060f1SDimitry Andric DwarfDirectory("dwarf-directory", cl::Hidden,
141fe6060f1SDimitry Andric cl::desc("Use .file directives with an explicit directory"),
142fe6060f1SDimitry Andric cl::init(true));
1430b57cec5SDimitry Andric
1440b57cec5SDimitry Andric static cl::opt<bool> AsmVerbose("asm-verbose",
1450b57cec5SDimitry Andric cl::desc("Add comments to directives."),
1460b57cec5SDimitry Andric cl::init(true));
1470b57cec5SDimitry Andric
1480b57cec5SDimitry Andric static cl::opt<bool>
1490b57cec5SDimitry Andric CompileTwice("compile-twice", cl::Hidden,
1500b57cec5SDimitry Andric cl::desc("Run everything twice, re-using the same pass "
1510b57cec5SDimitry Andric "manager and verify the result is the same."),
1520b57cec5SDimitry Andric cl::init(false));
1530b57cec5SDimitry Andric
1540b57cec5SDimitry Andric static cl::opt<bool> DiscardValueNames(
1550b57cec5SDimitry Andric "discard-value-names",
1560b57cec5SDimitry Andric cl::desc("Discard names from Value (other than GlobalValue)."),
1570b57cec5SDimitry Andric cl::init(false), cl::Hidden);
1580b57cec5SDimitry Andric
1590b57cec5SDimitry Andric static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
1600b57cec5SDimitry Andric
1610b57cec5SDimitry Andric static cl::opt<bool> RemarksWithHotness(
1620b57cec5SDimitry Andric "pass-remarks-with-hotness",
1630b57cec5SDimitry Andric cl::desc("With PGO, include profile count in optimization remarks"),
1640b57cec5SDimitry Andric cl::Hidden);
1650b57cec5SDimitry Andric
166bdd1243dSDimitry Andric static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
167e8d8bef9SDimitry Andric RemarksHotnessThreshold(
168e8d8bef9SDimitry Andric "pass-remarks-hotness-threshold",
1690b57cec5SDimitry Andric cl::desc("Minimum profile count required for "
170e8d8bef9SDimitry Andric "an optimization remark to be output. "
171e8d8bef9SDimitry Andric "Use 'auto' to apply the threshold from profile summary."),
172e8d8bef9SDimitry Andric cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
1730b57cec5SDimitry Andric
1740b57cec5SDimitry Andric static cl::opt<std::string>
1750b57cec5SDimitry Andric RemarksFilename("pass-remarks-output",
1760b57cec5SDimitry Andric cl::desc("Output filename for pass remarks"),
1770b57cec5SDimitry Andric cl::value_desc("filename"));
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric static cl::opt<std::string>
1800b57cec5SDimitry Andric RemarksPasses("pass-remarks-filter",
1810b57cec5SDimitry Andric cl::desc("Only record optimization remarks from passes whose "
1820b57cec5SDimitry Andric "names match the given regular expression"),
1830b57cec5SDimitry Andric cl::value_desc("regex"));
1840b57cec5SDimitry Andric
1850b57cec5SDimitry Andric static cl::opt<std::string> RemarksFormat(
1860b57cec5SDimitry Andric "pass-remarks-format",
1870b57cec5SDimitry Andric cl::desc("The format used for serializing remarks (default: YAML)"),
1880b57cec5SDimitry Andric cl::value_desc("format"), cl::init("yaml"));
1890b57cec5SDimitry Andric
1907a6dacacSDimitry Andric static cl::opt<bool> EnableNewPassManager(
1917a6dacacSDimitry Andric "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(false));
1927a6dacacSDimitry Andric
1937a6dacacSDimitry Andric // This flag specifies a textual description of the optimization pass pipeline
1947a6dacacSDimitry Andric // to run over the module. This flag switches opt to use the new pass manager
1957a6dacacSDimitry Andric // infrastructure, completely disabling all of the flags specific to the old
1967a6dacacSDimitry Andric // pass management.
1977a6dacacSDimitry Andric static cl::opt<std::string> PassPipeline(
1987a6dacacSDimitry Andric "passes",
1997a6dacacSDimitry Andric cl::desc(
2007a6dacacSDimitry Andric "A textual description of the pass pipeline. To have analysis passes "
2017a6dacacSDimitry Andric "available before a certain pass, add 'require<foo-analysis>'."));
2027a6dacacSDimitry Andric static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),
2037a6dacacSDimitry Andric cl::desc("Alias for -passes"));
2047a6dacacSDimitry Andric
2055f757f3fSDimitry Andric static cl::opt<bool> TryUseNewDbgInfoFormat(
2065f757f3fSDimitry Andric "try-experimental-debuginfo-iterators",
2075f757f3fSDimitry Andric cl::desc("Enable debuginfo iterator positions, if they're built in"),
2087a6dacacSDimitry Andric cl::init(false), cl::Hidden);
2095f757f3fSDimitry Andric
2105f757f3fSDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
2115f757f3fSDimitry Andric
2120b57cec5SDimitry Andric namespace {
213753f127fSDimitry Andric
getRunPassNames()214753f127fSDimitry Andric std::vector<std::string> &getRunPassNames() {
215753f127fSDimitry Andric static std::vector<std::string> RunPassNames;
216753f127fSDimitry Andric return RunPassNames;
217753f127fSDimitry Andric }
2180b57cec5SDimitry Andric
2190b57cec5SDimitry Andric struct RunPassOption {
operator =__anon964c1f4f0111::RunPassOption2200b57cec5SDimitry Andric void operator=(const std::string &Val) const {
2210b57cec5SDimitry Andric if (Val.empty())
2220b57cec5SDimitry Andric return;
2230b57cec5SDimitry Andric SmallVector<StringRef, 8> PassNames;
2240b57cec5SDimitry Andric StringRef(Val).split(PassNames, ',', -1, false);
2250b57cec5SDimitry Andric for (auto PassName : PassNames)
226753f127fSDimitry Andric getRunPassNames().push_back(std::string(PassName));
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric };
2295f757f3fSDimitry Andric } // namespace
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric static RunPassOption RunPassOpt;
2320b57cec5SDimitry Andric
2330b57cec5SDimitry Andric static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
2340b57cec5SDimitry Andric "run-pass",
2350b57cec5SDimitry Andric cl::desc("Run compiler only for specified passes (comma separated list)"),
23681ad6265SDimitry Andric cl::value_desc("pass-name"), cl::location(RunPassOpt));
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric static int compileModule(char **, LLVMContext &);
2390b57cec5SDimitry Andric
reportError(Twine Msg,StringRef Filename="")240349cc55cSDimitry Andric [[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
241e8d8bef9SDimitry Andric SmallString<256> Prefix;
242e8d8bef9SDimitry Andric if (!Filename.empty()) {
243e8d8bef9SDimitry Andric if (Filename == "-")
244e8d8bef9SDimitry Andric Filename = "<stdin>";
245e8d8bef9SDimitry Andric ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
246e8d8bef9SDimitry Andric }
247e8d8bef9SDimitry Andric WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
248e8d8bef9SDimitry Andric exit(1);
249e8d8bef9SDimitry Andric }
250e8d8bef9SDimitry Andric
reportError(Error Err,StringRef Filename)251349cc55cSDimitry Andric [[noreturn]] static void reportError(Error Err, StringRef Filename) {
252e8d8bef9SDimitry Andric assert(Err);
253e8d8bef9SDimitry Andric handleAllErrors(createFileError(Filename, std::move(Err)),
254e8d8bef9SDimitry Andric [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
255e8d8bef9SDimitry Andric llvm_unreachable("reportError() should not return");
256e8d8bef9SDimitry Andric }
257e8d8bef9SDimitry Andric
GetOutputStream(const char * TargetName,Triple::OSType OS,const char * ProgName)2580b57cec5SDimitry Andric static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
2590b57cec5SDimitry Andric Triple::OSType OS,
2600b57cec5SDimitry Andric const char *ProgName) {
2610b57cec5SDimitry Andric // If we don't yet have an output filename, make one.
2620b57cec5SDimitry Andric if (OutputFilename.empty()) {
2630b57cec5SDimitry Andric if (InputFilename == "-")
2640b57cec5SDimitry Andric OutputFilename = "-";
2650b57cec5SDimitry Andric else {
2660b57cec5SDimitry Andric // If InputFilename ends in .bc or .ll, remove it.
2670b57cec5SDimitry Andric StringRef IFN = InputFilename;
2685f757f3fSDimitry Andric if (IFN.ends_with(".bc") || IFN.ends_with(".ll"))
2695ffd83dbSDimitry Andric OutputFilename = std::string(IFN.drop_back(3));
2705f757f3fSDimitry Andric else if (IFN.ends_with(".mir"))
2715ffd83dbSDimitry Andric OutputFilename = std::string(IFN.drop_back(4));
2720b57cec5SDimitry Andric else
2735ffd83dbSDimitry Andric OutputFilename = std::string(IFN);
2740b57cec5SDimitry Andric
2755ffd83dbSDimitry Andric switch (codegen::getFileType()) {
2765f757f3fSDimitry Andric case CodeGenFileType::AssemblyFile:
2770b57cec5SDimitry Andric OutputFilename += ".s";
2780b57cec5SDimitry Andric break;
2795f757f3fSDimitry Andric case CodeGenFileType::ObjectFile:
2800b57cec5SDimitry Andric if (OS == Triple::Win32)
2810b57cec5SDimitry Andric OutputFilename += ".obj";
2820b57cec5SDimitry Andric else
2830b57cec5SDimitry Andric OutputFilename += ".o";
2840b57cec5SDimitry Andric break;
2855f757f3fSDimitry Andric case CodeGenFileType::Null:
286e8d8bef9SDimitry Andric OutputFilename = "-";
2870b57cec5SDimitry Andric break;
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric }
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric
2920b57cec5SDimitry Andric // Decide if we need "binary" output.
2930b57cec5SDimitry Andric bool Binary = false;
2945ffd83dbSDimitry Andric switch (codegen::getFileType()) {
2955f757f3fSDimitry Andric case CodeGenFileType::AssemblyFile:
2960b57cec5SDimitry Andric break;
2975f757f3fSDimitry Andric case CodeGenFileType::ObjectFile:
2985f757f3fSDimitry Andric case CodeGenFileType::Null:
2990b57cec5SDimitry Andric Binary = true;
3000b57cec5SDimitry Andric break;
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric
3030b57cec5SDimitry Andric // Open the file.
3040b57cec5SDimitry Andric std::error_code EC;
3058bcb0991SDimitry Andric sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
3060b57cec5SDimitry Andric if (!Binary)
307fe6060f1SDimitry Andric OpenFlags |= sys::fs::OF_TextWithCRLF;
3088bcb0991SDimitry Andric auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
3090b57cec5SDimitry Andric if (EC) {
310e8d8bef9SDimitry Andric reportError(EC.message());
3110b57cec5SDimitry Andric return nullptr;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric return FDOut;
3150b57cec5SDimitry Andric }
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric // main - Entry point for the llc compiler.
3180b57cec5SDimitry Andric //
main(int argc,char ** argv)3190b57cec5SDimitry Andric int main(int argc, char **argv) {
3200b57cec5SDimitry Andric InitLLVM X(argc, argv);
3210b57cec5SDimitry Andric
3220b57cec5SDimitry Andric // Enable debug stream buffering.
3230b57cec5SDimitry Andric EnableDebugBuffering = true;
3240b57cec5SDimitry Andric
3250b57cec5SDimitry Andric // Initialize targets first, so that --version shows registered targets.
3260b57cec5SDimitry Andric InitializeAllTargets();
3270b57cec5SDimitry Andric InitializeAllTargetMCs();
3280b57cec5SDimitry Andric InitializeAllAsmPrinters();
3290b57cec5SDimitry Andric InitializeAllAsmParsers();
3300b57cec5SDimitry Andric
3310b57cec5SDimitry Andric // Initialize codegen and IR passes used by llc so that the -print-after,
3320b57cec5SDimitry Andric // -print-before, and -stop-after options work.
3330b57cec5SDimitry Andric PassRegistry *Registry = PassRegistry::getPassRegistry();
3340b57cec5SDimitry Andric initializeCore(*Registry);
3350b57cec5SDimitry Andric initializeCodeGen(*Registry);
3360b57cec5SDimitry Andric initializeLoopStrengthReducePass(*Registry);
3370b57cec5SDimitry Andric initializeLowerIntrinsicsPass(*Registry);
338*0fca6ea1SDimitry Andric initializePostInlineEntryExitInstrumenterPass(*Registry);
3390b57cec5SDimitry Andric initializeUnreachableBlockElimLegacyPassPass(*Registry);
3400b57cec5SDimitry Andric initializeConstantHoistingLegacyPassPass(*Registry);
3410b57cec5SDimitry Andric initializeScalarOpts(*Registry);
3420b57cec5SDimitry Andric initializeVectorization(*Registry);
343e8d8bef9SDimitry Andric initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
3440b57cec5SDimitry Andric initializeExpandReductionsPass(*Registry);
345fe6060f1SDimitry Andric initializeExpandVectorPredicationPass(*Registry);
34606c3fb27SDimitry Andric initializeHardwareLoopsLegacyPass(*Registry);
3475ffd83dbSDimitry Andric initializeTransformUtils(*Registry);
348fe6060f1SDimitry Andric initializeReplaceWithVeclibLegacyPass(*Registry);
34981ad6265SDimitry Andric initializeTLSVariableHoistLegacyPassPass(*Registry);
3500b57cec5SDimitry Andric
3510b57cec5SDimitry Andric // Initialize debugging passes.
3520b57cec5SDimitry Andric initializeScavengerTestPass(*Registry);
3530b57cec5SDimitry Andric
354bdd1243dSDimitry Andric // Register the Target and CPU printer for --version.
355bdd1243dSDimitry Andric cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
3560b57cec5SDimitry Andric // Register the target printer for --version.
3570b57cec5SDimitry Andric cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
3580b57cec5SDimitry Andric
3590b57cec5SDimitry Andric cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
3600b57cec5SDimitry Andric
3617a6dacacSDimitry Andric if (!PassPipeline.empty() && !getRunPassNames().empty()) {
3627a6dacacSDimitry Andric errs() << "The `llc -run-pass=...` syntax for the new pass manager is "
3637a6dacacSDimitry Andric "not supported, please use `llc -passes=<pipeline>` (or the `-p` "
3647a6dacacSDimitry Andric "alias for a more concise version).\n";
3657a6dacacSDimitry Andric return 1;
3667a6dacacSDimitry Andric }
3677a6dacacSDimitry Andric
3685f757f3fSDimitry Andric // RemoveDIs debug-info transition: tests may request that we /try/ to use the
369*0fca6ea1SDimitry Andric // new debug-info format.
3705f757f3fSDimitry Andric if (TryUseNewDbgInfoFormat) {
371*0fca6ea1SDimitry Andric // Turn the new debug-info format on.
3725f757f3fSDimitry Andric UseNewDbgInfoFormat = true;
3735f757f3fSDimitry Andric }
3745f757f3fSDimitry Andric
375349cc55cSDimitry Andric if (TimeTrace)
376349cc55cSDimitry Andric timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
377349cc55cSDimitry Andric auto TimeTraceScopeExit = make_scope_exit([]() {
378349cc55cSDimitry Andric if (TimeTrace) {
379349cc55cSDimitry Andric if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
380349cc55cSDimitry Andric handleAllErrors(std::move(E), [&](const StringError &SE) {
381349cc55cSDimitry Andric errs() << SE.getMessage() << "\n";
382349cc55cSDimitry Andric });
383349cc55cSDimitry Andric return;
384349cc55cSDimitry Andric }
385349cc55cSDimitry Andric timeTraceProfilerCleanup();
386349cc55cSDimitry Andric }
387349cc55cSDimitry Andric });
388349cc55cSDimitry Andric
389349cc55cSDimitry Andric LLVMContext Context;
3900b57cec5SDimitry Andric Context.setDiscardValueNames(DiscardValueNames);
3910b57cec5SDimitry Andric
3920b57cec5SDimitry Andric // Set a diagnostic handler that doesn't exit on the first error
393cb14a3feSDimitry Andric Context.setDiagnosticHandler(std::make_unique<LLCDiagnosticHandler>());
3940b57cec5SDimitry Andric
3950b57cec5SDimitry Andric Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
3965ffd83dbSDimitry Andric setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
3970b57cec5SDimitry Andric RemarksFormat, RemarksWithHotness,
3980b57cec5SDimitry Andric RemarksHotnessThreshold);
399e8d8bef9SDimitry Andric if (Error E = RemarksFileOrErr.takeError())
400e8d8bef9SDimitry Andric reportError(std::move(E), RemarksFilename);
4010b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
4020b57cec5SDimitry Andric
403e8d8bef9SDimitry Andric if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
404e8d8bef9SDimitry Andric reportError("input language must be '', 'IR' or 'MIR'");
4050b57cec5SDimitry Andric
4060b57cec5SDimitry Andric // Compile the module TimeCompilations times to give better compile time
4070b57cec5SDimitry Andric // metrics.
4080b57cec5SDimitry Andric for (unsigned I = TimeCompilations; I; --I)
4090b57cec5SDimitry Andric if (int RetVal = compileModule(argv, Context))
4100b57cec5SDimitry Andric return RetVal;
4110b57cec5SDimitry Andric
4120b57cec5SDimitry Andric if (RemarksFile)
4130b57cec5SDimitry Andric RemarksFile->keep();
4140b57cec5SDimitry Andric return 0;
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric
addPass(PassManagerBase & PM,const char * argv0,StringRef PassName,TargetPassConfig & TPC)4170b57cec5SDimitry Andric static bool addPass(PassManagerBase &PM, const char *argv0,
4180b57cec5SDimitry Andric StringRef PassName, TargetPassConfig &TPC) {
4190b57cec5SDimitry Andric if (PassName == "none")
4200b57cec5SDimitry Andric return false;
4210b57cec5SDimitry Andric
4220b57cec5SDimitry Andric const PassRegistry *PR = PassRegistry::getPassRegistry();
4230b57cec5SDimitry Andric const PassInfo *PI = PR->getPassInfo(PassName);
4240b57cec5SDimitry Andric if (!PI) {
4250b57cec5SDimitry Andric WithColor::error(errs(), argv0)
4260b57cec5SDimitry Andric << "run-pass " << PassName << " is not registered.\n";
4270b57cec5SDimitry Andric return true;
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric
4300b57cec5SDimitry Andric Pass *P;
4310b57cec5SDimitry Andric if (PI->getNormalCtor())
4320b57cec5SDimitry Andric P = PI->getNormalCtor()();
4330b57cec5SDimitry Andric else {
4340b57cec5SDimitry Andric WithColor::error(errs(), argv0)
4350b57cec5SDimitry Andric << "cannot create pass: " << PI->getPassName() << "\n";
4360b57cec5SDimitry Andric return true;
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric std::string Banner = std::string("After ") + std::string(P->getPassName());
4395ffd83dbSDimitry Andric TPC.addMachinePrePasses();
4400b57cec5SDimitry Andric PM.add(P);
4415ffd83dbSDimitry Andric TPC.addMachinePostPasses(Banner);
4420b57cec5SDimitry Andric
4430b57cec5SDimitry Andric return false;
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric
compileModule(char ** argv,LLVMContext & Context)4460b57cec5SDimitry Andric static int compileModule(char **argv, LLVMContext &Context) {
4470b57cec5SDimitry Andric // Load the module to be compiled...
4480b57cec5SDimitry Andric SMDiagnostic Err;
4490b57cec5SDimitry Andric std::unique_ptr<Module> M;
4500b57cec5SDimitry Andric std::unique_ptr<MIRParser> MIR;
4510b57cec5SDimitry Andric Triple TheTriple;
4525ffd83dbSDimitry Andric std::string CPUStr = codegen::getCPUStr(),
4535ffd83dbSDimitry Andric FeaturesStr = codegen::getFeaturesStr();
454480093f4SDimitry Andric
455480093f4SDimitry Andric // Set attributes on functions as loaded from MIR from command line arguments.
456480093f4SDimitry Andric auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
4575ffd83dbSDimitry Andric codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
458480093f4SDimitry Andric };
4590b57cec5SDimitry Andric
4605ffd83dbSDimitry Andric auto MAttrs = codegen::getMAttrs();
461bdd1243dSDimitry Andric bool SkipModule =
462bdd1243dSDimitry Andric CPUStr == "help" || (!MAttrs.empty() && MAttrs.front() == "help");
4630b57cec5SDimitry Andric
4645f757f3fSDimitry Andric CodeGenOptLevel OLvl;
465bdd1243dSDimitry Andric if (auto Level = CodeGenOpt::parseLevel(OptLevel)) {
466bdd1243dSDimitry Andric OLvl = *Level;
467bdd1243dSDimitry Andric } else {
4680b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
4690b57cec5SDimitry Andric return 1;
4700b57cec5SDimitry Andric }
4710b57cec5SDimitry Andric
472e8d8bef9SDimitry Andric // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
473e8d8bef9SDimitry Andric // use that to indicate the MC default.
474e8d8bef9SDimitry Andric if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
475e8d8bef9SDimitry Andric StringRef V = BinutilsVersion.getValue();
476e8d8bef9SDimitry Andric unsigned Num;
477e8d8bef9SDimitry Andric if (V.consumeInteger(10, Num) || Num == 0 ||
478e8d8bef9SDimitry Andric !(V.empty() ||
479e8d8bef9SDimitry Andric (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
480e8d8bef9SDimitry Andric WithColor::error(errs(), argv[0])
481e8d8bef9SDimitry Andric << "invalid -binutils-version, accepting 'none' or major.minor\n";
482e8d8bef9SDimitry Andric return 1;
483e8d8bef9SDimitry Andric }
484e8d8bef9SDimitry Andric }
485e8d8bef9SDimitry Andric TargetOptions Options;
486e8d8bef9SDimitry Andric auto InitializeOptions = [&](const Triple &TheTriple) {
487e8d8bef9SDimitry Andric Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
48806c3fb27SDimitry Andric
48906c3fb27SDimitry Andric if (Options.XCOFFReadOnlyPointers) {
49006c3fb27SDimitry Andric if (!TheTriple.isOSAIX())
49106c3fb27SDimitry Andric reportError("-mxcoff-roptr option is only supported on AIX",
49206c3fb27SDimitry Andric InputFilename);
49306c3fb27SDimitry Andric
49406c3fb27SDimitry Andric // Since the storage mapping class is specified per csect,
49506c3fb27SDimitry Andric // without using data sections, it is less effective to use read-only
49606c3fb27SDimitry Andric // pointers. Using read-only pointers may cause other RO variables in the
49706c3fb27SDimitry Andric // same csect to become RW when the linker acts upon `-bforceimprw`;
49806c3fb27SDimitry Andric // therefore, we require that separate data sections are used in the
49906c3fb27SDimitry Andric // presence of ReadOnlyPointers. We respect the setting of data-sections
50006c3fb27SDimitry Andric // since we have not found reasons to do otherwise that overcome the user
50106c3fb27SDimitry Andric // surprise of not respecting the setting.
50206c3fb27SDimitry Andric if (!Options.DataSections)
50306c3fb27SDimitry Andric reportError("-mxcoff-roptr option must be used with -data-sections",
50406c3fb27SDimitry Andric InputFilename);
50506c3fb27SDimitry Andric }
50606c3fb27SDimitry Andric
507e8d8bef9SDimitry Andric Options.BinutilsVersion =
508e8d8bef9SDimitry Andric TargetMachine::parseBinutilsVersion(BinutilsVersion);
5090b57cec5SDimitry Andric Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
5100b57cec5SDimitry Andric Options.MCOptions.AsmVerbose = AsmVerbose;
5110b57cec5SDimitry Andric Options.MCOptions.PreserveAsmComments = PreserveComments;
5120b57cec5SDimitry Andric Options.MCOptions.IASSearchPaths = IncludeDirs;
5130b57cec5SDimitry Andric Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
51481ad6265SDimitry Andric if (DwarfDirectory.getPosition()) {
51581ad6265SDimitry Andric Options.MCOptions.MCUseDwarfDirectory =
51681ad6265SDimitry Andric DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
51781ad6265SDimitry Andric : MCTargetOptions::DisableDwarfDirectory;
51881ad6265SDimitry Andric } else {
51981ad6265SDimitry Andric // -dwarf-directory is not set explicitly. Some assemblers
52081ad6265SDimitry Andric // (e.g. GNU as or ptxas) do not support `.file directory'
52181ad6265SDimitry Andric // syntax prior to DWARFv5. Let the target decide the default
52281ad6265SDimitry Andric // value.
52381ad6265SDimitry Andric Options.MCOptions.MCUseDwarfDirectory =
52481ad6265SDimitry Andric MCTargetOptions::DefaultDwarfDirectory;
52581ad6265SDimitry Andric }
526e8d8bef9SDimitry Andric };
5270b57cec5SDimitry Andric
528bdd1243dSDimitry Andric std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
529bdd1243dSDimitry Andric std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
5300b57cec5SDimitry Andric
5315ffd83dbSDimitry Andric const Target *TheTarget = nullptr;
5325ffd83dbSDimitry Andric std::unique_ptr<TargetMachine> Target;
5335ffd83dbSDimitry Andric
5345ffd83dbSDimitry Andric // If user just wants to list available options, skip module loading
5355ffd83dbSDimitry Andric if (!SkipModule) {
536bdd1243dSDimitry Andric auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,
537bdd1243dSDimitry Andric StringRef OldDLStr) -> std::optional<std::string> {
5385ffd83dbSDimitry Andric // If we are supposed to override the target triple, do so now.
5395ffd83dbSDimitry Andric std::string IRTargetTriple = DataLayoutTargetTriple.str();
5405ffd83dbSDimitry Andric if (!TargetTriple.empty())
5415ffd83dbSDimitry Andric IRTargetTriple = Triple::normalize(TargetTriple);
5425ffd83dbSDimitry Andric TheTriple = Triple(IRTargetTriple);
5435ffd83dbSDimitry Andric if (TheTriple.getTriple().empty())
5445ffd83dbSDimitry Andric TheTriple.setTriple(sys::getDefaultTargetTriple());
5455ffd83dbSDimitry Andric
5465ffd83dbSDimitry Andric std::string Error;
5475ffd83dbSDimitry Andric TheTarget =
5485ffd83dbSDimitry Andric TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
5495ffd83dbSDimitry Andric if (!TheTarget) {
5505ffd83dbSDimitry Andric WithColor::error(errs(), argv[0]) << Error;
5515ffd83dbSDimitry Andric exit(1);
5525ffd83dbSDimitry Andric }
5535ffd83dbSDimitry Andric
554e8d8bef9SDimitry Andric InitializeOptions(TheTriple);
5555ffd83dbSDimitry Andric Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
55681ad6265SDimitry Andric TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
5575ffd83dbSDimitry Andric assert(Target && "Could not allocate target machine!");
5585ffd83dbSDimitry Andric
5595ffd83dbSDimitry Andric return Target->createDataLayout().getStringRepresentation();
5605ffd83dbSDimitry Andric };
5615ffd83dbSDimitry Andric if (InputLanguage == "mir" ||
5625f757f3fSDimitry Andric (InputLanguage == "" && StringRef(InputFilename).ends_with(".mir"))) {
5635ffd83dbSDimitry Andric MIR = createMIRParserFromFile(InputFilename, Err, Context,
5645ffd83dbSDimitry Andric setMIRFunctionAttributes);
5655ffd83dbSDimitry Andric if (MIR)
5665ffd83dbSDimitry Andric M = MIR->parseIRModule(SetDataLayout);
5675ffd83dbSDimitry Andric } else {
568bdd1243dSDimitry Andric M = parseIRFile(InputFilename, Err, Context,
569bdd1243dSDimitry Andric ParserCallbacks(SetDataLayout));
5705ffd83dbSDimitry Andric }
5715ffd83dbSDimitry Andric if (!M) {
5725ffd83dbSDimitry Andric Err.print(argv[0], WithColor::error(errs(), argv[0]));
5735ffd83dbSDimitry Andric return 1;
5745ffd83dbSDimitry Andric }
5755ffd83dbSDimitry Andric if (!TargetTriple.empty())
5765ffd83dbSDimitry Andric M->setTargetTriple(Triple::normalize(TargetTriple));
57781ad6265SDimitry Andric
578bdd1243dSDimitry Andric std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
57981ad6265SDimitry Andric if (!CM && CM_IR)
580bdd1243dSDimitry Andric Target->setCodeModel(*CM_IR);
5815f757f3fSDimitry Andric if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
5825f757f3fSDimitry Andric Target->setLargeDataThreshold(*LDT);
5835ffd83dbSDimitry Andric } else {
5845ffd83dbSDimitry Andric TheTriple = Triple(Triple::normalize(TargetTriple));
5855ffd83dbSDimitry Andric if (TheTriple.getTriple().empty())
5865ffd83dbSDimitry Andric TheTriple.setTriple(sys::getDefaultTargetTriple());
5875ffd83dbSDimitry Andric
5885ffd83dbSDimitry Andric // Get the target specific parser.
5895ffd83dbSDimitry Andric std::string Error;
5905ffd83dbSDimitry Andric TheTarget =
5915ffd83dbSDimitry Andric TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
5925ffd83dbSDimitry Andric if (!TheTarget) {
5935ffd83dbSDimitry Andric WithColor::error(errs(), argv[0]) << Error;
5945ffd83dbSDimitry Andric return 1;
5955ffd83dbSDimitry Andric }
5965ffd83dbSDimitry Andric
597e8d8bef9SDimitry Andric InitializeOptions(TheTriple);
5985ffd83dbSDimitry Andric Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
59981ad6265SDimitry Andric TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
6000b57cec5SDimitry Andric assert(Target && "Could not allocate target machine!");
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric // If we don't have a module then just exit now. We do this down
6030b57cec5SDimitry Andric // here since the CPU/Feature help is underneath the target machine
6040b57cec5SDimitry Andric // creation.
6050b57cec5SDimitry Andric return 0;
6065ffd83dbSDimitry Andric }
6070b57cec5SDimitry Andric
6080b57cec5SDimitry Andric assert(M && "Should have exited if we didn't have a module!");
6095ffd83dbSDimitry Andric if (codegen::getFloatABIForCalls() != FloatABI::Default)
6105f757f3fSDimitry Andric Target->Options.FloatABIType = codegen::getFloatABIForCalls();
6110b57cec5SDimitry Andric
6120b57cec5SDimitry Andric // Figure out where we are going to send the output.
6130b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> Out =
6140b57cec5SDimitry Andric GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
6150b57cec5SDimitry Andric if (!Out) return 1;
6160b57cec5SDimitry Andric
6170eae32dcSDimitry Andric // Ensure the filename is passed down to CodeViewDebug.
6180eae32dcSDimitry Andric Target->Options.ObjectFilenameForDebug = Out->outputFilename();
6190eae32dcSDimitry Andric
6200b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> DwoOut;
6210b57cec5SDimitry Andric if (!SplitDwarfOutputFile.empty()) {
6220b57cec5SDimitry Andric std::error_code EC;
6238bcb0991SDimitry Andric DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
6248bcb0991SDimitry Andric sys::fs::OF_None);
625e8d8bef9SDimitry Andric if (EC)
626e8d8bef9SDimitry Andric reportError(EC.message(), SplitDwarfOutputFile);
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric
6290b57cec5SDimitry Andric // Add an appropriate TargetLibraryInfo pass for the module's triple.
6300b57cec5SDimitry Andric TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric // The -disable-simplify-libcalls flag actually disables all builtin optzns.
6330b57cec5SDimitry Andric if (DisableSimplifyLibCalls)
6340b57cec5SDimitry Andric TLII.disableAllFunctions();
6350b57cec5SDimitry Andric
6360b57cec5SDimitry Andric // Verify module immediately to catch problems before doInitialization() is
6370b57cec5SDimitry Andric // called on any passes.
638e8d8bef9SDimitry Andric if (!NoVerify && verifyModule(*M, &errs()))
639e8d8bef9SDimitry Andric reportError("input module cannot be verified", InputFilename);
6400b57cec5SDimitry Andric
6410b57cec5SDimitry Andric // Override function attributes based on CPUStr, FeaturesStr, and command line
6420b57cec5SDimitry Andric // flags.
6435ffd83dbSDimitry Andric codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
6440b57cec5SDimitry Andric
6455f757f3fSDimitry Andric if (mc::getExplicitRelaxAll() &&
6465f757f3fSDimitry Andric codegen::getFileType() != CodeGenFileType::ObjectFile)
6470b57cec5SDimitry Andric WithColor::warning(errs(), argv[0])
6480b57cec5SDimitry Andric << ": warning: ignoring -mc-relax-all because filetype != obj";
6490b57cec5SDimitry Andric
6507a6dacacSDimitry Andric if (EnableNewPassManager || !PassPipeline.empty()) {
6517a6dacacSDimitry Andric return compileModuleWithNewPM(argv[0], std::move(M), std::move(MIR),
6527a6dacacSDimitry Andric std::move(Target), std::move(Out),
6537a6dacacSDimitry Andric std::move(DwoOut), Context, TLII, NoVerify,
6547a6dacacSDimitry Andric PassPipeline, codegen::getFileType());
6557a6dacacSDimitry Andric }
6567a6dacacSDimitry Andric
6577a6dacacSDimitry Andric // Build up all of the passes that we want to do to the module.
6587a6dacacSDimitry Andric legacy::PassManager PM;
6597a6dacacSDimitry Andric PM.add(new TargetLibraryInfoWrapperPass(TLII));
6607a6dacacSDimitry Andric
6610b57cec5SDimitry Andric {
6620b57cec5SDimitry Andric raw_pwrite_stream *OS = &Out->os();
6630b57cec5SDimitry Andric
6640b57cec5SDimitry Andric // Manually do the buffering rather than using buffer_ostream,
6650b57cec5SDimitry Andric // so we can memcmp the contents in CompileTwice mode
6660b57cec5SDimitry Andric SmallVector<char, 0> Buffer;
6670b57cec5SDimitry Andric std::unique_ptr<raw_svector_ostream> BOS;
6685f757f3fSDimitry Andric if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
6690b57cec5SDimitry Andric !Out->os().supportsSeeking()) ||
6700b57cec5SDimitry Andric CompileTwice) {
6718bcb0991SDimitry Andric BOS = std::make_unique<raw_svector_ostream>(Buffer);
6720b57cec5SDimitry Andric OS = BOS.get();
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric
6750b57cec5SDimitry Andric const char *argv0 = argv[0];
6760b57cec5SDimitry Andric LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
6778bcb0991SDimitry Andric MachineModuleInfoWrapperPass *MMIWP =
6788bcb0991SDimitry Andric new MachineModuleInfoWrapperPass(&LLVMTM);
6790b57cec5SDimitry Andric
6800b57cec5SDimitry Andric // Construct a custom pass pipeline that starts after instruction
6810b57cec5SDimitry Andric // selection.
682753f127fSDimitry Andric if (!getRunPassNames().empty()) {
6830b57cec5SDimitry Andric if (!MIR) {
6840b57cec5SDimitry Andric WithColor::warning(errs(), argv[0])
6850b57cec5SDimitry Andric << "run-pass is for .mir file only.\n";
68606c3fb27SDimitry Andric delete MMIWP;
6870b57cec5SDimitry Andric return 1;
6880b57cec5SDimitry Andric }
68906c3fb27SDimitry Andric TargetPassConfig *PTPC = LLVMTM.createPassConfig(PM);
69006c3fb27SDimitry Andric TargetPassConfig &TPC = *PTPC;
6910b57cec5SDimitry Andric if (TPC.hasLimitedCodeGenPipeline()) {
6920b57cec5SDimitry Andric WithColor::warning(errs(), argv[0])
6930b57cec5SDimitry Andric << "run-pass cannot be used with "
6947a6dacacSDimitry Andric << TPC.getLimitedCodeGenPipelineReason() << ".\n";
69506c3fb27SDimitry Andric delete PTPC;
69606c3fb27SDimitry Andric delete MMIWP;
6970b57cec5SDimitry Andric return 1;
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric
7000b57cec5SDimitry Andric TPC.setDisableVerify(NoVerify);
7010b57cec5SDimitry Andric PM.add(&TPC);
7028bcb0991SDimitry Andric PM.add(MMIWP);
7030b57cec5SDimitry Andric TPC.printAndVerify("");
704753f127fSDimitry Andric for (const std::string &RunPassName : getRunPassNames()) {
7050b57cec5SDimitry Andric if (addPass(PM, argv0, RunPassName, TPC))
7060b57cec5SDimitry Andric return 1;
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric TPC.setInitialized();
7090b57cec5SDimitry Andric PM.add(createPrintMIRPass(*OS));
7100b57cec5SDimitry Andric PM.add(createFreeMachineFunctionPass());
7115ffd83dbSDimitry Andric } else if (Target->addPassesToEmitFile(
7125ffd83dbSDimitry Andric PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
7135ffd83dbSDimitry Andric codegen::getFileType(), NoVerify, MMIWP)) {
714e8d8bef9SDimitry Andric reportError("target does not support generation of this file type");
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric
7175ffd83dbSDimitry Andric const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
7185ffd83dbSDimitry Andric ->Initialize(MMIWP->getMMI().getContext(), *Target);
7190b57cec5SDimitry Andric if (MIR) {
7208bcb0991SDimitry Andric assert(MMIWP && "Forgot to create MMIWP?");
7218bcb0991SDimitry Andric if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
7220b57cec5SDimitry Andric return 1;
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric
7250b57cec5SDimitry Andric // Before executing passes, print the final values of the LLVM options.
7260b57cec5SDimitry Andric cl::PrintOptionValues();
7270b57cec5SDimitry Andric
7280b57cec5SDimitry Andric // If requested, run the pass manager over the same module again,
7290b57cec5SDimitry Andric // to catch any bugs due to persistent state in the passes. Note that
7300b57cec5SDimitry Andric // opt has the same functionality, so it may be worth abstracting this out
7310b57cec5SDimitry Andric // in the future.
7320b57cec5SDimitry Andric SmallVector<char, 0> CompileTwiceBuffer;
7330b57cec5SDimitry Andric if (CompileTwice) {
7340b57cec5SDimitry Andric std::unique_ptr<Module> M2(llvm::CloneModule(*M));
7350b57cec5SDimitry Andric PM.run(*M2);
7360b57cec5SDimitry Andric CompileTwiceBuffer = Buffer;
7370b57cec5SDimitry Andric Buffer.clear();
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric
7400b57cec5SDimitry Andric PM.run(*M);
7410b57cec5SDimitry Andric
742cb14a3feSDimitry Andric if (Context.getDiagHandlerPtr()->HasErrors)
7430b57cec5SDimitry Andric return 1;
7440b57cec5SDimitry Andric
7450b57cec5SDimitry Andric // Compare the two outputs and make sure they're the same
7460b57cec5SDimitry Andric if (CompileTwice) {
7470b57cec5SDimitry Andric if (Buffer.size() != CompileTwiceBuffer.size() ||
7480b57cec5SDimitry Andric (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
7490b57cec5SDimitry Andric 0)) {
7500b57cec5SDimitry Andric errs()
7510b57cec5SDimitry Andric << "Running the pass manager twice changed the output.\n"
7520b57cec5SDimitry Andric "Writing the result of the second run to the specified output\n"
7530b57cec5SDimitry Andric "To generate the one-run comparison binary, just run without\n"
7540b57cec5SDimitry Andric "the compile-twice option\n";
7550b57cec5SDimitry Andric Out->os() << Buffer;
7560b57cec5SDimitry Andric Out->keep();
7570b57cec5SDimitry Andric return 1;
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric
7610b57cec5SDimitry Andric if (BOS) {
7620b57cec5SDimitry Andric Out->os() << Buffer;
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric
7660b57cec5SDimitry Andric // Declare success.
7670b57cec5SDimitry Andric Out->keep();
7680b57cec5SDimitry Andric if (DwoOut)
7690b57cec5SDimitry Andric DwoOut->keep();
7700b57cec5SDimitry Andric
7710b57cec5SDimitry Andric return 0;
7720b57cec5SDimitry Andric }
773