Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/llvm-project/llvm/tools/llc/llc.cpp
35231 views
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> DisableSimplifyLibCalls("disable-simplify-libcalls",
134
cl::desc("Disable simplify-libcalls"));
135
136
static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
137
cl::desc("Show encoding in .s output"));
138
139
static cl::opt<bool>
140
DwarfDirectory("dwarf-directory", cl::Hidden,
141
cl::desc("Use .file directives with an explicit directory"),
142
cl::init(true));
143
144
static cl::opt<bool> AsmVerbose("asm-verbose",
145
cl::desc("Add comments to directives."),
146
cl::init(true));
147
148
static 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(false));
153
154
static cl::opt<bool> DiscardValueNames(
155
"discard-value-names",
156
cl::desc("Discard names from Value (other than GlobalValue)."),
157
cl::init(false), cl::Hidden);
158
159
static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
160
161
static cl::opt<bool> RemarksWithHotness(
162
"pass-remarks-with-hotness",
163
cl::desc("With PGO, include profile count in optimization remarks"),
164
cl::Hidden);
165
166
static 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(0), cl::Hidden);
173
174
static cl::opt<std::string>
175
RemarksFilename("pass-remarks-output",
176
cl::desc("Output filename for pass remarks"),
177
cl::value_desc("filename"));
178
179
static 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
185
static 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("yaml"));
189
190
static cl::opt<bool> EnableNewPassManager(
191
"enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(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.
197
static 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>'."));
202
static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),
203
cl::desc("Alias for -passes"));
204
205
static cl::opt<bool> TryUseNewDbgInfoFormat(
206
"try-experimental-debuginfo-iterators",
207
cl::desc("Enable debuginfo iterator positions, if they're built in"),
208
cl::init(false), cl::Hidden);
209
210
extern cl::opt<bool> UseNewDbgInfoFormat;
211
212
namespace {
213
214
std::vector<std::string> &getRunPassNames() {
215
static std::vector<std::string> RunPassNames;
216
return RunPassNames;
217
}
218
219
struct RunPassOption {
220
void operator=(const std::string &Val) const {
221
if (Val.empty())
222
return;
223
SmallVector<StringRef, 8> PassNames;
224
StringRef(Val).split(PassNames, ',', -1, false);
225
for (auto PassName : PassNames)
226
getRunPassNames().push_back(std::string(PassName));
227
}
228
};
229
} // namespace
230
231
static RunPassOption RunPassOpt;
232
233
static 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(RunPassOpt));
237
238
static 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(Prefix);
246
}
247
WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
248
exit(1);
249
}
250
251
[[noreturn]] static void reportError(Error Err, StringRef Filename) {
252
assert(Err);
253
handleAllErrors(createFileError(Filename, std::move(Err)),
254
[&](const ErrorInfoBase &EI) { reportError(EI.message()); });
255
llvm_unreachable("reportError() should not return");
256
}
257
258
static 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(".bc") || IFN.ends_with(".ll"))
269
OutputFilename = std::string(IFN.drop_back(3));
270
else if (IFN.ends_with(".mir"))
271
OutputFilename = std::string(IFN.drop_back(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>(OutputFilename, EC, OpenFlags);
309
if (EC) {
310
reportError(EC.message());
311
return nullptr;
312
}
313
314
return FDOut;
315
}
316
317
// main - Entry point for the llc compiler.
318
//
319
int 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
initializePostInlineEntryExitInstrumenterPass(*Registry);
339
initializeUnreachableBlockElimLegacyPassPass(*Registry);
340
initializeConstantHoistingLegacyPassPass(*Registry);
341
initializeScalarOpts(*Registry);
342
initializeVectorization(*Registry);
343
initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
344
initializeExpandReductionsPass(*Registry);
345
initializeExpandVectorPredicationPass(*Registry);
346
initializeHardwareLoopsLegacyPass(*Registry);
347
initializeTransformUtils(*Registry);
348
initializeReplaceWithVeclibLegacyPass(*Registry);
349
initializeTLSVariableHoistLegacyPassPass(*Registry);
350
351
// Initialize debugging passes.
352
initializeScavengerTestPass(*Registry);
353
354
// Register the Target and CPU printer for --version.
355
cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
356
// Register the target printer for --version.
357
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
358
359
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
360
361
if (!PassPipeline.empty() && !getRunPassNames().empty()) {
362
errs() << "The `llc -run-pass=...` syntax for the new pass manager is "
363
"not supported, please use `llc -passes=<pipeline>` (or the `-p` "
364
"alias for a more concise version).\n";
365
return 1;
366
}
367
368
// RemoveDIs debug-info transition: tests may request that we /try/ to use the
369
// new debug-info format.
370
if (TryUseNewDbgInfoFormat) {
371
// Turn the new debug-info format on.
372
UseNewDbgInfoFormat = true;
373
}
374
375
if (TimeTrace)
376
timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
377
auto TimeTraceScopeExit = make_scope_exit([]() {
378
if (TimeTrace) {
379
if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
380
handleAllErrors(std::move(E), [&](const StringError &SE) {
381
errs() << SE.getMessage() << "\n";
382
});
383
return;
384
}
385
timeTraceProfilerCleanup();
386
}
387
});
388
389
LLVMContext Context;
390
Context.setDiscardValueNames(DiscardValueNames);
391
392
// Set a diagnostic handler that doesn't exit on the first error
393
Context.setDiagnosticHandler(std::make_unique<LLCDiagnosticHandler>());
394
395
Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
396
setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
397
RemarksFormat, RemarksWithHotness,
398
RemarksHotnessThreshold);
399
if (Error E = RemarksFileOrErr.takeError())
400
reportError(std::move(E), RemarksFilename);
401
std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
402
403
if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
404
reportError("input language must be '', 'IR' or 'MIR'");
405
406
// Compile the module TimeCompilations times to give better compile time
407
// metrics.
408
for (unsigned I = TimeCompilations; I; --I)
409
if (int RetVal = compileModule(argv, Context))
410
return RetVal;
411
412
if (RemarksFile)
413
RemarksFile->keep();
414
return 0;
415
}
416
417
static bool addPass(PassManagerBase &PM, const char *argv0,
418
StringRef PassName, TargetPassConfig &TPC) {
419
if (PassName == "none")
420
return false;
421
422
const PassRegistry *PR = PassRegistry::getPassRegistry();
423
const PassInfo *PI = PR->getPassInfo(PassName);
424
if (!PI) {
425
WithColor::error(errs(), argv0)
426
<< "run-pass " << PassName << " is not registered.\n";
427
return true;
428
}
429
430
Pass *P;
431
if (PI->getNormalCtor())
432
P = PI->getNormalCtor()();
433
else {
434
WithColor::error(errs(), argv0)
435
<< "cannot create pass: " << PI->getPassName() << "\n";
436
return true;
437
}
438
std::string Banner = std::string("After ") + std::string(P->getPassName());
439
TPC.addMachinePrePasses();
440
PM.add(P);
441
TPC.addMachinePostPasses(Banner);
442
443
return false;
444
}
445
446
static int compileModule(char **argv, LLVMContext &Context) {
447
// Load the module to be compiled...
448
SMDiagnostic Err;
449
std::unique_ptr<Module> M;
450
std::unique_ptr<MIRParser> MIR;
451
Triple TheTriple;
452
std::string CPUStr = codegen::getCPUStr(),
453
FeaturesStr = codegen::getFeaturesStr();
454
455
// Set attributes on functions as loaded from MIR from command line arguments.
456
auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
457
codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
458
};
459
460
auto MAttrs = codegen::getMAttrs();
461
bool SkipModule =
462
CPUStr == "help" || (!MAttrs.empty() && MAttrs.front() == "help");
463
464
CodeGenOptLevel OLvl;
465
if (auto Level = CodeGenOpt::parseLevel(OptLevel)) {
466
OLvl = *Level;
467
} else {
468
WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
469
return 1;
470
}
471
472
// Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
473
// use that to indicate the MC default.
474
if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
475
StringRef V = BinutilsVersion.getValue();
476
unsigned Num;
477
if (V.consumeInteger(10, Num) || Num == 0 ||
478
!(V.empty() ||
479
(V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
480
WithColor::error(errs(), argv[0])
481
<< "invalid -binutils-version, accepting 'none' or major.minor\n";
482
return 1;
483
}
484
}
485
TargetOptions Options;
486
auto InitializeOptions = [&](const Triple &TheTriple) {
487
Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
488
489
if (Options.XCOFFReadOnlyPointers) {
490
if (!TheTriple.isOSAIX())
491
reportError("-mxcoff-roptr option is only supported on AIX",
492
InputFilename);
493
494
// Since the storage mapping class is specified per csect,
495
// without using data sections, it is less effective to use read-only
496
// pointers. Using read-only pointers may cause other RO variables in the
497
// same csect to become RW when the linker acts upon `-bforceimprw`;
498
// therefore, we require that separate data sections are used in the
499
// presence of ReadOnlyPointers. We respect the setting of data-sections
500
// since we have not found reasons to do otherwise that overcome the user
501
// surprise of not respecting the setting.
502
if (!Options.DataSections)
503
reportError("-mxcoff-roptr option must be used with -data-sections",
504
InputFilename);
505
}
506
507
Options.BinutilsVersion =
508
TargetMachine::parseBinutilsVersion(BinutilsVersion);
509
Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
510
Options.MCOptions.AsmVerbose = AsmVerbose;
511
Options.MCOptions.PreserveAsmComments = PreserveComments;
512
Options.MCOptions.IASSearchPaths = IncludeDirs;
513
Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
514
if (DwarfDirectory.getPosition()) {
515
Options.MCOptions.MCUseDwarfDirectory =
516
DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory
517
: MCTargetOptions::DisableDwarfDirectory;
518
} else {
519
// -dwarf-directory is not set explicitly. Some assemblers
520
// (e.g. GNU as or ptxas) do not support `.file directory'
521
// syntax prior to DWARFv5. Let the target decide the default
522
// value.
523
Options.MCOptions.MCUseDwarfDirectory =
524
MCTargetOptions::DefaultDwarfDirectory;
525
}
526
};
527
528
std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
529
std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();
530
531
const Target *TheTarget = nullptr;
532
std::unique_ptr<TargetMachine> Target;
533
534
// If user just wants to list available options, skip module loading
535
if (!SkipModule) {
536
auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,
537
StringRef OldDLStr) -> std::optional<std::string> {
538
// If we are supposed to override the target triple, do so now.
539
std::string IRTargetTriple = DataLayoutTargetTriple.str();
540
if (!TargetTriple.empty())
541
IRTargetTriple = Triple::normalize(TargetTriple);
542
TheTriple = Triple(IRTargetTriple);
543
if (TheTriple.getTriple().empty())
544
TheTriple.setTriple(sys::getDefaultTargetTriple());
545
546
std::string Error;
547
TheTarget =
548
TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
549
if (!TheTarget) {
550
WithColor::error(errs(), argv[0]) << Error;
551
exit(1);
552
}
553
554
InitializeOptions(TheTriple);
555
Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
556
TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
557
assert(Target && "Could not allocate target machine!");
558
559
return Target->createDataLayout().getStringRepresentation();
560
};
561
if (InputLanguage == "mir" ||
562
(InputLanguage == "" && StringRef(InputFilename).ends_with(".mir"))) {
563
MIR = createMIRParserFromFile(InputFilename, Err, Context,
564
setMIRFunctionAttributes);
565
if (MIR)
566
M = MIR->parseIRModule(SetDataLayout);
567
} else {
568
M = parseIRFile(InputFilename, Err, Context,
569
ParserCallbacks(SetDataLayout));
570
}
571
if (!M) {
572
Err.print(argv[0], WithColor::error(errs(), argv[0]));
573
return 1;
574
}
575
if (!TargetTriple.empty())
576
M->setTargetTriple(Triple::normalize(TargetTriple));
577
578
std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
579
if (!CM && CM_IR)
580
Target->setCodeModel(*CM_IR);
581
if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())
582
Target->setLargeDataThreshold(*LDT);
583
} else {
584
TheTriple = Triple(Triple::normalize(TargetTriple));
585
if (TheTriple.getTriple().empty())
586
TheTriple.setTriple(sys::getDefaultTargetTriple());
587
588
// Get the target specific parser.
589
std::string Error;
590
TheTarget =
591
TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
592
if (!TheTarget) {
593
WithColor::error(errs(), argv[0]) << Error;
594
return 1;
595
}
596
597
InitializeOptions(TheTriple);
598
Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
599
TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM, CM, OLvl));
600
assert(Target && "Could not allocate target machine!");
601
602
// If we don't have a module then just exit now. We do this down
603
// here since the CPU/Feature help is underneath the target machine
604
// creation.
605
return 0;
606
}
607
608
assert(M && "Should have exited if we didn't have a module!");
609
if (codegen::getFloatABIForCalls() != FloatABI::Default)
610
Target->Options.FloatABIType = codegen::getFloatABIForCalls();
611
612
// Figure out where we are going to send the output.
613
std::unique_ptr<ToolOutputFile> Out =
614
GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
615
if (!Out) return 1;
616
617
// Ensure the filename is passed down to CodeViewDebug.
618
Target->Options.ObjectFilenameForDebug = Out->outputFilename();
619
620
std::unique_ptr<ToolOutputFile> DwoOut;
621
if (!SplitDwarfOutputFile.empty()) {
622
std::error_code EC;
623
DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
624
sys::fs::OF_None);
625
if (EC)
626
reportError(EC.message(), SplitDwarfOutputFile);
627
}
628
629
// Add an appropriate TargetLibraryInfo pass for the module's triple.
630
TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
631
632
// The -disable-simplify-libcalls flag actually disables all builtin optzns.
633
if (DisableSimplifyLibCalls)
634
TLII.disableAllFunctions();
635
636
// Verify module immediately to catch problems before doInitialization() is
637
// called on any passes.
638
if (!NoVerify && verifyModule(*M, &errs()))
639
reportError("input module cannot be verified", InputFilename);
640
641
// Override function attributes based on CPUStr, FeaturesStr, and command line
642
// flags.
643
codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
644
645
if (mc::getExplicitRelaxAll() &&
646
codegen::getFileType() != CodeGenFileType::ObjectFile)
647
WithColor::warning(errs(), argv[0])
648
<< ": warning: ignoring -mc-relax-all because filetype != obj";
649
650
if (EnableNewPassManager || !PassPipeline.empty()) {
651
return compileModuleWithNewPM(argv[0], std::move(M), std::move(MIR),
652
std::move(Target), std::move(Out),
653
std::move(DwoOut), Context, TLII, NoVerify,
654
PassPipeline, codegen::getFileType());
655
}
656
657
// Build up all of the passes that we want to do to the module.
658
legacy::PassManager PM;
659
PM.add(new TargetLibraryInfoWrapperPass(TLII));
660
661
{
662
raw_pwrite_stream *OS = &Out->os();
663
664
// Manually do the buffering rather than using buffer_ostream,
665
// so we can memcmp the contents in CompileTwice mode
666
SmallVector<char, 0> Buffer;
667
std::unique_ptr<raw_svector_ostream> BOS;
668
if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&
669
!Out->os().supportsSeeking()) ||
670
CompileTwice) {
671
BOS = std::make_unique<raw_svector_ostream>(Buffer);
672
OS = BOS.get();
673
}
674
675
const char *argv0 = argv[0];
676
LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
677
MachineModuleInfoWrapperPass *MMIWP =
678
new MachineModuleInfoWrapperPass(&LLVMTM);
679
680
// Construct a custom pass pipeline that starts after instruction
681
// selection.
682
if (!getRunPassNames().empty()) {
683
if (!MIR) {
684
WithColor::warning(errs(), argv[0])
685
<< "run-pass is for .mir file only.\n";
686
delete MMIWP;
687
return 1;
688
}
689
TargetPassConfig *PTPC = LLVMTM.createPassConfig(PM);
690
TargetPassConfig &TPC = *PTPC;
691
if (TPC.hasLimitedCodeGenPipeline()) {
692
WithColor::warning(errs(), argv[0])
693
<< "run-pass cannot be used with "
694
<< TPC.getLimitedCodeGenPipelineReason() << ".\n";
695
delete PTPC;
696
delete MMIWP;
697
return 1;
698
}
699
700
TPC.setDisableVerify(NoVerify);
701
PM.add(&TPC);
702
PM.add(MMIWP);
703
TPC.printAndVerify("");
704
for (const std::string &RunPassName : getRunPassNames()) {
705
if (addPass(PM, argv0, RunPassName, TPC))
706
return 1;
707
}
708
TPC.setInitialized();
709
PM.add(createPrintMIRPass(*OS));
710
PM.add(createFreeMachineFunctionPass());
711
} else if (Target->addPassesToEmitFile(
712
PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
713
codegen::getFileType(), NoVerify, MMIWP)) {
714
reportError("target does not support generation of this file type");
715
}
716
717
const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
718
->Initialize(MMIWP->getMMI().getContext(), *Target);
719
if (MIR) {
720
assert(MMIWP && "Forgot to create MMIWP?");
721
if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
722
return 1;
723
}
724
725
// Before executing passes, print the final values of the LLVM options.
726
cl::PrintOptionValues();
727
728
// If requested, run the pass manager over the same module again,
729
// to catch any bugs due to persistent state in the passes. Note that
730
// opt has the same functionality, so it may be worth abstracting this out
731
// in the future.
732
SmallVector<char, 0> CompileTwiceBuffer;
733
if (CompileTwice) {
734
std::unique_ptr<Module> M2(llvm::CloneModule(*M));
735
PM.run(*M2);
736
CompileTwiceBuffer = Buffer;
737
Buffer.clear();
738
}
739
740
PM.run(*M);
741
742
if (Context.getDiagHandlerPtr()->HasErrors)
743
return 1;
744
745
// Compare the two outputs and make sure they're the same
746
if (CompileTwice) {
747
if (Buffer.size() != CompileTwiceBuffer.size() ||
748
(memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
749
0)) {
750
errs()
751
<< "Running the pass manager twice changed the output.\n"
752
"Writing the result of the second run to the specified output\n"
753
"To generate the one-run comparison binary, just run without\n"
754
"the compile-twice option\n";
755
Out->os() << Buffer;
756
Out->keep();
757
return 1;
758
}
759
}
760
761
if (BOS) {
762
Out->os() << Buffer;
763
}
764
}
765
766
// Declare success.
767
Out->keep();
768
if (DwoOut)
769
DwoOut->keep();
770
771
return 0;
772
}
773
774