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