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

source code of llvm/tools/llc/llc.cpp