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