1//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
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 program takes in a list of bitcode files, links them and performs
10// link-time optimization according to the provided symbol resolutions using the
11// resolution-based LTO interface, and outputs one or more object files.
12//
13// This program is intended to eventually replace llvm-lto which uses the legacy
14// LTO interface.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/Bitcode/BitcodeReader.h"
20#include "llvm/CodeGen/CommandFlags.h"
21#include "llvm/DTLTO/DTLTO.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/LTO/LTO.h"
24#include "llvm/Plugins/PassPlugin.h"
25#include "llvm/Remarks/HotnessThresholdParser.h"
26#include "llvm/Support/Caching.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/InitLLVM.h"
30#include "llvm/Support/PluginLoader.h"
31#include "llvm/Support/TargetSelect.h"
32#include "llvm/Support/Threading.h"
33#include "llvm/Support/TimeProfiler.h"
34#include <atomic>
35#include <list>
36
37using namespace llvm;
38using namespace lto;
39
40static codegen::RegisterCodeGenFlags CGF;
41
42static cl::opt<char>
43 OptLevel("O",
44 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
45 "(default = '-O2')"),
46 cl::Prefix, cl::init(Val: '2'));
47
48static cl::opt<char> CGOptLevel(
49 "cg-opt-level",
50 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
51 cl::init(Val: '2'));
52
53static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
54 cl::desc("<input bitcode files>"));
55
56static cl::opt<std::string> OutputFilename("o", cl::Required,
57 cl::desc("Output filename"),
58 cl::value_desc("filename"));
59
60static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
61 cl::value_desc("directory"));
62
63static cl::opt<std::string> OptPipeline("opt-pipeline",
64 cl::desc("Optimizer Pipeline"),
65 cl::value_desc("pipeline"));
66
67static cl::opt<std::string> AAPipeline("aa-pipeline",
68 cl::desc("Alias Analysis Pipeline"),
69 cl::value_desc("aapipeline"));
70
71static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
72
73static cl::list<std::string> SelectSaveTemps(
74 "select-save-temps",
75 cl::value_desc("One, or multiple of: "
76 "resolution,preopt,promote,internalize,import,opt,precodegen"
77 ",combinedindex"),
78 cl::desc("Save selected temporary files. Cannot be specified together with "
79 "-save-temps"),
80 cl::CommaSeparated);
81
82constexpr const char *SaveTempsValues[] = {
83 "resolution", "preopt", "promote", "internalize",
84 "import", "opt", "precodegen", "combinedindex"};
85
86static cl::opt<bool>
87 ThinLTODistributedIndexes("thinlto-distributed-indexes",
88 cl::desc("Write out individual index and "
89 "import files for the "
90 "distributed backend case"));
91
92static cl::opt<bool>
93 ThinLTOEmitIndexes("thinlto-emit-indexes",
94 cl::desc("Write out individual index files via "
95 "InProcessThinLTO"));
96
97static cl::opt<bool>
98 ThinLTOEmitImports("thinlto-emit-imports",
99 cl::desc("Write out individual imports files via "
100 "InProcessThinLTO. Has no effect unless "
101 "specified with -thinlto-emit-indexes or "
102 "-thinlto-distributed-indexes"));
103
104static cl::opt<std::string> DTLTODistributor(
105 "dtlto-distributor",
106 cl::desc("Distributor to use for ThinLTO backend compilations. Specifying "
107 "this enables DTLTO."));
108
109static cl::list<std::string> DTLTODistributorArgs(
110 "dtlto-distributor-arg", cl::CommaSeparated,
111 cl::desc("Arguments to pass to the DTLTO distributor process."),
112 cl::value_desc("arg"));
113
114static cl::opt<std::string> DTLTOCompiler(
115 "dtlto-compiler",
116 cl::desc("Compiler to use for DTLTO ThinLTO backend compilations."));
117
118static cl::list<std::string> DTLTOCompilerPrependArgs(
119 "dtlto-compiler-prepend-arg", cl::CommaSeparated,
120 cl::desc("Prepend arguments to pass to the remote compiler for backend "
121 "compilations."),
122 cl::value_desc("arg"));
123
124static cl::list<std::string> DTLTOCompilerArgs(
125 "dtlto-compiler-arg", cl::CommaSeparated,
126 cl::desc("Arguments to pass to the remote compiler for backend "
127 "compilations."),
128 cl::value_desc("arg"));
129
130// Default to using all available threads in the system, but using only one
131// thread per core (no SMT).
132// Use -thinlto-threads=all to use hardware_concurrency() instead, which means
133// to use all hardware threads or cores in the system.
134static cl::opt<std::string> Threads("thinlto-threads");
135
136static cl::list<std::string> SymbolResolutions(
137 "r",
138 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
139 "where \"resolution\" is a sequence (which may be empty) of the\n"
140 "following characters:\n"
141 " p - prevailing: the linker has chosen this definition of the\n"
142 " symbol\n"
143 " l - local: the definition of this symbol is unpreemptable at\n"
144 " runtime and is known to be in this linkage unit\n"
145 " x - externally visible: the definition of this symbol is\n"
146 " visible outside of the LTO unit\n"
147 "A resolution for each symbol must be specified"));
148
149static cl::opt<std::string> OverrideTriple(
150 "override-triple",
151 cl::desc("Replace target triples in input files with this triple"));
152
153static cl::opt<std::string> DefaultTriple(
154 "default-triple",
155 cl::desc(
156 "Replace unspecified target triples in input files with this triple"));
157
158static cl::opt<bool> RemarksWithHotness(
159 "pass-remarks-with-hotness",
160 cl::desc("With PGO, include profile count in optimization remarks"),
161 cl::Hidden);
162
163static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
164 RemarksHotnessThreshold(
165 "pass-remarks-hotness-threshold",
166 cl::desc("Minimum profile count required for an "
167 "optimization remark to be output."
168 " Use 'auto' to apply the threshold from profile summary."),
169 cl::value_desc("uint or 'auto'"), cl::init(Val: 0), cl::Hidden);
170
171static cl::opt<std::string>
172 RemarksFilename("pass-remarks-output",
173 cl::desc("Output filename for pass remarks"),
174 cl::value_desc("filename"));
175
176static cl::opt<std::string>
177 RemarksPasses("pass-remarks-filter",
178 cl::desc("Only record optimization remarks from passes whose "
179 "names match the given regular expression"),
180 cl::value_desc("regex"));
181
182static cl::opt<std::string> RemarksFormat(
183 "pass-remarks-format",
184 cl::desc("The format used for serializing remarks (default: YAML)"),
185 cl::value_desc("format"), cl::init(Val: "yaml"));
186
187static cl::opt<std::string>
188 SamplePGOFile("lto-sample-profile-file",
189 cl::desc("Specify a SamplePGO profile file"));
190
191static cl::opt<std::string>
192 CSPGOFile("lto-cspgo-profile-file",
193 cl::desc("Specify a context sensitive PGO profile file"));
194
195static cl::opt<bool>
196 RunCSIRInstr("lto-cspgo-gen",
197 cl::desc("Run PGO context sensitive IR instrumentation"),
198 cl::Hidden);
199
200static cl::opt<bool>
201 DebugPassManager("debug-pass-manager", cl::Hidden,
202 cl::desc("Print pass management debugging information"));
203
204static cl::opt<std::string>
205 StatsFile("stats-file", cl::desc("Filename to write statistics to"));
206
207static cl::list<std::string>
208 PassPlugins("load-pass-plugin",
209 cl::desc("Load passes from plugin library"));
210
211static cl::opt<LTO::LTOKind> UnifiedLTOMode(
212 "unified-lto", cl::desc("Set LTO mode with the following options:"),
213 cl::values(clEnumValN(LTO::LTOK_UnifiedThin, "thin",
214 "ThinLTO with Unified LTO enabled"),
215 clEnumValN(LTO::LTOK_UnifiedRegular, "full",
216 "Regular LTO with Unified LTO enabled"),
217 clEnumValN(LTO::LTOK_Default, "default",
218 "Any LTO mode without Unified LTO")),
219 cl::value_desc("mode"), cl::init(Val: LTO::LTOK_Default));
220
221static cl::opt<bool> EnableFreestanding(
222 "lto-freestanding",
223 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
224 cl::Hidden);
225
226static cl::opt<bool> WholeProgramVisibilityEnabledInLTO(
227 "whole-program-visibility-enabled-in-lto",
228 cl::desc("Enable whole program visibility during LTO"), cl::Hidden);
229
230static cl::opt<bool> ValidateAllVtablesHaveTypeInfos(
231 "validate-all-vtables-have-type-infos",
232 cl::desc("Validate that all vtables have type infos in LTO"), cl::Hidden);
233
234static cl::opt<bool>
235 AllVtablesHaveTypeInfos("all-vtables-have-type-infos", cl::Hidden,
236 cl::desc("All vtables have type infos"));
237
238// Specifying a symbol here states that it is a library symbol that had a
239// definition in bitcode, but was not extracted. Such symbols cannot safely
240// be referenced, since they have already lost their opportunity to be defined.
241//
242// FIXME: Listing all bitcode libfunc symbols here is clunky. A higher-level way
243// to indicate which TUs made it into the link might be better, but this would
244// require more detailed tracking of the sources of constructs in the IR.
245// Alternatively, there may be some other data structure that could hold this
246// information.
247static cl::list<std::string> BitcodeLibFuncs(
248 "bitcode-libfuncs", cl::Hidden,
249 cl::desc("set of unextracted libfuncs implemented in bitcode"));
250
251static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
252
253static cl::opt<unsigned> TimeTraceGranularity(
254 "time-trace-granularity",
255 cl::desc(
256 "Minimum time granularity (in microseconds) traced by time profiler"),
257 cl::init(Val: 500), cl::Hidden);
258
259static cl::opt<std::string>
260 TimeTraceFile("time-trace-file",
261 cl::desc("Specify time trace file destination"),
262 cl::value_desc("filename"));
263
264static void check(Error E, std::string Msg) {
265 if (!E)
266 return;
267 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
268 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
269 });
270 exit(status: 1);
271}
272
273template <typename T> static T check(Expected<T> E, std::string Msg) {
274 if (E)
275 return std::move(*E);
276 check(E.takeError(), Msg);
277 return T();
278}
279
280static void check(std::error_code EC, std::string Msg) {
281 check(E: errorCodeToError(EC), Msg);
282}
283
284template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
285 if (E)
286 return std::move(*E);
287 check(E.getError(), Msg);
288 return T();
289}
290
291static int usage() {
292 errs() << "Available subcommands: dump-symtab run print-guid\n";
293 return 1;
294}
295
296static int run(int argc, char **argv) {
297 cl::LibraryOptionsContext LibraryOptions;
298 cl::parseCommandLineOptions(Context&: LibraryOptions, Args: ArrayRef(argv, argc),
299 Overview: "Resolution-based LTO test harness");
300
301 if (TimeTrace)
302 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
303 llvm::scope_exit TimeTraceScopeExit([]() {
304 if (TimeTrace) {
305 check(E: timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename),
306 Msg: "timeTraceProfilerWrite failed");
307 timeTraceProfilerCleanup();
308 }
309 });
310
311 // FIXME: Workaround PR30396 which means that a symbol can appear
312 // more than once if it is defined in module-level assembly and
313 // has a GV declaration. We allow (file, symbol) pairs to have multiple
314 // resolutions and apply them in the order observed.
315 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
316 CommandLineResolutions;
317 for (StringRef R : SymbolResolutions) {
318 StringRef Rest, FileName, SymbolName;
319 std::tie(args&: FileName, args&: Rest) = R.split(Separator: ',');
320 if (Rest.empty()) {
321 llvm::errs() << "invalid resolution: " << R << '\n';
322 return 1;
323 }
324 std::tie(args&: SymbolName, args&: Rest) = Rest.split(Separator: ',');
325 SymbolResolution Res;
326 for (char C : Rest) {
327 if (C == 'p')
328 Res.Prevailing = true;
329 else if (C == 'l')
330 Res.FinalDefinitionInLinkageUnit = true;
331 else if (C == 'x')
332 Res.VisibleToRegularObj = true;
333 else if (C == 'r')
334 Res.LinkerRedefined = true;
335 else {
336 llvm::errs() << "invalid character " << C << " in resolution: " << R
337 << '\n';
338 return 1;
339 }
340 }
341 CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}]
342 .push_back(x: Res);
343 }
344
345 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
346
347 Config Conf;
348 Conf.LibraryOptions = &LibraryOptions;
349 Conf.PTO = PipelineTuningOptions(&LibraryOptions);
350 if (TimeTrace) {
351 Conf.TimeTraceEnabled = TimeTrace;
352 Conf.TimeTraceGranularity = TimeTraceGranularity;
353 }
354 Conf.CPU = codegen::getMCPU();
355 Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple: Triple());
356 Conf.MAttrs = codegen::getMAttrs();
357 if (auto RM = codegen::getExplicitRelocModel())
358 Conf.RelocModel = *RM;
359 Conf.CodeModel = codegen::getExplicitCodeModel();
360
361 Conf.DebugPassManager = DebugPassManager;
362
363 if (SaveTemps && !SelectSaveTemps.empty()) {
364 llvm::errs() << "-save-temps cannot be specified with -select-save-temps\n";
365 return 1;
366 }
367 if (SaveTemps || !SelectSaveTemps.empty()) {
368 DenseSet<StringRef> SaveTempsArgs;
369 for (auto &S : SelectSaveTemps)
370 if (is_contained(Range: SaveTempsValues, Element: S))
371 SaveTempsArgs.insert(V: S);
372 else {
373 llvm::errs() << ("invalid -select-save-temps argument: " + S) << '\n';
374 return 1;
375 }
376 check(E: Conf.addSaveTemps(OutputFileName: OutputFilename + ".", UseInputModulePath: false, SaveTempsArgs),
377 Msg: "Config::addSaveTemps failed");
378 }
379
380 // Optimization remarks.
381 Conf.RemarksFilename = RemarksFilename;
382 Conf.RemarksPasses = RemarksPasses;
383 Conf.RemarksWithHotness = RemarksWithHotness;
384 Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
385 Conf.RemarksFormat = RemarksFormat;
386
387 Conf.SampleProfile = SamplePGOFile;
388 Conf.CSIRProfile = CSPGOFile;
389 Conf.RunCSIRInstr = RunCSIRInstr;
390
391 // Run a custom pipeline, if asked for.
392 Conf.OptPipeline = OptPipeline;
393 Conf.AAPipeline = AAPipeline;
394
395 Conf.OptLevel = OptLevel - '0';
396 Conf.Freestanding = EnableFreestanding;
397 llvm::append_range(C&: Conf.PassPluginFilenames, R&: PassPlugins);
398 if (auto Level = CodeGenOpt::parseLevel(C: CGOptLevel)) {
399 Conf.CGOptLevel = *Level;
400 } else {
401 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
402 return 1;
403 }
404
405 if (auto FT = codegen::getExplicitFileType())
406 Conf.CGFileType = *FT;
407
408 Conf.OverrideTriple = OverrideTriple;
409 Conf.DefaultTriple = DefaultTriple;
410 Conf.StatsFile = StatsFile;
411 Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
412 Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
413
414 if (WholeProgramVisibilityEnabledInLTO.getNumOccurrences() > 0)
415 Conf.HasWholeProgramVisibility = WholeProgramVisibilityEnabledInLTO;
416 if (ValidateAllVtablesHaveTypeInfos.getNumOccurrences() > 0)
417 Conf.ValidateAllVtablesHaveTypeInfos = ValidateAllVtablesHaveTypeInfos;
418 if (AllVtablesHaveTypeInfos.getNumOccurrences() > 0)
419 Conf.AllVtablesHaveTypeInfos = AllVtablesHaveTypeInfos;
420
421 if (ThinLTODistributedIndexes && !DTLTODistributor.empty())
422 llvm::errs() << "-thinlto-distributed-indexes cannot be specfied together "
423 "with -dtlto-distributor\n";
424 auto DTLTODistributorArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
425 C&: DTLTODistributorArgs, F: [](const std::string &S) { return StringRef(S); }));
426 auto DTLTOCompilerPrependArgsSV = llvm::to_vector<0>(
427 Range: llvm::map_range(C&: DTLTOCompilerPrependArgs,
428 F: [](const std::string &S) { return StringRef(S); }));
429 auto DTLTOCompilerArgsSV = llvm::to_vector<0>(Range: llvm::map_range(
430 C&: DTLTOCompilerArgs, F: [](const std::string &S) { return StringRef(S); }));
431
432 auto AddStream =
433 [&](size_t Task,
434 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
435 std::string Path = OutputFilename + "." + utostr(X: Task);
436
437 std::error_code EC;
438 auto S = std::make_unique<raw_fd_ostream>(args&: Path, args&: EC, args: sys::fs::OF_None);
439 check(EC, Msg: Path);
440 return std::make_unique<CachedFileStream>(args: std::move(S), args&: Path);
441 };
442
443 auto AddBuffer = [&](size_t Task, const Twine &ModuleName,
444 std::unique_ptr<MemoryBuffer> MB) {
445 auto Stream = AddStream(Task, ModuleName);
446 *Stream->OS << MB->getBuffer();
447 check(E: Stream->commit(), Msg: "Failed to commit cache");
448 };
449
450 ThinBackend Backend;
451 if (ThinLTODistributedIndexes)
452 Backend = createWriteIndexesThinBackend(Parallelism: llvm::hardware_concurrency(Num: Threads),
453 /*OldPrefix=*/"",
454 /*NewPrefix=*/"",
455 /*NativeObjectPrefix=*/"",
456 ShouldEmitImportsFiles: ThinLTOEmitImports,
457 /*LinkedObjectsFile=*/nullptr,
458 /*OnWrite=*/{});
459 else
460 Backend = createInProcessThinBackend(
461 Parallelism: llvm::heavyweight_hardware_concurrency(Num: Threads),
462 /* OnWrite */ {}, ShouldEmitIndexFiles: ThinLTOEmitIndexes, ShouldEmitImportsFiles: ThinLTOEmitImports);
463
464 // Track whether we hit an error; in particular, in the multi-threaded case,
465 // we can't exit() early because the rest of the threads wouldn't have had a
466 // change to be join-ed, and that would result in a "terminate called without
467 // an active exception". Altogether, this results in nondeterministic
468 // behavior. Instead, we don't exit in the multi-threaded case, but we make
469 // sure to report the error and then at the end (after joining cleanly)
470 // exit(1).
471 std::atomic<bool> HasErrors{false};
472 Conf.DiagHandler = [&](const DiagnosticInfo &DI) {
473 DiagnosticPrinterRawOStream DP(errs());
474 DI.print(DP);
475 errs() << '\n';
476 if (DI.getSeverity() == DS_Error)
477 HasErrors = true;
478 };
479
480 LTO::LTOKind LTOMode = UnifiedLTOMode;
481
482 std::unique_ptr<LTO> Lto;
483 if (!DTLTODistributor.empty()) {
484 Lto = std::make_unique<DTLTO>(
485 args: std::move(Conf), args: 1, args&: LTOMode, args: nullptr, args&: ThinLTOEmitIndexes,
486 args&: ThinLTOEmitImports, args&: OutputFilename, args&: DTLTODistributor,
487 args&: DTLTODistributorArgsSV, args&: DTLTOCompiler, args&: DTLTOCompilerPrependArgsSV,
488 args&: DTLTOCompilerArgsSV, args&: AddBuffer, args&: SaveTemps);
489 } else {
490 Lto =
491 std::make_unique<LTO>(args: std::move(Conf), args: std::move(Backend), args: 1, args&: LTOMode);
492 }
493
494 for (std::string F : InputFilenames) {
495 std::unique_ptr<MemoryBuffer> MB = check(E: MemoryBuffer::getFile(Filename: F), Msg: F);
496 std::unique_ptr<InputFile> Input =
497 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: F);
498
499 std::vector<SymbolResolution> Res;
500 for (const InputFile::Symbol &Sym : Input->symbols()) {
501 auto I = CommandLineResolutions.find(x: {F, std::string(Sym.getName())});
502 // If it isn't found, look for ".", which would have been added
503 // (followed by a hash) when the symbol was promoted during module
504 // splitting if it was defined in one part and used in the other.
505 // Try looking up the symbol name before the suffix.
506 if (I == CommandLineResolutions.end()) {
507 auto SplitName = Sym.getName().rsplit(Separator: ".");
508 I = CommandLineResolutions.find(x: {F, std::string(SplitName.first)});
509 }
510 if (I == CommandLineResolutions.end()) {
511 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
512 << ',' << Sym.getName() << '\n';
513 HasErrors = true;
514 } else {
515 Res.push_back(x: I->second.front());
516 I->second.pop_front();
517 if (I->second.empty())
518 CommandLineResolutions.erase(position: I);
519 }
520 }
521
522 if (HasErrors)
523 continue;
524
525 MBs.push_back(x: std::move(MB));
526 check(E: Lto->add(Obj: std::move(Input), Res), Msg: F);
527 }
528
529 if (!CommandLineResolutions.empty()) {
530 HasErrors = true;
531 for (auto UnusedRes : CommandLineResolutions)
532 llvm::errs() << argv[0] << ": unused symbol resolution for "
533 << UnusedRes.first.first << ',' << UnusedRes.first.second
534 << '\n';
535 }
536 if (HasErrors)
537 return 1;
538
539 Lto->setBitcodeLibFuncs(
540 SmallVector<StringRef>(BitcodeLibFuncs.begin(), BitcodeLibFuncs.end()));
541
542 FileCache Cache;
543 if (!CacheDir.empty())
544 Cache = check(E: localCache(CacheNameRef: "ThinLTO", TempFilePrefixRef: "Thin", CacheDirectoryPathRef: CacheDir, AddBuffer,
545 CacheFileRename: !DTLTODistributor.empty()),
546 Msg: "failed to create cache");
547
548 check(E: Lto->run(AddStream, Cache), Msg: "LTO::run failed");
549 Lto->waitForCleanup();
550 return static_cast<int>(HasErrors);
551}
552
553static int dumpSymtab(int argc, char **argv) {
554 for (StringRef F : make_range(x: argv + 1, y: argv + argc)) {
555 std::unique_ptr<MemoryBuffer> MB =
556 check(E: MemoryBuffer::getFile(Filename: F), Msg: std::string(F));
557 BitcodeFileContents BFC =
558 check(E: getBitcodeFileContents(Buffer: *MB), Msg: std::string(F));
559
560 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
561 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
562 BFC.Symtab.data());
563 outs() << "version: " << Hdr->Version << '\n';
564 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
565 outs() << "producer: " << Hdr->Producer.get(Strtab: BFC.StrtabForSymtab)
566 << '\n';
567 }
568
569 std::unique_ptr<InputFile> Input =
570 check(E: InputFile::create(Object: MB->getMemBufferRef()), Msg: std::string(F));
571
572 outs() << "target triple: " << Input->getTargetTriple() << '\n';
573 Triple TT(Input->getTargetTriple());
574
575 outs() << "source filename: " << Input->getSourceFileName() << '\n';
576
577 if (TT.isOSBinFormatCOFF())
578 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
579
580 if (TT.isOSBinFormatELF()) {
581 outs() << "dependent libraries:";
582 for (auto L : Input->getDependentLibraries())
583 outs() << " \"" << L << "\"";
584 outs() << '\n';
585 }
586
587 ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable =
588 Input->getComdatTable();
589 for (const InputFile::Symbol &Sym : Input->symbols()) {
590 switch (Sym.getVisibility()) {
591 case GlobalValue::HiddenVisibility:
592 outs() << 'H';
593 break;
594 case GlobalValue::ProtectedVisibility:
595 outs() << 'P';
596 break;
597 case GlobalValue::DefaultVisibility:
598 outs() << 'D';
599 break;
600 }
601
602 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
603 PrintBool('U', Sym.isUndefined());
604 PrintBool('C', Sym.isCommon());
605 PrintBool('W', Sym.isWeak());
606 PrintBool('I', Sym.isIndirect());
607 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
608 PrintBool('T', Sym.isTLS());
609 PrintBool('X', Sym.isExecutable());
610 outs() << ' ' << Sym.getName() << '\n';
611
612 if (Sym.isCommon())
613 outs() << " size " << Sym.getCommonSize() << " align "
614 << Sym.getCommonAlignment() << '\n';
615
616 int Comdat = Sym.getComdatIndex();
617 if (Comdat != -1) {
618 outs() << " comdat ";
619 switch (ComdatTable[Comdat].second) {
620 case Comdat::Any:
621 outs() << "any";
622 break;
623 case Comdat::ExactMatch:
624 outs() << "exactmatch";
625 break;
626 case Comdat::Largest:
627 outs() << "largest";
628 break;
629 case Comdat::NoDeduplicate:
630 outs() << "nodeduplicate";
631 break;
632 case Comdat::SameSize:
633 outs() << "samesize";
634 break;
635 }
636 outs() << ' ' << ComdatTable[Comdat].first << '\n';
637 }
638
639 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
640 outs() << " fallback " << Sym.getCOFFWeakExternalFallback()
641 << '\n';
642
643 if (!Sym.getSectionName().empty())
644 outs() << " section " << Sym.getSectionName() << "\n";
645 }
646
647 outs() << '\n';
648 }
649
650 return 0;
651}
652
653int main(int argc, char **argv) {
654 InitLLVM X(argc, argv);
655 InitializeAllTargets();
656 InitializeAllTargetMCs();
657 InitializeAllAsmPrinters();
658 InitializeAllAsmParsers();
659
660 // FIXME: This should use llvm::cl subcommands, but it isn't currently
661 // possible to pass an argument not associated with a subcommand to a
662 // subcommand (e.g. -use-new-pm).
663 if (argc < 2)
664 return usage();
665
666 StringRef Subcommand = argv[1];
667 // Ensure that argv[0] is correct after adjusting argv/argc.
668 argv[1] = argv[0];
669 if (Subcommand == "dump-symtab")
670 return dumpSymtab(argc: argc - 1, argv: argv + 1);
671 if (Subcommand == "run")
672 return run(argc: argc - 1, argv: argv + 1);
673 if (Subcommand == "print-guid" && argc > 2) {
674 // Note the name of the function we're calling: this won't return the right
675 // answer for internal linkage symbols.
676 outs() << GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: argv[2]) << '\n';
677 return 0;
678 }
679 if (Subcommand == "--version") {
680 cl::PrintVersionMessage();
681 return 0;
682 }
683 return usage();
684}
685