1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the llc code generator driver. It provides a convenient
10 // command-line interface for generating native assembly-language code
11 // or C code, given LLVM bitcode.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/CodeGen/MIRParser/MIRParser.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/AutoUpgrade.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LLVMRemarkStreamer.h"
34 #include "llvm/IR/LegacyPassManager.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Remarks/HotnessThresholdParser.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/InitLLVM.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/PluginLoader.h"
52 #include "llvm/Support/SourceMgr.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/TimeProfiler.h"
55 #include "llvm/Support/ToolOutputFile.h"
56 #include "llvm/Support/WithColor.h"
57 #include "llvm/Target/TargetLoweringObjectFile.h"
58 #include "llvm/Target/TargetMachine.h"
59 #include "llvm/Transforms/Utils/Cloning.h"
60 #include <memory>
61 using namespace llvm;
62 
63 static codegen::RegisterCodeGenFlags CGF;
64 
65 // General options for llc.  Other pass-specific options are specified
66 // within the corresponding llc passes, and target-specific options
67 // and back-end code generation options are specified with the target machine.
68 //
69 static cl::opt<std::string>
70 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
71 
72 static cl::opt<std::string>
73 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
74 
75 static cl::opt<std::string>
76 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
77 
78 static cl::opt<std::string>
79     SplitDwarfOutputFile("split-dwarf-output",
80                          cl::desc(".dwo output filename"),
81                          cl::value_desc("filename"));
82 
83 static cl::opt<unsigned>
84 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
85                  cl::value_desc("N"),
86                  cl::desc("Repeat compilation N times for timing"));
87 
88 static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
89 
90 static cl::opt<unsigned> TimeTraceGranularity(
91     "time-trace-granularity",
92     cl::desc(
93         "Minimum time granularity (in microseconds) traced by time profiler"),
94     cl::init(500), cl::Hidden);
95 
96 static cl::opt<std::string>
97     TimeTraceFile("time-trace-file",
98                   cl::desc("Specify time trace file destination"),
99                   cl::value_desc("filename"));
100 
101 static cl::opt<std::string>
102     BinutilsVersion("binutils-version", cl::Hidden,
103                     cl::desc("Produced object files can use all ELF features "
104                              "supported by this binutils version and newer."
105                              "If -no-integrated-as is specified, the generated "
106                              "assembly will consider GNU as support."
107                              "'none' means that all ELF features can be used, "
108                              "regardless of binutils support"));
109 
110 static cl::opt<bool>
111 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
112                       cl::desc("Disable integrated assembler"));
113 
114 static cl::opt<bool>
115     PreserveComments("preserve-as-comments", cl::Hidden,
116                      cl::desc("Preserve Comments in outputted assembly"),
117                      cl::init(true));
118 
119 // Determine optimization level.
120 static cl::opt<char>
121     OptLevel("O",
122              cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
123                       "(default = '-O2')"),
124              cl::Prefix, cl::init(' '));
125 
126 static cl::opt<std::string>
127 TargetTriple("mtriple", cl::desc("Override target triple for module"));
128 
129 static cl::opt<std::string> SplitDwarfFile(
130     "split-dwarf-file",
131     cl::desc(
132         "Specify the name of the .dwo file to encode in the DWARF output"));
133 
134 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
135                               cl::desc("Do not verify input module"));
136 
137 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
138                                              cl::desc("Disable simplify-libcalls"));
139 
140 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
141                                     cl::desc("Show encoding in .s output"));
142 
143 static cl::opt<bool>
144     DwarfDirectory("dwarf-directory", cl::Hidden,
145                    cl::desc("Use .file directives with an explicit directory"),
146                    cl::init(true));
147 
148 static cl::opt<bool> AsmVerbose("asm-verbose",
149                                 cl::desc("Add comments to directives."),
150                                 cl::init(true));
151 
152 static cl::opt<bool>
153     CompileTwice("compile-twice", cl::Hidden,
154                  cl::desc("Run everything twice, re-using the same pass "
155                           "manager and verify the result is the same."),
156                  cl::init(false));
157 
158 static cl::opt<bool> DiscardValueNames(
159     "discard-value-names",
160     cl::desc("Discard names from Value (other than GlobalValue)."),
161     cl::init(false), cl::Hidden);
162 
163 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
164 
165 static cl::opt<bool> RemarksWithHotness(
166     "pass-remarks-with-hotness",
167     cl::desc("With PGO, include profile count in optimization remarks"),
168     cl::Hidden);
169 
170 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
171     RemarksHotnessThreshold(
172         "pass-remarks-hotness-threshold",
173         cl::desc("Minimum profile count required for "
174                  "an optimization remark to be output. "
175                  "Use 'auto' to apply the threshold from profile summary."),
176         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
177 
178 static cl::opt<std::string>
179     RemarksFilename("pass-remarks-output",
180                     cl::desc("Output filename for pass remarks"),
181                     cl::value_desc("filename"));
182 
183 static cl::opt<std::string>
184     RemarksPasses("pass-remarks-filter",
185                   cl::desc("Only record optimization remarks from passes whose "
186                            "names match the given regular expression"),
187                   cl::value_desc("regex"));
188 
189 static cl::opt<std::string> RemarksFormat(
190     "pass-remarks-format",
191     cl::desc("The format used for serializing remarks (default: YAML)"),
192     cl::value_desc("format"), cl::init("yaml"));
193 
194 namespace {
195 static ManagedStatic<std::vector<std::string>> RunPassNames;
196 
197 struct RunPassOption {
198   void operator=(const std::string &Val) const {
199     if (Val.empty())
200       return;
201     SmallVector<StringRef, 8> PassNames;
202     StringRef(Val).split(PassNames, ',', -1, false);
203     for (auto PassName : PassNames)
204       RunPassNames->push_back(std::string(PassName));
205   }
206 };
207 }
208 
209 static RunPassOption RunPassOpt;
210 
211 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
212     "run-pass",
213     cl::desc("Run compiler only for specified passes (comma separated list)"),
214     cl::value_desc("pass-name"), cl::location(RunPassOpt));
215 
216 static int compileModule(char **, LLVMContext &);
217 
218 [[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
219   SmallString<256> Prefix;
220   if (!Filename.empty()) {
221     if (Filename == "-")
222       Filename = "<stdin>";
223     ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
224   }
225   WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
226   exit(1);
227 }
228 
229 [[noreturn]] static void reportError(Error Err, StringRef Filename) {
230   assert(Err);
231   handleAllErrors(createFileError(Filename, std::move(Err)),
232                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
233   llvm_unreachable("reportError() should not return");
234 }
235 
236 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
237                                                        Triple::OSType OS,
238                                                        const char *ProgName) {
239   // If we don't yet have an output filename, make one.
240   if (OutputFilename.empty()) {
241     if (InputFilename == "-")
242       OutputFilename = "-";
243     else {
244       // If InputFilename ends in .bc or .ll, remove it.
245       StringRef IFN = InputFilename;
246       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
247         OutputFilename = std::string(IFN.drop_back(3));
248       else if (IFN.endswith(".mir"))
249         OutputFilename = std::string(IFN.drop_back(4));
250       else
251         OutputFilename = std::string(IFN);
252 
253       switch (codegen::getFileType()) {
254       case CGFT_AssemblyFile:
255         if (TargetName[0] == 'c') {
256           if (TargetName[1] == 0)
257             OutputFilename += ".cbe.c";
258           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
259             OutputFilename += ".cpp";
260           else
261             OutputFilename += ".s";
262         } else
263           OutputFilename += ".s";
264         break;
265       case CGFT_ObjectFile:
266         if (OS == Triple::Win32)
267           OutputFilename += ".obj";
268         else
269           OutputFilename += ".o";
270         break;
271       case CGFT_Null:
272         OutputFilename = "-";
273         break;
274       }
275     }
276   }
277 
278   // Decide if we need "binary" output.
279   bool Binary = false;
280   switch (codegen::getFileType()) {
281   case CGFT_AssemblyFile:
282     break;
283   case CGFT_ObjectFile:
284   case CGFT_Null:
285     Binary = true;
286     break;
287   }
288 
289   // Open the file.
290   std::error_code EC;
291   sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
292   if (!Binary)
293     OpenFlags |= sys::fs::OF_TextWithCRLF;
294   auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
295   if (EC) {
296     reportError(EC.message());
297     return nullptr;
298   }
299 
300   return FDOut;
301 }
302 
303 struct LLCDiagnosticHandler : public DiagnosticHandler {
304   bool *HasError;
305   LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
306   bool handleDiagnostics(const DiagnosticInfo &DI) override {
307     if (DI.getKind() == llvm::DK_SrcMgr) {
308       const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
309       const SMDiagnostic &SMD = DISM.getSMDiag();
310 
311       if (SMD.getKind() == SourceMgr::DK_Error)
312         *HasError = true;
313 
314       SMD.print(nullptr, errs());
315 
316       // For testing purposes, we print the LocCookie here.
317       if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
318         WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
319 
320       return true;
321     }
322 
323     if (DI.getSeverity() == DS_Error)
324       *HasError = true;
325 
326     if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
327       if (!Remark->isEnabled())
328         return true;
329 
330     DiagnosticPrinterRawOStream DP(errs());
331     errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
332     DI.print(DP);
333     errs() << "\n";
334     return true;
335   }
336 };
337 
338 // main - Entry point for the llc compiler.
339 //
340 int main(int argc, char **argv) {
341   InitLLVM X(argc, argv);
342 
343   // Enable debug stream buffering.
344   EnableDebugBuffering = true;
345 
346   // Initialize targets first, so that --version shows registered targets.
347   InitializeAllTargets();
348   InitializeAllTargetMCs();
349   InitializeAllAsmPrinters();
350   InitializeAllAsmParsers();
351 
352   // Initialize codegen and IR passes used by llc so that the -print-after,
353   // -print-before, and -stop-after options work.
354   PassRegistry *Registry = PassRegistry::getPassRegistry();
355   initializeCore(*Registry);
356   initializeCodeGen(*Registry);
357   initializeLoopStrengthReducePass(*Registry);
358   initializeLowerIntrinsicsPass(*Registry);
359   initializeEntryExitInstrumenterPass(*Registry);
360   initializePostInlineEntryExitInstrumenterPass(*Registry);
361   initializeUnreachableBlockElimLegacyPassPass(*Registry);
362   initializeConstantHoistingLegacyPassPass(*Registry);
363   initializeScalarOpts(*Registry);
364   initializeVectorization(*Registry);
365   initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
366   initializeExpandReductionsPass(*Registry);
367   initializeExpandVectorPredicationPass(*Registry);
368   initializeHardwareLoopsPass(*Registry);
369   initializeTransformUtils(*Registry);
370   initializeReplaceWithVeclibLegacyPass(*Registry);
371   initializeTLSVariableHoistLegacyPassPass(*Registry);
372 
373   // Initialize debugging passes.
374   initializeScavengerTestPass(*Registry);
375 
376   // Register the target printer for --version.
377   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
378 
379   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
380 
381   if (TimeTrace)
382     timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
383   auto TimeTraceScopeExit = make_scope_exit([]() {
384     if (TimeTrace) {
385       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
386         handleAllErrors(std::move(E), [&](const StringError &SE) {
387           errs() << SE.getMessage() << "\n";
388         });
389         return;
390       }
391       timeTraceProfilerCleanup();
392     }
393   });
394 
395   LLVMContext Context;
396   Context.setDiscardValueNames(DiscardValueNames);
397 
398   // Set a diagnostic handler that doesn't exit on the first error
399   bool HasError = false;
400   Context.setDiagnosticHandler(
401       std::make_unique<LLCDiagnosticHandler>(&HasError));
402 
403   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
404       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
405                                    RemarksFormat, RemarksWithHotness,
406                                    RemarksHotnessThreshold);
407   if (Error E = RemarksFileOrErr.takeError())
408     reportError(std::move(E), RemarksFilename);
409   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
410 
411   if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
412     reportError("input language must be '', 'IR' or 'MIR'");
413 
414   // Compile the module TimeCompilations times to give better compile time
415   // metrics.
416   for (unsigned I = TimeCompilations; I; --I)
417     if (int RetVal = compileModule(argv, Context))
418       return RetVal;
419 
420   if (RemarksFile)
421     RemarksFile->keep();
422   return 0;
423 }
424 
425 static bool addPass(PassManagerBase &PM, const char *argv0,
426                     StringRef PassName, TargetPassConfig &TPC) {
427   if (PassName == "none")
428     return false;
429 
430   const PassRegistry *PR = PassRegistry::getPassRegistry();
431   const PassInfo *PI = PR->getPassInfo(PassName);
432   if (!PI) {
433     WithColor::error(errs(), argv0)
434         << "run-pass " << PassName << " is not registered.\n";
435     return true;
436   }
437 
438   Pass *P;
439   if (PI->getNormalCtor())
440     P = PI->getNormalCtor()();
441   else {
442     WithColor::error(errs(), argv0)
443         << "cannot create pass: " << PI->getPassName() << "\n";
444     return true;
445   }
446   std::string Banner = std::string("After ") + std::string(P->getPassName());
447   TPC.addMachinePrePasses();
448   PM.add(P);
449   TPC.addMachinePostPasses(Banner);
450 
451   return false;
452 }
453 
454 static int compileModule(char **argv, LLVMContext &Context) {
455   // Load the module to be compiled...
456   SMDiagnostic Err;
457   std::unique_ptr<Module> M;
458   std::unique_ptr<MIRParser> MIR;
459   Triple TheTriple;
460   std::string CPUStr = codegen::getCPUStr(),
461               FeaturesStr = codegen::getFeaturesStr();
462 
463   // Set attributes on functions as loaded from MIR from command line arguments.
464   auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
465     codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
466   };
467 
468   auto MAttrs = codegen::getMAttrs();
469   bool SkipModule = codegen::getMCPU() == "help" ||
470                     (!MAttrs.empty() && MAttrs.front() == "help");
471 
472   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
473   switch (OptLevel) {
474   default:
475     WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
476     return 1;
477   case ' ': break;
478   case '0': OLvl = CodeGenOpt::None; break;
479   case '1': OLvl = CodeGenOpt::Less; break;
480   case '2': OLvl = CodeGenOpt::Default; break;
481   case '3': OLvl = CodeGenOpt::Aggressive; break;
482   }
483 
484   // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
485   // use that to indicate the MC default.
486   if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
487     StringRef V = BinutilsVersion.getValue();
488     unsigned Num;
489     if (V.consumeInteger(10, Num) || Num == 0 ||
490         !(V.empty() ||
491           (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
492       WithColor::error(errs(), argv[0])
493           << "invalid -binutils-version, accepting 'none' or major.minor\n";
494       return 1;
495     }
496   }
497   TargetOptions Options;
498   auto InitializeOptions = [&](const Triple &TheTriple) {
499     Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
500     Options.BinutilsVersion =
501         TargetMachine::parseBinutilsVersion(BinutilsVersion);
502     Options.DisableIntegratedAS = NoIntegratedAssembler;
503     Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
504     Options.MCOptions.AsmVerbose = AsmVerbose;
505     Options.MCOptions.PreserveAsmComments = PreserveComments;
506     Options.MCOptions.IASSearchPaths = IncludeDirs;
507     Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
508     if (DwarfDirectory.getPosition()) {
509       Options.MCOptions.MCUseDwarfDirectory =
510           DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
511                          : MCTargetOptions::DisableDwarfDirectory;
512     } else {
513       // -dwarf-directory is not set explicitly. Some assemblers
514       // (e.g. GNU as or ptxas) do not support `.file directory'
515       // syntax prior to DWARFv5. Let the target decide the default
516       // value.
517       Options.MCOptions.MCUseDwarfDirectory =
518           MCTargetOptions::DefaultDwarfDirectory;
519     }
520   };
521 
522   Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
523   Optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
524 
525   const Target *TheTarget = nullptr;
526   std::unique_ptr<TargetMachine> Target;
527 
528   // If user just wants to list available options, skip module loading
529   if (!SkipModule) {
530     auto SetDataLayout =
531         [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
532       // If we are supposed to override the target triple, do so now.
533       std::string IRTargetTriple = DataLayoutTargetTriple.str();
534       if (!TargetTriple.empty())
535         IRTargetTriple = Triple::normalize(TargetTriple);
536       TheTriple = Triple(IRTargetTriple);
537       if (TheTriple.getTriple().empty())
538         TheTriple.setTriple(sys::getDefaultTargetTriple());
539 
540       std::string Error;
541       TheTarget =
542           TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
543       if (!TheTarget) {
544         WithColor::error(errs(), argv[0]) << Error;
545         exit(1);
546       }
547 
548       // On AIX, setting the relocation model to anything other than PIC is
549       // considered a user error.
550       if (TheTriple.isOSAIX() && RM && *RM != Reloc::PIC_)
551         reportError("invalid relocation model, AIX only supports PIC",
552                     InputFilename);
553 
554       InitializeOptions(TheTriple);
555       Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
556           TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
557       assert(Target && "Could not allocate target machine!");
558 
559       return Target->createDataLayout().getStringRepresentation();
560     };
561     if (InputLanguage == "mir" ||
562         (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
563       MIR = createMIRParserFromFile(InputFilename, Err, Context,
564                                     setMIRFunctionAttributes);
565       if (MIR)
566         M = MIR->parseIRModule(SetDataLayout);
567     } else {
568       M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
569     }
570     if (!M) {
571       Err.print(argv[0], WithColor::error(errs(), argv[0]));
572       return 1;
573     }
574     if (!TargetTriple.empty())
575       M->setTargetTriple(Triple::normalize(TargetTriple));
576 
577     Optional<CodeModel::Model> CM_IR = M->getCodeModel();
578     if (!CM && CM_IR)
579       Target->setCodeModel(CM_IR.getValue());
580   } else {
581     TheTriple = Triple(Triple::normalize(TargetTriple));
582     if (TheTriple.getTriple().empty())
583       TheTriple.setTriple(sys::getDefaultTargetTriple());
584 
585     // Get the target specific parser.
586     std::string Error;
587     TheTarget =
588         TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
589     if (!TheTarget) {
590       WithColor::error(errs(), argv[0]) << Error;
591       return 1;
592     }
593 
594     // On AIX, setting the relocation model to anything other than PIC is
595     // considered a user error.
596     if (TheTriple.isOSAIX() && RM && *RM != Reloc::PIC_) {
597       WithColor::error(errs(), argv[0])
598           << "invalid relocation model, AIX only supports PIC.\n";
599       return 1;
600     }
601 
602     InitializeOptions(TheTriple);
603     Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
604         TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
605     assert(Target && "Could not allocate target machine!");
606 
607     // If we don't have a module then just exit now. We do this down
608     // here since the CPU/Feature help is underneath the target machine
609     // creation.
610     return 0;
611   }
612 
613   assert(M && "Should have exited if we didn't have a module!");
614   if (codegen::getFloatABIForCalls() != FloatABI::Default)
615     Options.FloatABIType = codegen::getFloatABIForCalls();
616 
617   // Figure out where we are going to send the output.
618   std::unique_ptr<ToolOutputFile> Out =
619       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
620   if (!Out) return 1;
621 
622   // Ensure the filename is passed down to CodeViewDebug.
623   Target->Options.ObjectFilenameForDebug = Out->outputFilename();
624 
625   std::unique_ptr<ToolOutputFile> DwoOut;
626   if (!SplitDwarfOutputFile.empty()) {
627     std::error_code EC;
628     DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
629                                                sys::fs::OF_None);
630     if (EC)
631       reportError(EC.message(), SplitDwarfOutputFile);
632   }
633 
634   // Build up all of the passes that we want to do to the module.
635   legacy::PassManager PM;
636 
637   // Add an appropriate TargetLibraryInfo pass for the module's triple.
638   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
639 
640   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
641   if (DisableSimplifyLibCalls)
642     TLII.disableAllFunctions();
643   PM.add(new TargetLibraryInfoWrapperPass(TLII));
644 
645   // Verify module immediately to catch problems before doInitialization() is
646   // called on any passes.
647   if (!NoVerify && verifyModule(*M, &errs()))
648     reportError("input module cannot be verified", InputFilename);
649 
650   // Override function attributes based on CPUStr, FeaturesStr, and command line
651   // flags.
652   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
653 
654   if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
655     WithColor::warning(errs(), argv[0])
656         << ": warning: ignoring -mc-relax-all because filetype != obj";
657 
658   {
659     raw_pwrite_stream *OS = &Out->os();
660 
661     // Manually do the buffering rather than using buffer_ostream,
662     // so we can memcmp the contents in CompileTwice mode
663     SmallVector<char, 0> Buffer;
664     std::unique_ptr<raw_svector_ostream> BOS;
665     if ((codegen::getFileType() != CGFT_AssemblyFile &&
666          !Out->os().supportsSeeking()) ||
667         CompileTwice) {
668       BOS = std::make_unique<raw_svector_ostream>(Buffer);
669       OS = BOS.get();
670     }
671 
672     const char *argv0 = argv[0];
673     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
674     MachineModuleInfoWrapperPass *MMIWP =
675         new MachineModuleInfoWrapperPass(&LLVMTM);
676 
677     // Construct a custom pass pipeline that starts after instruction
678     // selection.
679     if (!RunPassNames->empty()) {
680       if (!MIR) {
681         WithColor::warning(errs(), argv[0])
682             << "run-pass is for .mir file only.\n";
683         return 1;
684       }
685       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
686       if (TPC.hasLimitedCodeGenPipeline()) {
687         WithColor::warning(errs(), argv[0])
688             << "run-pass cannot be used with "
689             << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
690         return 1;
691       }
692 
693       TPC.setDisableVerify(NoVerify);
694       PM.add(&TPC);
695       PM.add(MMIWP);
696       TPC.printAndVerify("");
697       for (const std::string &RunPassName : *RunPassNames) {
698         if (addPass(PM, argv0, RunPassName, TPC))
699           return 1;
700       }
701       TPC.setInitialized();
702       PM.add(createPrintMIRPass(*OS));
703       PM.add(createFreeMachineFunctionPass());
704     } else if (Target->addPassesToEmitFile(
705                    PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
706                    codegen::getFileType(), NoVerify, MMIWP)) {
707       reportError("target does not support generation of this file type");
708     }
709 
710     const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
711         ->Initialize(MMIWP->getMMI().getContext(), *Target);
712     if (MIR) {
713       assert(MMIWP && "Forgot to create MMIWP?");
714       if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
715         return 1;
716     }
717 
718     // Before executing passes, print the final values of the LLVM options.
719     cl::PrintOptionValues();
720 
721     // If requested, run the pass manager over the same module again,
722     // to catch any bugs due to persistent state in the passes. Note that
723     // opt has the same functionality, so it may be worth abstracting this out
724     // in the future.
725     SmallVector<char, 0> CompileTwiceBuffer;
726     if (CompileTwice) {
727       std::unique_ptr<Module> M2(llvm::CloneModule(*M));
728       PM.run(*M2);
729       CompileTwiceBuffer = Buffer;
730       Buffer.clear();
731     }
732 
733     PM.run(*M);
734 
735     auto HasError =
736         ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
737     if (*HasError)
738       return 1;
739 
740     // Compare the two outputs and make sure they're the same
741     if (CompileTwice) {
742       if (Buffer.size() != CompileTwiceBuffer.size() ||
743           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
744            0)) {
745         errs()
746             << "Running the pass manager twice changed the output.\n"
747                "Writing the result of the second run to the specified output\n"
748                "To generate the one-run comparison binary, just run without\n"
749                "the compile-twice option\n";
750         Out->os() << Buffer;
751         Out->keep();
752         return 1;
753       }
754     }
755 
756     if (BOS) {
757       Out->os() << Buffer;
758     }
759   }
760 
761   // Declare success.
762   Out->keep();
763   if (DwoOut)
764     DwoOut->keep();
765 
766   return 0;
767 }
768