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