1 //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
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
7 //===----------------------------------------------------------------------===//
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.
13 // This program is intended to eventually replace llvm-lto which uses the legacy
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/CodeGen/CommandFlags.inc"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/LTO/Caching.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/InitLLVM.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/Threading.h"
33 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
35 cl::Prefix
, cl::ZeroOrMore
, cl::init('2'));
37 static cl::opt
<char> CGOptLevel(
39 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
42 static cl::list
<std::string
> InputFilenames(cl::Positional
, cl::OneOrMore
,
43 cl::desc("<input bitcode files>"));
45 static cl::opt
<std::string
> OutputFilename("o", cl::Required
,
46 cl::desc("Output filename"),
47 cl::value_desc("filename"));
49 static cl::opt
<std::string
> CacheDir("cache-dir", cl::desc("Cache Directory"),
50 cl::value_desc("directory"));
52 static cl::opt
<std::string
> OptPipeline("opt-pipeline",
53 cl::desc("Optimizer Pipeline"),
54 cl::value_desc("pipeline"));
56 static cl::opt
<std::string
> AAPipeline("aa-pipeline",
57 cl::desc("Alias Analysis Pipeline"),
58 cl::value_desc("aapipeline"));
60 static cl::opt
<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
63 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
64 cl::desc("Write out individual index and "
65 "import files for the "
66 "distributed backend case"));
68 static cl::opt
<int> Threads("thinlto-threads",
69 cl::init(llvm::heavyweight_hardware_concurrency()));
71 static cl::list
<std::string
> SymbolResolutions(
73 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
74 "where \"resolution\" is a sequence (which may be empty) of the\n"
75 "following characters:\n"
76 " p - prevailing: the linker has chosen this definition of the\n"
78 " l - local: the definition of this symbol is unpreemptable at\n"
79 " runtime and is known to be in this linkage unit\n"
80 " x - externally visible: the definition of this symbol is\n"
81 " visible outside of the LTO unit\n"
82 "A resolution for each symbol must be specified."),
85 static cl::opt
<std::string
> OverrideTriple(
87 cl::desc("Replace target triples in input files with this triple"));
89 static cl::opt
<std::string
> DefaultTriple(
92 "Replace unspecified target triples in input files with this triple"));
94 static cl::opt
<std::string
>
95 OptRemarksOutput("pass-remarks-output",
96 cl::desc("YAML output file for optimization remarks"));
98 static cl::opt
<bool> OptRemarksWithHotness(
99 "pass-remarks-with-hotness",
100 cl::desc("Whether to include hotness informations in the remarks.\n"
101 "Has effect only if -pass-remarks-output is specified."));
103 static cl::opt
<std::string
>
104 SamplePGOFile("lto-sample-profile-file",
105 cl::desc("Specify a SamplePGO profile file"));
108 UseNewPM("use-new-pm",
109 cl::desc("Run LTO passes using the new pass manager"),
110 cl::init(false), cl::Hidden
);
113 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden
,
114 cl::desc("Print pass management debugging information"));
116 static cl::opt
<std::string
>
117 StatsFile("stats-file", cl::desc("Filename to write statistics to"));
119 static void check(Error E
, std::string Msg
) {
122 handleAllErrors(std::move(E
), [&](ErrorInfoBase
&EIB
) {
123 errs() << "llvm-lto2: " << Msg
<< ": " << EIB
.message().c_str() << '\n';
128 template <typename T
> static T
check(Expected
<T
> E
, std::string Msg
) {
130 return std::move(*E
);
131 check(E
.takeError(), Msg
);
135 static void check(std::error_code EC
, std::string Msg
) {
136 check(errorCodeToError(EC
), Msg
);
139 template <typename T
> static T
check(ErrorOr
<T
> E
, std::string Msg
) {
141 return std::move(*E
);
142 check(E
.getError(), Msg
);
147 errs() << "Available subcommands: dump-symtab run\n";
151 static int run(int argc
, char **argv
) {
152 cl::ParseCommandLineOptions(argc
, argv
, "Resolution-based LTO test harness");
154 // FIXME: Workaround PR30396 which means that a symbol can appear
155 // more than once if it is defined in module-level assembly and
156 // has a GV declaration. We allow (file, symbol) pairs to have multiple
157 // resolutions and apply them in the order observed.
158 std::map
<std::pair
<std::string
, std::string
>, std::list
<SymbolResolution
>>
159 CommandLineResolutions
;
160 for (std::string R
: SymbolResolutions
) {
162 StringRef FileName
, SymbolName
;
163 std::tie(FileName
, Rest
) = Rest
.split(',');
165 llvm::errs() << "invalid resolution: " << R
<< '\n';
168 std::tie(SymbolName
, Rest
) = Rest
.split(',');
169 SymbolResolution Res
;
170 for (char C
: Rest
) {
172 Res
.Prevailing
= true;
174 Res
.FinalDefinitionInLinkageUnit
= true;
176 Res
.VisibleToRegularObj
= true;
178 Res
.LinkerRedefined
= true;
180 llvm::errs() << "invalid character " << C
<< " in resolution: " << R
185 CommandLineResolutions
[{FileName
, SymbolName
}].push_back(Res
);
188 std::vector
<std::unique_ptr
<MemoryBuffer
>> MBs
;
191 Conf
.DiagHandler
= [](const DiagnosticInfo
&DI
) {
192 DiagnosticPrinterRawOStream
DP(errs());
195 if (DI
.getSeverity() == DS_Error
)
200 Conf
.Options
= InitTargetOptionsFromCodeGenFlags();
201 Conf
.MAttrs
= MAttrs
;
202 if (auto RM
= getRelocModel())
203 Conf
.RelocModel
= *RM
;
204 Conf
.CodeModel
= getCodeModel();
206 Conf
.DebugPassManager
= DebugPassManager
;
209 check(Conf
.addSaveTemps(OutputFilename
+ "."),
210 "Config::addSaveTemps failed");
212 // Optimization remarks.
213 Conf
.RemarksFilename
= OptRemarksOutput
;
214 Conf
.RemarksWithHotness
= OptRemarksWithHotness
;
216 Conf
.SampleProfile
= SamplePGOFile
;
218 // Run a custom pipeline, if asked for.
219 Conf
.OptPipeline
= OptPipeline
;
220 Conf
.AAPipeline
= AAPipeline
;
222 Conf
.OptLevel
= OptLevel
- '0';
223 Conf
.UseNewPM
= UseNewPM
;
224 switch (CGOptLevel
) {
226 Conf
.CGOptLevel
= CodeGenOpt::None
;
229 Conf
.CGOptLevel
= CodeGenOpt::Less
;
232 Conf
.CGOptLevel
= CodeGenOpt::Default
;
235 Conf
.CGOptLevel
= CodeGenOpt::Aggressive
;
238 llvm::errs() << "invalid cg optimization level: " << CGOptLevel
<< '\n';
242 if (FileType
.getNumOccurrences())
243 Conf
.CGFileType
= FileType
;
245 Conf
.OverrideTriple
= OverrideTriple
;
246 Conf
.DefaultTriple
= DefaultTriple
;
247 Conf
.StatsFile
= StatsFile
;
250 if (ThinLTODistributedIndexes
)
251 Backend
= createWriteIndexesThinBackend(/* OldPrefix */ "",
253 /* ShouldEmitImportsFiles */ true,
254 /* LinkedObjectsFile */ nullptr,
257 Backend
= createInProcessThinBackend(Threads
);
258 LTO
Lto(std::move(Conf
), std::move(Backend
));
260 bool HasErrors
= false;
261 for (std::string F
: InputFilenames
) {
262 std::unique_ptr
<MemoryBuffer
> MB
= check(MemoryBuffer::getFile(F
), F
);
263 std::unique_ptr
<InputFile
> Input
=
264 check(InputFile::create(MB
->getMemBufferRef()), F
);
266 std::vector
<SymbolResolution
> Res
;
267 for (const InputFile::Symbol
&Sym
: Input
->symbols()) {
268 auto I
= CommandLineResolutions
.find({F
, Sym
.getName()});
269 if (I
== CommandLineResolutions
.end()) {
270 llvm::errs() << argv
[0] << ": missing symbol resolution for " << F
271 << ',' << Sym
.getName() << '\n';
274 Res
.push_back(I
->second
.front());
275 I
->second
.pop_front();
276 if (I
->second
.empty())
277 CommandLineResolutions
.erase(I
);
284 MBs
.push_back(std::move(MB
));
285 check(Lto
.add(std::move(Input
), Res
), F
);
288 if (!CommandLineResolutions
.empty()) {
290 for (auto UnusedRes
: CommandLineResolutions
)
291 llvm::errs() << argv
[0] << ": unused symbol resolution for "
292 << UnusedRes
.first
.first
<< ',' << UnusedRes
.first
.second
299 [&](size_t Task
) -> std::unique_ptr
<lto::NativeObjectStream
> {
300 std::string Path
= OutputFilename
+ "." + utostr(Task
);
303 auto S
= llvm::make_unique
<raw_fd_ostream
>(Path
, EC
, sys::fs::F_None
);
305 return llvm::make_unique
<lto::NativeObjectStream
>(std::move(S
));
308 auto AddBuffer
= [&](size_t Task
, std::unique_ptr
<MemoryBuffer
> MB
) {
309 *AddStream(Task
)->OS
<< MB
->getBuffer();
312 NativeObjectCache Cache
;
313 if (!CacheDir
.empty())
314 Cache
= check(localCache(CacheDir
, AddBuffer
), "failed to create cache");
316 check(Lto
.run(AddStream
, Cache
), "LTO::run failed");
320 static int dumpSymtab(int argc
, char **argv
) {
321 for (StringRef F
: make_range(argv
+ 1, argv
+ argc
)) {
322 std::unique_ptr
<MemoryBuffer
> MB
= check(MemoryBuffer::getFile(F
), F
);
323 BitcodeFileContents BFC
= check(getBitcodeFileContents(*MB
), F
);
325 if (BFC
.Symtab
.size() >= sizeof(irsymtab::storage::Header
)) {
326 auto *Hdr
= reinterpret_cast<const irsymtab::storage::Header
*>(
328 outs() << "version: " << Hdr
->Version
<< '\n';
329 if (Hdr
->Version
== irsymtab::storage::Header::kCurrentVersion
)
330 outs() << "producer: " << Hdr
->Producer
.get(BFC
.StrtabForSymtab
)
334 std::unique_ptr
<InputFile
> Input
=
335 check(InputFile::create(MB
->getMemBufferRef()), F
);
337 outs() << "target triple: " << Input
->getTargetTriple() << '\n';
338 Triple
TT(Input
->getTargetTriple());
340 outs() << "source filename: " << Input
->getSourceFileName() << '\n';
342 if (TT
.isOSBinFormatCOFF())
343 outs() << "linker opts: " << Input
->getCOFFLinkerOpts() << '\n';
345 std::vector
<StringRef
> ComdatTable
= Input
->getComdatTable();
346 for (const InputFile::Symbol
&Sym
: Input
->symbols()) {
347 switch (Sym
.getVisibility()) {
348 case GlobalValue::HiddenVisibility
:
351 case GlobalValue::ProtectedVisibility
:
354 case GlobalValue::DefaultVisibility
:
359 auto PrintBool
= [&](char C
, bool B
) { outs() << (B
? C
: '-'); };
360 PrintBool('U', Sym
.isUndefined());
361 PrintBool('C', Sym
.isCommon());
362 PrintBool('W', Sym
.isWeak());
363 PrintBool('I', Sym
.isIndirect());
364 PrintBool('O', Sym
.canBeOmittedFromSymbolTable());
365 PrintBool('T', Sym
.isTLS());
366 PrintBool('X', Sym
.isExecutable());
367 outs() << ' ' << Sym
.getName() << '\n';
370 outs() << " size " << Sym
.getCommonSize() << " align "
371 << Sym
.getCommonAlignment() << '\n';
373 int Comdat
= Sym
.getComdatIndex();
375 outs() << " comdat " << ComdatTable
[Comdat
] << '\n';
377 if (TT
.isOSBinFormatCOFF() && Sym
.isWeak() && Sym
.isIndirect())
378 outs() << " fallback " << Sym
.getCOFFWeakExternalFallback() << '\n';
380 if (!Sym
.getSectionName().empty())
381 outs() << " section " << Sym
.getSectionName() << "\n";
390 int main(int argc
, char **argv
) {
391 InitLLVM
X(argc
, argv
);
392 InitializeAllTargets();
393 InitializeAllTargetMCs();
394 InitializeAllAsmPrinters();
395 InitializeAllAsmParsers();
397 // FIXME: This should use llvm::cl subcommands, but it isn't currently
398 // possible to pass an argument not associated with a subcommand to a
399 // subcommand (e.g. -use-new-pm).
403 StringRef Subcommand
= argv
[1];
404 // Ensure that argv[0] is correct after adjusting argv/argc.
406 if (Subcommand
== "dump-symtab")
407 return dumpSymtab(argc
- 1, argv
+ 1);
408 if (Subcommand
== "run")
409 return run(argc
- 1, argv
+ 1);