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