1//===-- llcdriver.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/ADT/SmallVectorExtras.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/RuntimeLibcallInfo.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/CodeGen/CommandFlags.h"
23#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
24#include "llvm/CodeGen/LinkAllCodegenComponents.h"
25#include "llvm/CodeGen/MIRParser/MIRParser.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/CodeGen/TargetPassConfig.h"
29#include "llvm/CodeGen/TargetSubtargetInfo.h"
30#include "llvm/IR/AutoUpgrade.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DiagnosticInfo.h"
33#include "llvm/IR/DiagnosticPrinter.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/LLVMRemarkStreamer.h"
36#include "llvm/IR/LegacyPassManager.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/IRReader/IRReader.h"
40#include "llvm/InitializePasses.h"
41#include "llvm/MC/MCTargetOptionsCommandFlags.h"
42#include "llvm/MC/TargetRegistry.h"
43#include "llvm/Pass.h"
44#include "llvm/Plugins/PassPlugin.h"
45#include "llvm/Remarks/HotnessThresholdParser.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/FormattedStream.h"
50#include "llvm/Support/PGOOptions.h"
51#include "llvm/Support/Path.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/TargetParser/Host.h"
60#include "llvm/TargetParser/SubtargetFeature.h"
61#include "llvm/TargetParser/Triple.h"
62#include "llvm/Transforms/Utils/Cloning.h"
63#include <cassert>
64#include <memory>
65#include <optional>
66using namespace llvm;
67
68static codegen::RegisterCodeGenFlags CGF;
69static codegen::RegisterMTuneFlag MTF;
70static codegen::RegisterSaveStatsFlag SSF;
71
72// General options for llc. Other pass-specific options are specified
73// within the corresponding llc passes, and target-specific options
74// and back-end code generation options are specified with the target machine.
75//
76static cl::opt<std::string>
77 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init(Val: "-"));
78
79static cl::list<std::string>
80 InstPrinterOptions("M", cl::desc("InstPrinter options"));
81
82static cl::opt<std::string>
83 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
84
85static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
86 cl::value_desc("filename"));
87
88static cl::opt<std::string>
89 SplitDwarfOutputFile("split-dwarf-output", cl::desc(".dwo output filename"),
90 cl::value_desc("filename"));
91
92static cl::opt<unsigned>
93 TimeCompilations("time-compilations", cl::Hidden, cl::init(Val: 1u),
94 cl::value_desc("N"),
95 cl::desc("Repeat compilation N times for timing"));
96
97static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
98
99static cl::opt<unsigned> TimeTraceGranularity(
100 "time-trace-granularity",
101 cl::desc(
102 "Minimum time granularity (in microseconds) traced by time profiler"),
103 cl::init(Val: 500), cl::Hidden);
104
105static cl::opt<std::string>
106 TimeTraceFile("time-trace-file",
107 cl::desc("Specify time trace file destination"),
108 cl::value_desc("filename"));
109
110static cl::opt<std::string>
111 BinutilsVersion("binutils-version", cl::Hidden,
112 cl::desc("Produced object files can use all ELF features "
113 "supported by this binutils version and newer."
114 "If -no-integrated-as is specified, the generated "
115 "assembly will consider GNU as support."
116 "'none' means that all ELF features can be used, "
117 "regardless of binutils support"));
118
119static cl::opt<bool>
120 PreserveComments("preserve-as-comments", cl::Hidden,
121 cl::desc("Preserve Comments in outputted assembly"),
122 cl::init(Val: true));
123
124// Determine optimization level.
125static cl::opt<char>
126 OptLevel("O",
127 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
128 "(default = '-O2')"),
129 cl::Prefix, cl::init(Val: '2'));
130
131static cl::opt<std::string>
132 TargetTriple("mtriple", cl::desc("Override target triple for module"));
133
134static cl::opt<std::string> SplitDwarfFile(
135 "split-dwarf-file",
136 cl::desc(
137 "Specify the name of the .dwo file to encode in the DWARF output"));
138
139static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
140 cl::desc("Do not verify input module"));
141
142static cl::opt<bool> VerifyEach("verify-each",
143 cl::desc("Verify after each transform"));
144
145static cl::opt<bool>
146 DisableSimplifyLibCalls("disable-simplify-libcalls",
147 cl::desc("Disable simplify-libcalls"));
148
149static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
150 cl::desc("Show encoding in .s output"));
151
152static cl::opt<unsigned>
153 OutputAsmVariant("output-asm-variant",
154 cl::desc("Syntax variant to use for output printing"));
155
156static cl::opt<bool>
157 DwarfDirectory("dwarf-directory", cl::Hidden,
158 cl::desc("Use .file directives with an explicit directory"),
159 cl::init(Val: true));
160
161static cl::opt<bool> AsmVerbose("asm-verbose",
162 cl::desc("Add comments to directives."),
163 cl::init(Val: true));
164
165static cl::opt<bool>
166 CompileTwice("compile-twice", cl::Hidden,
167 cl::desc("Run everything twice, re-using the same pass "
168 "manager and verify the result is the same."),
169 cl::init(Val: false));
170
171static cl::opt<bool> DiscardValueNames(
172 "discard-value-names",
173 cl::desc("Discard names from Value (other than GlobalValue)."),
174 cl::init(Val: false), cl::Hidden);
175
176static cl::opt<bool>
177 PrintMIR2VecVocab("print-mir2vec-vocab", cl::Hidden,
178 cl::desc("Print MIR2Vec vocabulary contents"),
179 cl::init(Val: false));
180
181static cl::opt<bool>
182 PrintMIR2Vec("print-mir2vec", cl::Hidden,
183 cl::desc("Print MIR2Vec embeddings for functions"),
184 cl::init(Val: false));
185
186static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
187
188static cl::opt<bool> RemarksWithHotness(
189 "pass-remarks-with-hotness",
190 cl::desc("With PGO, include profile count in optimization remarks"),
191 cl::Hidden);
192
193static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
194 RemarksHotnessThreshold(
195 "pass-remarks-hotness-threshold",
196 cl::desc("Minimum profile count required for "
197 "an optimization remark to be output. "
198 "Use 'auto' to apply the threshold from profile summary."),
199 cl::value_desc("N or 'auto'"), cl::init(Val: 0), cl::Hidden);
200
201static cl::opt<std::string>
202 RemarksFilename("pass-remarks-output",
203 cl::desc("Output filename for pass remarks"),
204 cl::value_desc("filename"));
205
206static cl::opt<std::string>
207 RemarksPasses("pass-remarks-filter",
208 cl::desc("Only record optimization remarks from passes whose "
209 "names match the given regular expression"),
210 cl::value_desc("regex"));
211
212static cl::opt<std::string> RemarksFormat(
213 "pass-remarks-format",
214 cl::desc("The format used for serializing remarks (default: YAML)"),
215 cl::value_desc("format"), cl::init(Val: "yaml"));
216
217static cl::list<std::string> PassPlugins("load-pass-plugin",
218 cl::desc("Load plugin library"));
219
220static cl::list<std::string>
221 PluginArgs("plugin-arg",
222 cl::desc("Pass <arg> to the pass plugin named <plugin>"),
223 cl::value_desc("plugin>,<arg"));
224
225static cl::opt<bool> EnableNewPassManager(
226 "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(Val: false));
227
228// This flag specifies a textual description of the optimization pass pipeline
229// to run over the module. This flag switches opt to use the new pass manager
230// infrastructure, completely disabling all of the flags specific to the old
231// pass management.
232static cl::opt<std::string> PassPipeline(
233 "passes",
234 cl::desc(
235 "A textual description of the pass pipeline. To have analysis passes "
236 "available before a certain pass, add 'require<foo-analysis>'."));
237static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),
238 cl::desc("Alias for -passes"));
239
240static std::vector<std::string> &getRunPassNames() {
241 static std::vector<std::string> RunPassNames;
242 return RunPassNames;
243}
244
245namespace {
246struct RunPassOption {
247 void operator=(const std::string &Val) const {
248 if (Val.empty())
249 return;
250 SmallVector<StringRef, 8> PassNames;
251 StringRef(Val).split(A&: PassNames, Separator: ',', MaxSplit: -1, KeepEmpty: false);
252 for (auto PassName : PassNames)
253 getRunPassNames().push_back(x: std::string(PassName));
254 }
255};
256} // namespace
257
258static RunPassOption RunPassOpt;
259
260static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
261 "run-pass",
262 cl::desc("Run compiler only for specified passes (comma separated list)"),
263 cl::value_desc("pass-name"), cl::location(L&: RunPassOpt));
264
265// PGO command line options
266enum PGOKind {
267 NoPGO,
268 SampleUse,
269};
270
271static cl::opt<PGOKind>
272 PGOKindFlag("pgo-kind", cl::init(Val: NoPGO), cl::Hidden,
273 cl::desc("The kind of profile guided optimization"),
274 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
275 clEnumValN(SampleUse, "pgo-sample-use-pipeline",
276 "Use sampled profile to guide PGO.")));
277
278// Function to set PGO options on TargetMachine based on command line flags.
279static void setPGOOptions(TargetMachine &TM) {
280 std::optional<PGOOptions> PGOOpt;
281
282 switch (PGOKindFlag) {
283 case SampleUse:
284 // Use default values for other PGOOptions parameters. This parameter
285 // is used to test that PGO data is preserved at -O0.
286 PGOOpt = PGOOptions("", "", "", "", PGOOptions::SampleUse,
287 PGOOptions::NoCSAction);
288 break;
289 case NoPGO:
290 PGOOpt = std::nullopt;
291 break;
292 }
293
294 if (PGOOpt)
295 TM.setPGOOption(PGOOpt);
296}
297
298static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &,
299 LLVMContext &Context, std::string &OutputFilename);
300
301[[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
302 SmallString<256> Prefix;
303 if (!Filename.empty()) {
304 if (Filename == "-")
305 Filename = "<stdin>";
306 ("'" + Twine(Filename) + "': ").toStringRef(Out&: Prefix);
307 }
308 WithColor::error(OS&: errs(), Prefix: "llc") << Prefix << Msg << "\n";
309 exit(status: 1);
310}
311
312[[noreturn]] static void reportError(Error Err, StringRef Filename) {
313 assert(Err);
314 handleAllErrors(E: createFileError(F: Filename, E: std::move(Err)),
315 Handlers: [&](const ErrorInfoBase &EI) { reportError(Msg: EI.message()); });
316 llvm_unreachable("reportError() should not return");
317}
318
319static std::unique_ptr<ToolOutputFile> GetOutputStream(Triple::OSType OS) {
320 // If we don't yet have an output filename, make one.
321 if (OutputFilename.empty()) {
322 if (InputFilename == "-")
323 OutputFilename = "-";
324 else {
325 // If InputFilename ends in .bc or .ll, remove it.
326 StringRef IFN = InputFilename;
327 if (IFN.ends_with(Suffix: ".bc") || IFN.ends_with(Suffix: ".ll"))
328 OutputFilename = std::string(IFN.drop_back(N: 3));
329 else if (IFN.ends_with(Suffix: ".mir"))
330 OutputFilename = std::string(IFN.drop_back(N: 4));
331 else
332 OutputFilename = std::string(IFN);
333
334 switch (codegen::getFileType()) {
335 case CodeGenFileType::AssemblyFile:
336 OutputFilename += ".s";
337 break;
338 case CodeGenFileType::ObjectFile:
339 if (OS == Triple::Win32)
340 OutputFilename += ".obj";
341 else
342 OutputFilename += ".o";
343 break;
344 case CodeGenFileType::Null:
345 OutputFilename = "-";
346 break;
347 }
348 }
349 }
350
351 // Decide if we need "binary" output.
352 bool Binary = false;
353 switch (codegen::getFileType()) {
354 case CodeGenFileType::AssemblyFile:
355 break;
356 case CodeGenFileType::ObjectFile:
357 case CodeGenFileType::Null:
358 Binary = true;
359 break;
360 }
361
362 // Open the file.
363 std::error_code EC;
364 sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
365 if (!Binary)
366 OpenFlags |= sys::fs::OF_TextWithCRLF;
367 auto FDOut = std::make_unique<ToolOutputFile>(args&: OutputFilename, args&: EC, args&: OpenFlags);
368 if (EC)
369 reportError(Msg: EC.message());
370 return FDOut;
371}
372
373// Entry point for the llc compiler.
374//
375extern "C" int llcMain(int argc, char **argv) {
376 // Enable debug stream buffering.
377 EnableDebugBuffering = true;
378
379 // Initialize targets first, so that --version shows registered targets.
380 InitializeAllTargets();
381 InitializeAllTargetMCs();
382 InitializeAllAsmPrinters();
383 InitializeAllAsmParsers();
384
385 // Initialize codegen and IR passes used by llc so that the -print-after,
386 // -print-before, and -stop-after options work.
387 PassRegistry *Registry = PassRegistry::getPassRegistry();
388 initializeCore(*Registry);
389 initializeCodeGen(*Registry);
390 initializeLoopStrengthReducePass(*Registry);
391 initializePostInlineEntryExitInstrumenterPass(*Registry);
392 initializeUnreachableBlockElimLegacyPassPass(*Registry);
393 initializeConstantHoistingLegacyPassPass(*Registry);
394 initializeScalarOpts(*Registry);
395 initializeIPO(*Registry);
396 initializeVectorization(*Registry);
397 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
398 initializeTransformUtils(*Registry);
399
400 // Initialize debugging passes.
401 initializeScavengerTestPass(*Registry);
402
403 // Register the Target and CPU printer for --version.
404 cl::AddExtraVersionPrinter(func: sys::printDefaultTargetAndDetectedCPU);
405 // Register the target printer for --version.
406 cl::AddExtraVersionPrinter(func: TargetRegistry::printRegisteredTargetsForVersion);
407
408 cl::ParseCommandLineOptions(argc, argv, Overview: "llvm system compiler\n");
409
410 SmallVector<PassPlugin, 1> PluginList;
411 for (const std::string &Path : PassPlugins) {
412 auto Plugin = PassPlugin::load(Filename: Path);
413 if (!Plugin)
414 reportFatalUsageError(Err: Plugin.takeError());
415 PluginList.emplace_back(Args&: Plugin.get());
416 }
417 if (Error E = passPluginArguments(
418 Infos: map_to_vector(C&: PluginList,
419 F: [](const PassPlugin &P) { return P.getInfo(); }),
420 Args: PluginArgs))
421 reportFatalUsageError(Err: std::move(E));
422
423 if (!PassPipeline.empty() && !getRunPassNames().empty()) {
424 errs() << "The `llc -run-pass=...` syntax for the new pass manager is "
425 "not supported, please use `llc -passes=<pipeline>` (or the `-p` "
426 "alias for a more concise version).\n";
427 return 1;
428 }
429
430 if (TimeTrace)
431 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
432 llvm::scope_exit TimeTraceScopeExit([]() {
433 if (TimeTrace) {
434 if (auto E = timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename)) {
435 handleAllErrors(E: std::move(E), Handlers: [&](const StringError &SE) {
436 errs() << SE.getMessage() << "\n";
437 });
438 return;
439 }
440 timeTraceProfilerCleanup();
441 }
442 });
443
444 LLVMContext Context;
445 Context.setDiscardValueNames(DiscardValueNames);
446
447 // Set a diagnostic handler that doesn't exit on the first error
448 Context.setDiagnosticHandler(DH: std::make_unique<LLCDiagnosticHandler>());
449
450 Expected<LLVMRemarkFileHandle> RemarksFileOrErr =
451 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
452 RemarksFormat, RemarksWithHotness,
453 RemarksHotnessThreshold);
454 if (Error E = RemarksFileOrErr.takeError())
455 reportError(Err: std::move(E), Filename: RemarksFilename);
456 LLVMRemarkFileHandle RemarksFile = std::move(*RemarksFileOrErr);
457
458 codegen::MaybeEnableStatistics();
459 std::string OutputFilename;
460
461 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
462 reportError(Msg: "input language must be '', 'IR' or 'MIR'");
463
464 // Compile the module TimeCompilations times to give better compile time
465 // metrics.
466 for (unsigned I = TimeCompilations; I; --I)
467 if (int RetVal = compileModule(argv, PluginList, Context, OutputFilename))
468 return RetVal;
469
470 if (RemarksFile)
471 RemarksFile->keep();
472
473 return codegen::MaybeSaveStatistics(OutputFilename, ToolName: "llc");
474}
475
476static bool addPass(PassManagerBase &PM, const char *argv0, StringRef PassName,
477 TargetPassConfig &TPC) {
478 if (PassName == "none")
479 return false;
480
481 const PassRegistry *PR = PassRegistry::getPassRegistry();
482 const PassInfo *PI = PR->getPassInfo(Arg: PassName);
483 if (!PI) {
484 WithColor::error(OS&: errs(), Prefix: argv0)
485 << "run-pass " << PassName << " is not registered.\n";
486 return true;
487 }
488
489 Pass *P;
490 if (PI->getNormalCtor())
491 P = PI->getNormalCtor()();
492 else {
493 WithColor::error(OS&: errs(), Prefix: argv0)
494 << "cannot create pass: " << PI->getPassName() << "\n";
495 return true;
496 }
497 std::string Banner = std::string("After ") + std::string(P->getPassName());
498 TPC.addMachinePrePasses();
499 PM.add(P);
500 TPC.addMachinePostPasses(Banner);
501
502 return false;
503}
504
505static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
506 LLVMContext &Context, std::string &OutputFilename) {
507 // Load the module to be compiled...
508 SMDiagnostic Err;
509 std::unique_ptr<Module> M;
510 std::unique_ptr<MIRParser> MIR;
511 Triple TheTriple;
512 std::string CPUStr = codegen::getCPUStr();
513 std::string TuneCPUStr = codegen::getTuneCPUStr();
514 std::string FeaturesStr = codegen::getFeaturesStr();
515
516 // Set attributes on functions as loaded from MIR from command line arguments.
517 auto setMIRFunctionAttributes = [&CPUStr, &TuneCPUStr,
518 &FeaturesStr](Function &F) {
519 codegen::setFunctionAttributes(F, CPU: CPUStr, Features: FeaturesStr, TuneCPU: TuneCPUStr);
520 };
521
522 CodeGenOptLevel OLvl;
523 if (auto Level = CodeGenOpt::parseLevel(C: OptLevel)) {
524 OLvl = *Level;
525 } else {
526 WithColor::error(OS&: errs(), Prefix: argv[0]) << "invalid optimization level.\n";
527 return 1;
528 }
529
530 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
531 // use that to indicate the MC default.
532 if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
533 StringRef V = BinutilsVersion.getValue();
534 unsigned Num;
535 if (V.consumeInteger(Radix: 10, Result&: Num) || Num == 0 ||
536 !(V.empty() ||
537 (V.consume_front(Prefix: ".") && !V.consumeInteger(Radix: 10, Result&: Num) && V.empty()))) {
538 WithColor::error(OS&: errs(), Prefix: argv[0])
539 << "invalid -binutils-version, accepting 'none' or major.minor\n";
540 return 1;
541 }
542 }
543 TargetOptions Options;
544 auto InitializeOptions = [&](const Triple &TheTriple) {
545 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
546
547 if (Options.XCOFFReadOnlyPointers) {
548 if (!TheTriple.isOSAIX())
549 reportError(Msg: "-mxcoff-roptr option is only supported on AIX",
550 Filename: InputFilename);
551
552 // Since the storage mapping class is specified per csect,
553 // without using data sections, it is less effective to use read-only
554 // pointers. Using read-only pointers may cause other RO variables in the
555 // same csect to become RW when the linker acts upon `-bforceimprw`;
556 // therefore, we require that separate data sections are used in the
557 // presence of ReadOnlyPointers. We respect the setting of data-sections
558 // since we have not found reasons to do otherwise that overcome the user
559 // surprise of not respecting the setting.
560 if (!Options.DataSections)
561 reportError(Msg: "-mxcoff-roptr option must be used with -data-sections",
562 Filename: InputFilename);
563 }
564
565 Options.MCOptions.BinutilsVersion =
566 MCTargetOptions::parseBinutilsVersion(Version: BinutilsVersion);
567 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
568 Options.MCOptions.AsmVerbose = AsmVerbose;
569 Options.MCOptions.PreserveAsmComments = PreserveComments;
570 if (OutputAsmVariant.getNumOccurrences())
571 Options.MCOptions.OutputAsmVariant = OutputAsmVariant;
572 Options.MCOptions.IASSearchPaths = IncludeDirs;
573 Options.MCOptions.InstPrinterOptions = InstPrinterOptions;
574 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
575 if (DwarfDirectory.getPosition()) {
576 Options.MCOptions.MCUseDwarfDirectory =
577 DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
578 : MCTargetOptions::DisableDwarfDirectory;
579 } else {
580 // -dwarf-directory is not set explicitly. Some assemblers
581 // (e.g. GNU as or ptxas) do not support `.file directory'
582 // syntax prior to DWARFv5. Let the target decide the default
583 // value.
584 Options.MCOptions.MCUseDwarfDirectory =
585 MCTargetOptions::DefaultDwarfDirectory;
586 }
587 };
588
589 std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
590 std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
591
592 const Target *TheTarget = nullptr;
593 std::unique_ptr<TargetMachine> Target;
594
595 // If user just wants to list available options, skip module loading
596 auto MAttrs = codegen::getMAttrs();
597 bool SkipModule =
598 CPUStr == "help" || TuneCPUStr == "help" || is_contained(Range&: MAttrs, Element: "help");
599 if (SkipModule) {
600 if (!TargetTriple.empty())
601 TheTriple = Triple(Triple::normalize(Str: TargetTriple));
602 else
603 TheTriple = Triple(sys::getDefaultTargetTriple());
604
605 // Get the target specific parser.
606 std::string Error;
607 TheTarget =
608 TargetRegistry::lookupTarget(ArchName: codegen::getMArch(), TheTriple, Error);
609 if (!TheTarget) {
610 WithColor::error(OS&: errs(), Prefix: argv[0]) << Error << "\n";
611 return 1;
612 }
613
614 InitializeOptions(TheTriple);
615 // Pass "help" as CPU for -mtune=help
616 std::string SkipModuleCPU = (TuneCPUStr == "help" ? "help" : CPUStr);
617 // Create the target machine just to print the help info. Use unique_ptr
618 // to avoid a memory leak.
619 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
620 TT: TheTriple, CPU: SkipModuleCPU, Features: FeaturesStr, Options, RM, CM, OL: OLvl));
621 if (!Target) {
622 WithColor::error(OS&: errs(), Prefix: argv[0])
623 << "could not allocate target machine\n";
624 return 1;
625 }
626
627 // If we don't have a module then just exit now. We do this down
628 // here since the CPU/Feature help is underneath the target machine
629 // creation.
630 return 0;
631 }
632
633 auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,
634 StringRef OldDLStr) -> std::optional<std::string> {
635 // If we are supposed to override the target triple, do so now.
636 std::string IRTargetTriple = DataLayoutTargetTriple.str();
637 if (!TargetTriple.empty())
638 IRTargetTriple = Triple::normalize(Str: TargetTriple);
639 TheTriple = Triple(IRTargetTriple);
640 if (TheTriple.getTriple().empty())
641 TheTriple.setTriple(sys::getDefaultTargetTriple());
642
643 std::string Error;
644 TheTarget =
645 TargetRegistry::lookupTarget(ArchName: codegen::getMArch(), TheTriple, Error);
646 if (!TheTarget) {
647 WithColor::error(OS&: errs(), Prefix: argv[0]) << Error << "\n";
648 exit(status: 1);
649 }
650
651 InitializeOptions(TheTriple);
652 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
653 TT: TheTriple, CPU: CPUStr, Features: FeaturesStr, Options, RM, CM, OL: OLvl));
654 if (!Target) {
655 WithColor::error(OS&: errs(), Prefix: argv[0])
656 << "could not allocate target machine\n";
657 exit(status: 1);
658 }
659
660 // Set PGO options based on command line flags
661 setPGOOptions(*Target);
662
663 return TheTriple.computeDataLayout(ABIName: Options.MCOptions.getABIName());
664 };
665 if (InputLanguage == "mir" ||
666 (InputLanguage == "" && StringRef(InputFilename).ends_with(Suffix: ".mir"))) {
667 MIR = createMIRParserFromFile(Filename: InputFilename, Error&: Err, Context,
668 ProcessIRFunction: setMIRFunctionAttributes);
669 if (MIR)
670 M = MIR->parseIRModule(DataLayoutCallback: SetDataLayout);
671 } else {
672 M = parseIRFile(Filename: InputFilename, Err, Context,
673 Callbacks: ParserCallbacks(SetDataLayout));
674 }
675 if (!M) {
676 Err.print(ProgName: argv[0], S&: WithColor::error(OS&: errs(), Prefix: argv[0]));
677 return 1;
678 }
679
680 M->setTargetTriple(TheTriple);
681
682 std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
683 if (!CM && CM_IR)
684 Target->setCodeModel(*CM_IR);
685 if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
686 Target->setLargeDataThreshold(*LDT);
687
688 // Figure out where we are going to send the output.
689 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OS: TheTriple.getOS());
690 if (!Out)
691 return 1;
692
693 // Ensure the filename is passed down to CodeViewDebug.
694 Target->Options.ObjectFilenameForDebug = Out->outputFilename();
695
696 // Return a copy of the output filename via the output param
697 OutputFilename = Out->outputFilename();
698
699 // Tell target that this tool is not necessarily used with argument ABI
700 // compliance (i.e. narrow integer argument extensions).
701 Target->Options.VerifyArgABICompliance = 0;
702
703 std::unique_ptr<ToolOutputFile> DwoOut;
704 if (!SplitDwarfOutputFile.empty()) {
705 std::error_code EC;
706 DwoOut = std::make_unique<ToolOutputFile>(args&: SplitDwarfOutputFile, args&: EC,
707 args: sys::fs::OF_None);
708 if (EC)
709 reportError(Msg: EC.message(), Filename: SplitDwarfOutputFile);
710 }
711
712 // Add an appropriate TargetLibraryInfo pass for the module's triple.
713 TargetLibraryInfoImpl TLII(M->getTargetTriple(), Target->Options.VecLib);
714
715 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
716 if (DisableSimplifyLibCalls)
717 TLII.disableAllFunctions();
718
719 // Verify module immediately to catch problems before doInitialization() is
720 // called on any passes.
721 if (!NoVerify && verifyModule(M: *M, OS: &errs()))
722 reportError(Msg: "input module cannot be verified", Filename: InputFilename);
723
724 // Override function attributes based on CPUStr, TuneCPUStr, FeaturesStr, and
725 // command line flags.
726 codegen::setFunctionAttributes(M&: *M, CPU: CPUStr, Features: FeaturesStr, TuneCPU: TuneCPUStr);
727
728 for (auto &Plugin : PluginList) {
729 CodeGenFileType CGFT = codegen::getFileType();
730 if (Plugin.invokePreCodeGenCallback(M&: *M, TM&: *Target, CGFT, OS&: Out->os())) {
731 // TODO: Deduplicate code with below and the NewPMDriver.
732 if (Context.getDiagHandlerPtr()->HasErrors)
733 exit(status: 1);
734 Out->keep();
735 return 0;
736 }
737 }
738
739 if (mc::getExplicitRelaxAll() &&
740 codegen::getFileType() != CodeGenFileType::ObjectFile)
741 WithColor::warning(OS&: errs(), Prefix: argv[0])
742 << ": warning: ignoring -mc-relax-all because filetype != obj";
743
744 VerifierKind VK = VerifierKind::InputOutput;
745 if (NoVerify)
746 VK = VerifierKind::None;
747 else if (VerifyEach)
748 VK = VerifierKind::EachPass;
749
750 // Use the NewPM if the user specifies -passes (NewPM specific), specifically
751 // requests the NewPM with -enable-new-pm, or the target defaults to the
752 // NewPM, the user has not explicitly disabled the NewPM with
753 // -enable-new-pm=false, and the user has not specified -run-pass.
754 if (!PassPipeline.empty() ||
755 (EnableNewPassManager.getNumOccurrences() > 0 && EnableNewPassManager) ||
756 (Target->shouldDefaultToNewPM() &&
757 !(EnableNewPassManager.getNumOccurrences() && !EnableNewPassManager) &&
758 getRunPassNames().empty())) {
759 return compileModuleWithNewPM(
760 Arg0: argv[0], M: std::move(M), MIR: std::move(MIR), Target: std::move(Target),
761 Out: std::move(Out), DwoOut: std::move(DwoOut), Context, TLII, VK, PassPipeline,
762 PassPlugins: PluginList, FileType: codegen::getFileType());
763 }
764
765 // Build up all of the passes that we want to do to the module.
766 legacy::PassManager PM;
767 PM.add(P: new TargetLibraryInfoWrapperPass(TLII));
768 PM.add(P: new RuntimeLibraryInfoWrapper(Options.MCOptions.ABIName,
769 Target->Options.VecLib));
770
771 {
772 raw_pwrite_stream *OS = &Out->os();
773
774 // Manually do the buffering rather than using buffer_ostream,
775 // so we can memcmp the contents in CompileTwice mode
776 SmallVector<char, 0> Buffer;
777 std::unique_ptr<raw_svector_ostream> BOS;
778 if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
779 !Out->os().supportsSeeking()) ||
780 CompileTwice) {
781 BOS = std::make_unique<raw_svector_ostream>(args&: Buffer);
782 OS = BOS.get();
783 }
784
785 const char *argv0 = argv[0];
786 MachineModuleInfoWrapperPass *MMIWP =
787 new MachineModuleInfoWrapperPass(Target.get());
788
789 // Set a temporary diagnostic handler. This is used before
790 // MachineModuleInfoWrapperPass::doInitialization for features like -M.
791 bool HasMCErrors = false;
792 MCContext &MCCtx = MMIWP->getMMI().getContext();
793 MCCtx.setDiagnosticHandler([&](const SMDiagnostic &SMD, bool IsInlineAsm,
794 const SourceMgr &SrcMgr,
795 std::vector<const MDNode *> &LocInfos) {
796 WithColor::error(OS&: errs(), Prefix: argv0) << SMD.getMessage() << '\n';
797 HasMCErrors = true;
798 });
799
800 // Construct a custom pass pipeline that starts after instruction
801 // selection.
802 if (!getRunPassNames().empty()) {
803 if (!MIR) {
804 WithColor::error(OS&: errs(), Prefix: argv[0])
805 << "run-pass is for .mir file only.\n";
806 delete MMIWP;
807 return 1;
808 }
809 TargetPassConfig *PTPC = Target->createPassConfig(PM);
810 TargetPassConfig &TPC = *PTPC;
811 if (TPC.hasLimitedCodeGenPipeline()) {
812 WithColor::error(OS&: errs(), Prefix: argv[0])
813 << "run-pass cannot be used with "
814 << TPC.getLimitedCodeGenPipelineReason() << ".\n";
815 delete PTPC;
816 delete MMIWP;
817 return 1;
818 }
819
820 TPC.setDisableVerify(NoVerify);
821 PM.add(P: &TPC);
822 PM.add(P: MMIWP);
823 TPC.printAndVerify(Banner: "");
824 for (const std::string &RunPassName : getRunPassNames()) {
825 if (addPass(PM, argv0, PassName: RunPassName, TPC))
826 return 1;
827 }
828 TPC.setInitialized();
829 PM.add(P: createPrintMIRPass(OS&: *OS));
830
831 // Add MIR2Vec vocabulary printer if requested
832 if (PrintMIR2VecVocab) {
833 PM.add(P: createMIR2VecVocabPrinterLegacyPass(OS&: errs()));
834 }
835
836 // Add MIR2Vec printer if requested
837 if (PrintMIR2Vec) {
838 PM.add(P: createMIR2VecPrinterLegacyPass(OS&: errs()));
839 }
840
841 PM.add(P: createFreeMachineFunctionPass());
842 } else {
843 if (Target->addPassesToEmitFile(PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
844 codegen::getFileType(), NoVerify,
845 MMIWP)) {
846 if (!HasMCErrors)
847 reportError(Msg: "target does not support generation of this file type");
848 }
849
850 // Add MIR2Vec vocabulary printer if requested
851 if (PrintMIR2VecVocab) {
852 PM.add(P: createMIR2VecVocabPrinterLegacyPass(OS&: errs()));
853 }
854
855 // Add MIR2Vec printer if requested
856 if (PrintMIR2Vec) {
857 PM.add(P: createMIR2VecPrinterLegacyPass(OS&: errs()));
858 }
859 }
860
861 Target->getObjFileLowering()->Initialize(ctx&: MMIWP->getMMI().getContext(),
862 TM: *Target);
863 if (MIR) {
864 assert(MMIWP && "Forgot to create MMIWP?");
865 if (MIR->parseMachineFunctions(M&: *M, MMI&: MMIWP->getMMI()))
866 return 1;
867 }
868
869 // Before executing passes, print the final values of the LLVM options.
870 cl::PrintOptionValues();
871
872 // If requested, run the pass manager over the same module again,
873 // to catch any bugs due to persistent state in the passes. Note that
874 // opt has the same functionality, so it may be worth abstracting this out
875 // in the future.
876 SmallVector<char, 0> CompileTwiceBuffer;
877 if (CompileTwice) {
878 std::unique_ptr<Module> M2(llvm::CloneModule(M: *M));
879 PM.run(M&: *M2);
880 CompileTwiceBuffer = Buffer;
881 Buffer.clear();
882 }
883
884 PM.run(M&: *M);
885
886 if (Context.getDiagHandlerPtr()->HasErrors || HasMCErrors)
887 return 1;
888
889 // Compare the two outputs and make sure they're the same
890 if (CompileTwice) {
891 if (Buffer.size() != CompileTwiceBuffer.size() ||
892 (memcmp(s1: Buffer.data(), s2: CompileTwiceBuffer.data(), n: Buffer.size()) !=
893 0)) {
894 errs()
895 << "Running the pass manager twice changed the output.\n"
896 "Writing the result of the second run to the specified output\n"
897 "To generate the one-run comparison binary, just run without\n"
898 "the compile-twice option\n";
899 Out->os() << Buffer;
900 Out->keep();
901 return 1;
902 }
903 }
904
905 if (BOS) {
906 Out->os() << Buffer;
907 }
908 }
909
910 // Declare success.
911 Out->keep();
912 if (DwoOut)
913 DwoOut->keep();
914
915 return 0;
916}
917