1210284Sjmallett//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2232812Sjmallett//
3215990Sjmallett// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4210284Sjmallett// See https://llvm.org/LICENSE.txt for license information.
5210284Sjmallett// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6215990Sjmallett//
7215990Sjmallett//===----------------------------------------------------------------------===//
8215990Sjmallett//
9210284Sjmallett// This is the llc code generator driver. It provides a convenient
10215990Sjmallett// command-line interface for generating native assembly-language code
11215990Sjmallett// or C code, given LLVM bitcode.
12210284Sjmallett//
13215990Sjmallett//===----------------------------------------------------------------------===//
14215990Sjmallett
15215990Sjmallett#include "llvm/ADT/STLExtras.h"
16215990Sjmallett#include "llvm/ADT/Triple.h"
17215990Sjmallett#include "llvm/Analysis/TargetLibraryInfo.h"
18232812Sjmallett#include "llvm/CodeGen/CommandFlags.h"
19215990Sjmallett#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20215990Sjmallett#include "llvm/CodeGen/LinkAllCodegenComponents.h"
21215990Sjmallett#include "llvm/CodeGen/MIRParser/MIRParser.h"
22215990Sjmallett#include "llvm/CodeGen/MachineFunctionPass.h"
23215990Sjmallett#include "llvm/CodeGen/MachineModuleInfo.h"
24215990Sjmallett#include "llvm/CodeGen/TargetPassConfig.h"
25215990Sjmallett#include "llvm/CodeGen/TargetSubtargetInfo.h"
26215990Sjmallett#include "llvm/IR/AutoUpgrade.h"
27215990Sjmallett#include "llvm/IR/DataLayout.h"
28215990Sjmallett#include "llvm/IR/DiagnosticInfo.h"
29232812Sjmallett#include "llvm/IR/DiagnosticPrinter.h"
30215990Sjmallett#include "llvm/IR/IRPrintingPasses.h"
31215990Sjmallett#include "llvm/IR/LLVMContext.h"
32215990Sjmallett#include "llvm/IR/LLVMRemarkStreamer.h"
33215990Sjmallett#include "llvm/IR/LegacyPassManager.h"
34215990Sjmallett#include "llvm/IR/Module.h"
35215990Sjmallett#include "llvm/IR/Verifier.h"
36215990Sjmallett#include "llvm/IRReader/IRReader.h"
37215990Sjmallett#include "llvm/InitializePasses.h"
38210284Sjmallett#include "llvm/MC/SubtargetFeature.h"
39210284Sjmallett#include "llvm/Pass.h"
40210284Sjmallett#include "llvm/Remarks/HotnessThresholdParser.h"
41210284Sjmallett#include "llvm/Support/CommandLine.h"
42210284Sjmallett#include "llvm/Support/Debug.h"
43210284Sjmallett#include "llvm/Support/FileSystem.h"
44210284Sjmallett#include "llvm/Support/FormattedStream.h"
45215990Sjmallett#include "llvm/Support/Host.h"
46210284Sjmallett#include "llvm/Support/InitLLVM.h"
47210284Sjmallett#include "llvm/Support/ManagedStatic.h"
48210284Sjmallett#include "llvm/Support/PluginLoader.h"
49210284Sjmallett#include "llvm/Support/SourceMgr.h"
50210284Sjmallett#include "llvm/Support/TargetRegistry.h"
51232812Sjmallett#include "llvm/Support/TargetSelect.h"
52210284Sjmallett#include "llvm/Support/ToolOutputFile.h"
53210284Sjmallett#include "llvm/Support/WithColor.h"
54210284Sjmallett#include "llvm/Target/TargetLoweringObjectFile.h"
55210284Sjmallett#include "llvm/Target/TargetMachine.h"
56210284Sjmallett#include "llvm/Transforms/Utils/Cloning.h"
57210284Sjmallett#include <memory>
58210284Sjmallettusing namespace llvm;
59210284Sjmallett
60210284Sjmallettstatic codegen::RegisterCodeGenFlags CGF;
61210284Sjmallett
62210284Sjmallett// General options for llc.  Other pass-specific options are specified
63210284Sjmallett// within the corresponding llc passes, and target-specific options
64210284Sjmallett// and back-end code generation options are specified with the target machine.
65210284Sjmallett//
66210284Sjmallettstatic cl::opt<std::string>
67210284SjmallettInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
68210284Sjmallett
69210284Sjmallettstatic cl::opt<std::string>
70210284SjmallettInputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
71210284Sjmallett
72210284Sjmallettstatic cl::opt<std::string>
73210284SjmallettOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
74210284Sjmallett
75210284Sjmallettstatic cl::opt<std::string>
76210284Sjmallett    SplitDwarfOutputFile("split-dwarf-output",
77210284Sjmallett                         cl::desc(".dwo output filename"),
78210284Sjmallett                         cl::value_desc("filename"));
79210284Sjmallett
80210284Sjmallettstatic cl::opt<unsigned>
81210284SjmallettTimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
82210284Sjmallett                 cl::value_desc("N"),
83210284Sjmallett                 cl::desc("Repeat compilation N times for timing"));
84210284Sjmallett
85210284Sjmallettstatic cl::opt<std::string>
86210284Sjmallett    BinutilsVersion("binutils-version", cl::Hidden,
87210284Sjmallett                    cl::desc("Produced object files can use all ELF features "
88210284Sjmallett                             "supported by this binutils version and newer."
89210284Sjmallett                             "If -no-integrated-as is specified, the generated "
90210284Sjmallett                             "assembly will consider GNU as support."
91210284Sjmallett                             "'none' means that all ELF features can be used, "
92210284Sjmallett                             "regardless of binutils support"));
93210284Sjmallett
94210284Sjmallettstatic cl::opt<bool>
95210284SjmallettNoIntegratedAssembler("no-integrated-as", cl::Hidden,
96210284Sjmallett                      cl::desc("Disable integrated assembler"));
97210284Sjmallett
98210284Sjmallettstatic cl::opt<bool>
99210284Sjmallett    PreserveComments("preserve-as-comments", cl::Hidden,
100210284Sjmallett                     cl::desc("Preserve Comments in outputted assembly"),
101210284Sjmallett                     cl::init(true));
102210284Sjmallett
103210284Sjmallett// Determine optimization level.
104210284Sjmallettstatic cl::opt<char>
105210284SjmallettOptLevel("O",
106210284Sjmallett         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
107210284Sjmallett                  "(default = '-O2')"),
108210284Sjmallett         cl::Prefix,
109210284Sjmallett         cl::ZeroOrMore,
110210284Sjmallett         cl::init(' '));
111210284Sjmallett
112210284Sjmallettstatic cl::opt<std::string>
113210284SjmallettTargetTriple("mtriple", cl::desc("Override target triple for module"));
114210284Sjmallett
115210284Sjmallettstatic cl::opt<std::string> SplitDwarfFile(
116210284Sjmallett    "split-dwarf-file",
117210284Sjmallett    cl::desc(
118210284Sjmallett        "Specify the name of the .dwo file to encode in the DWARF output"));
119210284Sjmallett
120210284Sjmallettstatic cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
121210284Sjmallett                              cl::desc("Do not verify input module"));
122210284Sjmallett
123210284Sjmallettstatic cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
124210284Sjmallett                                             cl::desc("Disable simplify-libcalls"));
125210284Sjmallett
126210284Sjmallettstatic cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
127210284Sjmallett                                    cl::desc("Show encoding in .s output"));
128210284Sjmallett
129210284Sjmallettstatic cl::opt<bool> EnableDwarfDirectory(
130210284Sjmallett    "enable-dwarf-directory", cl::Hidden,
131210284Sjmallett    cl::desc("Use .file directives with an explicit directory."));
132210284Sjmallett
133210284Sjmallettstatic cl::opt<bool> AsmVerbose("asm-verbose",
134210284Sjmallett                                cl::desc("Add comments to directives."),
135210284Sjmallett                                cl::init(true));
136210284Sjmallett
137210284Sjmallettstatic cl::opt<bool>
138210284Sjmallett    CompileTwice("compile-twice", cl::Hidden,
139210284Sjmallett                 cl::desc("Run everything twice, re-using the same pass "
140210284Sjmallett                          "manager and verify the result is the same."),
141210284Sjmallett                 cl::init(false));
142210284Sjmallett
143210284Sjmallettstatic cl::opt<bool> DiscardValueNames(
144210284Sjmallett    "discard-value-names",
145210284Sjmallett    cl::desc("Discard names from Value (other than GlobalValue)."),
146210284Sjmallett    cl::init(false), cl::Hidden);
147210284Sjmallett
148210284Sjmallettstatic cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
149210284Sjmallett
150210284Sjmallettstatic cl::opt<bool> RemarksWithHotness(
151210284Sjmallett    "pass-remarks-with-hotness",
152210284Sjmallett    cl::desc("With PGO, include profile count in optimization remarks"),
153210284Sjmallett    cl::Hidden);
154210284Sjmallett
155210284Sjmallettstatic cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
156210284Sjmallett    RemarksHotnessThreshold(
157210284Sjmallett        "pass-remarks-hotness-threshold",
158210284Sjmallett        cl::desc("Minimum profile count required for "
159210284Sjmallett                 "an optimization remark to be output. "
160210284Sjmallett                 "Use 'auto' to apply the threshold from profile summary."),
161210284Sjmallett        cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
162210284Sjmallett
163210284Sjmallettstatic cl::opt<std::string>
164210284Sjmallett    RemarksFilename("pass-remarks-output",
165210284Sjmallett                    cl::desc("Output filename for pass remarks"),
166210284Sjmallett                    cl::value_desc("filename"));
167210284Sjmallett
168210284Sjmallettstatic cl::opt<std::string>
169210284Sjmallett    RemarksPasses("pass-remarks-filter",
170210284Sjmallett                  cl::desc("Only record optimization remarks from passes whose "
171210284Sjmallett                           "names match the given regular expression"),
172210284Sjmallett                  cl::value_desc("regex"));
173210284Sjmallett
174210284Sjmallettstatic cl::opt<std::string> RemarksFormat(
175210284Sjmallett    "pass-remarks-format",
176210284Sjmallett    cl::desc("The format used for serializing remarks (default: YAML)"),
177210284Sjmallett    cl::value_desc("format"), cl::init("yaml"));
178210284Sjmallett
179210284Sjmallettnamespace {
180210284Sjmallettstatic ManagedStatic<std::vector<std::string>> RunPassNames;
181210284Sjmallett
182210284Sjmallettstruct RunPassOption {
183210284Sjmallett  void operator=(const std::string &Val) const {
184210284Sjmallett    if (Val.empty())
185210284Sjmallett      return;
186210284Sjmallett    SmallVector<StringRef, 8> PassNames;
187210284Sjmallett    StringRef(Val).split(PassNames, ',', -1, false);
188210284Sjmallett    for (auto PassName : PassNames)
189210284Sjmallett      RunPassNames->push_back(std::string(PassName));
190210284Sjmallett  }
191210284Sjmallett};
192210284Sjmallett}
193210284Sjmallett
194210284Sjmallettstatic RunPassOption RunPassOpt;
195210284Sjmallett
196210284Sjmallettstatic cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
197210284Sjmallett    "run-pass",
198210284Sjmallett    cl::desc("Run compiler only for specified passes (comma separated list)"),
199210284Sjmallett    cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
200210284Sjmallett
201210284Sjmallettstatic int compileModule(char **, LLVMContext &);
202210284Sjmallett
203210284SjmallettLLVM_ATTRIBUTE_NORETURN static void reportError(Twine Msg,
204210284Sjmallett                                                StringRef Filename = "") {
205210284Sjmallett  SmallString<256> Prefix;
206210284Sjmallett  if (!Filename.empty()) {
207210284Sjmallett    if (Filename == "-")
208210284Sjmallett      Filename = "<stdin>";
209210284Sjmallett    ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
210210284Sjmallett  }
211210284Sjmallett  WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
212210284Sjmallett  exit(1);
213210284Sjmallett}
214210284Sjmallett
215210284SjmallettLLVM_ATTRIBUTE_NORETURN static void reportError(Error Err, StringRef Filename) {
216210284Sjmallett  assert(Err);
217210284Sjmallett  handleAllErrors(createFileError(Filename, std::move(Err)),
218210284Sjmallett                  [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
219210284Sjmallett  llvm_unreachable("reportError() should not return");
220210284Sjmallett}
221210284Sjmallett
222210284Sjmallettstatic std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
223210284Sjmallett                                                       Triple::OSType OS,
224210284Sjmallett                                                       const char *ProgName) {
225210284Sjmallett  // If we don't yet have an output filename, make one.
226210284Sjmallett  if (OutputFilename.empty()) {
227210284Sjmallett    if (InputFilename == "-")
228215990Sjmallett      OutputFilename = "-";
229210284Sjmallett    else {
230210284Sjmallett      // If InputFilename ends in .bc or .ll, remove it.
231210284Sjmallett      StringRef IFN = InputFilename;
232210284Sjmallett      if (IFN.endswith(".bc") || IFN.endswith(".ll"))
233210284Sjmallett        OutputFilename = std::string(IFN.drop_back(3));
234210284Sjmallett      else if (IFN.endswith(".mir"))
235210284Sjmallett        OutputFilename = std::string(IFN.drop_back(4));
236210284Sjmallett      else
237210284Sjmallett        OutputFilename = std::string(IFN);
238210284Sjmallett
239210284Sjmallett      switch (codegen::getFileType()) {
240210284Sjmallett      case CGFT_AssemblyFile:
241210284Sjmallett        if (TargetName[0] == 'c') {
242210284Sjmallett          if (TargetName[1] == 0)
243210284Sjmallett            OutputFilename += ".cbe.c";
244210284Sjmallett          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
245210284Sjmallett            OutputFilename += ".cpp";
246210284Sjmallett          else
247210284Sjmallett            OutputFilename += ".s";
248210284Sjmallett        } else
249210284Sjmallett          OutputFilename += ".s";
250210284Sjmallett        break;
251210284Sjmallett      case CGFT_ObjectFile:
252210284Sjmallett        if (OS == Triple::Win32)
253210284Sjmallett          OutputFilename += ".obj";
254210284Sjmallett        else
255210284Sjmallett          OutputFilename += ".o";
256210284Sjmallett        break;
257210284Sjmallett      case CGFT_Null:
258215990Sjmallett        OutputFilename = "-";
259210284Sjmallett        break;
260215990Sjmallett      }
261215990Sjmallett    }
262210284Sjmallett  }
263210284Sjmallett
264210284Sjmallett  // Decide if we need "binary" output.
265215990Sjmallett  bool Binary = false;
266215990Sjmallett  switch (codegen::getFileType()) {
267210284Sjmallett  case CGFT_AssemblyFile:
268210284Sjmallett    break;
269210284Sjmallett  case CGFT_ObjectFile:
270210284Sjmallett  case CGFT_Null:
271210284Sjmallett    Binary = true;
272210284Sjmallett    break;
273210284Sjmallett  }
274210284Sjmallett
275210284Sjmallett  // Open the file.
276210284Sjmallett  std::error_code EC;
277210284Sjmallett  sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
278210284Sjmallett  if (!Binary)
279210284Sjmallett    OpenFlags |= sys::fs::OF_TextWithCRLF;
280210284Sjmallett  auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
281210284Sjmallett  if (EC) {
282210284Sjmallett    reportError(EC.message());
283210284Sjmallett    return nullptr;
284210284Sjmallett  }
285210284Sjmallett
286210284Sjmallett  return FDOut;
287210284Sjmallett}
288210284Sjmallett
289210284Sjmallettstruct LLCDiagnosticHandler : public DiagnosticHandler {
290210284Sjmallett  bool *HasError;
291210284Sjmallett  LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
292210284Sjmallett  bool handleDiagnostics(const DiagnosticInfo &DI) override {
293210284Sjmallett    if (DI.getKind() == llvm::DK_SrcMgr) {
294210284Sjmallett      const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
295210284Sjmallett      const SMDiagnostic &SMD = DISM.getSMDiag();
296210284Sjmallett
297210284Sjmallett      if (SMD.getKind() == SourceMgr::DK_Error)
298210284Sjmallett        *HasError = true;
299210284Sjmallett
300210284Sjmallett      SMD.print(nullptr, errs());
301210284Sjmallett
302210284Sjmallett      // For testing purposes, we print the LocCookie here.
303210284Sjmallett      if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
304210284Sjmallett        WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
305210284Sjmallett
306210284Sjmallett      return true;
307210284Sjmallett    }
308210284Sjmallett
309210284Sjmallett    if (DI.getSeverity() == DS_Error)
310210284Sjmallett      *HasError = true;
311210284Sjmallett
312210284Sjmallett    if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
313210284Sjmallett      if (!Remark->isEnabled())
314210284Sjmallett        return true;
315210284Sjmallett
316210284Sjmallett    DiagnosticPrinterRawOStream DP(errs());
317210284Sjmallett    errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
318210284Sjmallett    DI.print(DP);
319210284Sjmallett    errs() << "\n";
320210284Sjmallett    return true;
321210284Sjmallett  }
322210284Sjmallett};
323210284Sjmallett
324210284Sjmallett// main - Entry point for the llc compiler.
325210284Sjmallett//
326210284Sjmallettint main(int argc, char **argv) {
327210284Sjmallett  InitLLVM X(argc, argv);
328210284Sjmallett
329210284Sjmallett  // Enable debug stream buffering.
330210284Sjmallett  EnableDebugBuffering = true;
331210284Sjmallett
332210284Sjmallett  LLVMContext Context;
333210284Sjmallett
334210284Sjmallett  // Initialize targets first, so that --version shows registered targets.
335210284Sjmallett  InitializeAllTargets();
336210284Sjmallett  InitializeAllTargetMCs();
337210284Sjmallett  InitializeAllAsmPrinters();
338210284Sjmallett  InitializeAllAsmParsers();
339210284Sjmallett
340210284Sjmallett  // Initialize codegen and IR passes used by llc so that the -print-after,
341210284Sjmallett  // -print-before, and -stop-after options work.
342210284Sjmallett  PassRegistry *Registry = PassRegistry::getPassRegistry();
343210284Sjmallett  initializeCore(*Registry);
344210284Sjmallett  initializeCodeGen(*Registry);
345210284Sjmallett  initializeLoopStrengthReducePass(*Registry);
346210284Sjmallett  initializeLowerIntrinsicsPass(*Registry);
347210284Sjmallett  initializeEntryExitInstrumenterPass(*Registry);
348210284Sjmallett  initializePostInlineEntryExitInstrumenterPass(*Registry);
349210284Sjmallett  initializeUnreachableBlockElimLegacyPassPass(*Registry);
350210284Sjmallett  initializeConstantHoistingLegacyPassPass(*Registry);
351210284Sjmallett  initializeScalarOpts(*Registry);
352210284Sjmallett  initializeVectorization(*Registry);
353210284Sjmallett  initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
354210284Sjmallett  initializeExpandReductionsPass(*Registry);
355210284Sjmallett  initializeExpandVectorPredicationPass(*Registry);
356210284Sjmallett  initializeHardwareLoopsPass(*Registry);
357210284Sjmallett  initializeTransformUtils(*Registry);
358210284Sjmallett  initializeReplaceWithVeclibLegacyPass(*Registry);
359210284Sjmallett
360210284Sjmallett  // Initialize debugging passes.
361210284Sjmallett  initializeScavengerTestPass(*Registry);
362210284Sjmallett
363210284Sjmallett  // Register the target printer for --version.
364210284Sjmallett  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
365210284Sjmallett
366210284Sjmallett  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
367210284Sjmallett
368210284Sjmallett  Context.setDiscardValueNames(DiscardValueNames);
369210284Sjmallett
370210284Sjmallett  // Set a diagnostic handler that doesn't exit on the first error
371210284Sjmallett  bool HasError = false;
372210284Sjmallett  Context.setDiagnosticHandler(
373210284Sjmallett      std::make_unique<LLCDiagnosticHandler>(&HasError));
374210284Sjmallett
375210284Sjmallett  Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
376210284Sjmallett      setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
377210284Sjmallett                                   RemarksFormat, RemarksWithHotness,
378210284Sjmallett                                   RemarksHotnessThreshold);
379210284Sjmallett  if (Error E = RemarksFileOrErr.takeError())
380210284Sjmallett    reportError(std::move(E), RemarksFilename);
381210284Sjmallett  std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
382210284Sjmallett
383210284Sjmallett  if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
384210284Sjmallett    reportError("input language must be '', 'IR' or 'MIR'");
385210284Sjmallett
386210284Sjmallett  // Compile the module TimeCompilations times to give better compile time
387210284Sjmallett  // metrics.
388210284Sjmallett  for (unsigned I = TimeCompilations; I; --I)
389210284Sjmallett    if (int RetVal = compileModule(argv, Context))
390210284Sjmallett      return RetVal;
391210284Sjmallett
392  if (RemarksFile)
393    RemarksFile->keep();
394  return 0;
395}
396
397static bool addPass(PassManagerBase &PM, const char *argv0,
398                    StringRef PassName, TargetPassConfig &TPC) {
399  if (PassName == "none")
400    return false;
401
402  const PassRegistry *PR = PassRegistry::getPassRegistry();
403  const PassInfo *PI = PR->getPassInfo(PassName);
404  if (!PI) {
405    WithColor::error(errs(), argv0)
406        << "run-pass " << PassName << " is not registered.\n";
407    return true;
408  }
409
410  Pass *P;
411  if (PI->getNormalCtor())
412    P = PI->getNormalCtor()();
413  else {
414    WithColor::error(errs(), argv0)
415        << "cannot create pass: " << PI->getPassName() << "\n";
416    return true;
417  }
418  std::string Banner = std::string("After ") + std::string(P->getPassName());
419  TPC.addMachinePrePasses();
420  PM.add(P);
421  TPC.addMachinePostPasses(Banner);
422
423  return false;
424}
425
426static int compileModule(char **argv, LLVMContext &Context) {
427  // Load the module to be compiled...
428  SMDiagnostic Err;
429  std::unique_ptr<Module> M;
430  std::unique_ptr<MIRParser> MIR;
431  Triple TheTriple;
432  std::string CPUStr = codegen::getCPUStr(),
433              FeaturesStr = codegen::getFeaturesStr();
434
435  // Set attributes on functions as loaded from MIR from command line arguments.
436  auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
437    codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
438  };
439
440  auto MAttrs = codegen::getMAttrs();
441  bool SkipModule = codegen::getMCPU() == "help" ||
442                    (!MAttrs.empty() && MAttrs.front() == "help");
443
444  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
445  switch (OptLevel) {
446  default:
447    WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
448    return 1;
449  case ' ': break;
450  case '0': OLvl = CodeGenOpt::None; break;
451  case '1': OLvl = CodeGenOpt::Less; break;
452  case '2': OLvl = CodeGenOpt::Default; break;
453  case '3': OLvl = CodeGenOpt::Aggressive; break;
454  }
455
456  // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
457  // use that to indicate the MC default.
458  if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
459    StringRef V = BinutilsVersion.getValue();
460    unsigned Num;
461    if (V.consumeInteger(10, Num) || Num == 0 ||
462        !(V.empty() ||
463          (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
464      WithColor::error(errs(), argv[0])
465          << "invalid -binutils-version, accepting 'none' or major.minor\n";
466      return 1;
467    }
468  }
469  TargetOptions Options;
470  auto InitializeOptions = [&](const Triple &TheTriple) {
471    Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
472    Options.BinutilsVersion =
473        TargetMachine::parseBinutilsVersion(BinutilsVersion);
474    Options.DisableIntegratedAS = NoIntegratedAssembler;
475    Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
476    Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
477    Options.MCOptions.AsmVerbose = AsmVerbose;
478    Options.MCOptions.PreserveAsmComments = PreserveComments;
479    Options.MCOptions.IASSearchPaths = IncludeDirs;
480    Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
481  };
482
483  Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
484
485  const Target *TheTarget = nullptr;
486  std::unique_ptr<TargetMachine> Target;
487
488  // If user just wants to list available options, skip module loading
489  if (!SkipModule) {
490    auto SetDataLayout =
491        [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
492      // If we are supposed to override the target triple, do so now.
493      std::string IRTargetTriple = DataLayoutTargetTriple.str();
494      if (!TargetTriple.empty())
495        IRTargetTriple = Triple::normalize(TargetTriple);
496      TheTriple = Triple(IRTargetTriple);
497      if (TheTriple.getTriple().empty())
498        TheTriple.setTriple(sys::getDefaultTargetTriple());
499
500      std::string Error;
501      TheTarget =
502          TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
503      if (!TheTarget) {
504        WithColor::error(errs(), argv[0]) << Error;
505        exit(1);
506      }
507
508      // On AIX, setting the relocation model to anything other than PIC is
509      // considered a user error.
510      if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
511        reportError("invalid relocation model, AIX only supports PIC",
512                    InputFilename);
513
514      InitializeOptions(TheTriple);
515      Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
516          TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
517          codegen::getExplicitCodeModel(), OLvl));
518      assert(Target && "Could not allocate target machine!");
519
520      return Target->createDataLayout().getStringRepresentation();
521    };
522    if (InputLanguage == "mir" ||
523        (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
524      MIR = createMIRParserFromFile(InputFilename, Err, Context,
525                                    setMIRFunctionAttributes);
526      if (MIR)
527        M = MIR->parseIRModule(SetDataLayout);
528    } else {
529      M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
530    }
531    if (!M) {
532      Err.print(argv[0], WithColor::error(errs(), argv[0]));
533      return 1;
534    }
535    if (!TargetTriple.empty())
536      M->setTargetTriple(Triple::normalize(TargetTriple));
537  } else {
538    TheTriple = Triple(Triple::normalize(TargetTriple));
539    if (TheTriple.getTriple().empty())
540      TheTriple.setTriple(sys::getDefaultTargetTriple());
541
542    // Get the target specific parser.
543    std::string Error;
544    TheTarget =
545        TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
546    if (!TheTarget) {
547      WithColor::error(errs(), argv[0]) << Error;
548      return 1;
549    }
550
551    // On AIX, setting the relocation model to anything other than PIC is
552    // considered a user error.
553    if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
554      WithColor::error(errs(), argv[0])
555          << "invalid relocation model, AIX only supports PIC.\n";
556      return 1;
557    }
558
559    InitializeOptions(TheTriple);
560    Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
561        TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
562        codegen::getExplicitCodeModel(), OLvl));
563    assert(Target && "Could not allocate target machine!");
564
565    // If we don't have a module then just exit now. We do this down
566    // here since the CPU/Feature help is underneath the target machine
567    // creation.
568    return 0;
569  }
570
571  assert(M && "Should have exited if we didn't have a module!");
572  if (codegen::getFloatABIForCalls() != FloatABI::Default)
573    Options.FloatABIType = codegen::getFloatABIForCalls();
574
575  // Figure out where we are going to send the output.
576  std::unique_ptr<ToolOutputFile> Out =
577      GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
578  if (!Out) return 1;
579
580  std::unique_ptr<ToolOutputFile> DwoOut;
581  if (!SplitDwarfOutputFile.empty()) {
582    std::error_code EC;
583    DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
584                                               sys::fs::OF_None);
585    if (EC)
586      reportError(EC.message(), SplitDwarfOutputFile);
587  }
588
589  // Build up all of the passes that we want to do to the module.
590  legacy::PassManager PM;
591
592  // Add an appropriate TargetLibraryInfo pass for the module's triple.
593  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
594
595  // The -disable-simplify-libcalls flag actually disables all builtin optzns.
596  if (DisableSimplifyLibCalls)
597    TLII.disableAllFunctions();
598  PM.add(new TargetLibraryInfoWrapperPass(TLII));
599
600  // Verify module immediately to catch problems before doInitialization() is
601  // called on any passes.
602  if (!NoVerify && verifyModule(*M, &errs()))
603    reportError("input module cannot be verified", InputFilename);
604
605  // Override function attributes based on CPUStr, FeaturesStr, and command line
606  // flags.
607  codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
608
609  if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
610    WithColor::warning(errs(), argv[0])
611        << ": warning: ignoring -mc-relax-all because filetype != obj";
612
613  {
614    raw_pwrite_stream *OS = &Out->os();
615
616    // Manually do the buffering rather than using buffer_ostream,
617    // so we can memcmp the contents in CompileTwice mode
618    SmallVector<char, 0> Buffer;
619    std::unique_ptr<raw_svector_ostream> BOS;
620    if ((codegen::getFileType() != CGFT_AssemblyFile &&
621         !Out->os().supportsSeeking()) ||
622        CompileTwice) {
623      BOS = std::make_unique<raw_svector_ostream>(Buffer);
624      OS = BOS.get();
625    }
626
627    const char *argv0 = argv[0];
628    LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
629    MachineModuleInfoWrapperPass *MMIWP =
630        new MachineModuleInfoWrapperPass(&LLVMTM);
631
632    // Construct a custom pass pipeline that starts after instruction
633    // selection.
634    if (!RunPassNames->empty()) {
635      if (!MIR) {
636        WithColor::warning(errs(), argv[0])
637            << "run-pass is for .mir file only.\n";
638        return 1;
639      }
640      TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
641      if (TPC.hasLimitedCodeGenPipeline()) {
642        WithColor::warning(errs(), argv[0])
643            << "run-pass cannot be used with "
644            << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
645        return 1;
646      }
647
648      TPC.setDisableVerify(NoVerify);
649      PM.add(&TPC);
650      PM.add(MMIWP);
651      TPC.printAndVerify("");
652      for (const std::string &RunPassName : *RunPassNames) {
653        if (addPass(PM, argv0, RunPassName, TPC))
654          return 1;
655      }
656      TPC.setInitialized();
657      PM.add(createPrintMIRPass(*OS));
658      PM.add(createFreeMachineFunctionPass());
659    } else if (Target->addPassesToEmitFile(
660                   PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
661                   codegen::getFileType(), NoVerify, MMIWP)) {
662      reportError("target does not support generation of this file type");
663    }
664
665    const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
666        ->Initialize(MMIWP->getMMI().getContext(), *Target);
667    if (MIR) {
668      assert(MMIWP && "Forgot to create MMIWP?");
669      if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
670        return 1;
671    }
672
673    // Before executing passes, print the final values of the LLVM options.
674    cl::PrintOptionValues();
675
676    // If requested, run the pass manager over the same module again,
677    // to catch any bugs due to persistent state in the passes. Note that
678    // opt has the same functionality, so it may be worth abstracting this out
679    // in the future.
680    SmallVector<char, 0> CompileTwiceBuffer;
681    if (CompileTwice) {
682      std::unique_ptr<Module> M2(llvm::CloneModule(*M));
683      PM.run(*M2);
684      CompileTwiceBuffer = Buffer;
685      Buffer.clear();
686    }
687
688    PM.run(*M);
689
690    auto HasError =
691        ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
692    if (*HasError)
693      return 1;
694
695    // Compare the two outputs and make sure they're the same
696    if (CompileTwice) {
697      if (Buffer.size() != CompileTwiceBuffer.size() ||
698          (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
699           0)) {
700        errs()
701            << "Running the pass manager twice changed the output.\n"
702               "Writing the result of the second run to the specified output\n"
703               "To generate the one-run comparison binary, just run without\n"
704               "the compile-twice option\n";
705        Out->os() << Buffer;
706        Out->keep();
707        return 1;
708      }
709    }
710
711    if (BOS) {
712      Out->os() << Buffer;
713    }
714  }
715
716  // Declare success.
717  Out->keep();
718  if (DwoOut)
719    DwoOut->keep();
720
721  return 0;
722}
723