blob: 26426367e252ed4a8650bada41ed90109a098e3e [file] [log] [blame]
Teresa Johnson2d320e52016-08-11 14:58:12 +00001//===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program takes in a list of bitcode files, links them and performs
11// link-time optimization according to the provided symbol resolutions using the
12// resolution-based LTO interface, and outputs one or more object files.
13//
14// This program is intended to eventually replace llvm-lto which uses the legacy
15// LTO interface.
16//
17//===----------------------------------------------------------------------===//
18
Peter Collingbournea4799ad2017-06-27 23:50:24 +000019#include "llvm/Bitcode/BitcodeReader.h"
David Blaikie461bf522018-04-11 18:49:37 +000020#include "llvm/CodeGen/CommandFlags.inc"
Mehdi Aminide4b9a32016-12-23 23:54:17 +000021#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournea4799ad2017-06-27 23:50:24 +000022#include "llvm/LTO/Caching.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000023#include "llvm/LTO/LTO.h"
24#include "llvm/Support/CommandLine.h"
Peter Collingbourne14ecedf2017-03-28 23:35:34 +000025#include "llvm/Support/FileSystem.h"
Teresa Johnsondb949a72018-10-16 17:37:45 +000026#include "llvm/Support/InitLLVM.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000027#include "llvm/Support/TargetSelect.h"
Teresa Johnson740d8712016-10-19 17:35:01 +000028#include "llvm/Support/Threading.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000029
30using namespace llvm;
31using namespace lto;
Teresa Johnson2d320e52016-08-11 14:58:12 +000032
Teresa Johnson485ef162016-10-31 22:12:21 +000033static cl::opt<char>
34 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
35 "(default = '-O2')"),
36 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
37
Peter Collingbourne8bb25c42016-12-08 05:28:30 +000038static cl::opt<char> CGOptLevel(
39 "cg-opt-level",
40 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
41 cl::init('2'));
42
Teresa Johnson2d320e52016-08-11 14:58:12 +000043static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44 cl::desc("<input bitcode files>"));
45
46static cl::opt<std::string> OutputFilename("o", cl::Required,
47 cl::desc("Output filename"),
48 cl::value_desc("filename"));
49
Mehdi Amini242275b2016-08-23 21:30:12 +000050static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
51 cl::value_desc("directory"));
52
Davide Italianofab897d2016-09-07 17:46:16 +000053static cl::opt<std::string> OptPipeline("opt-pipeline",
54 cl::desc("Optimizer Pipeline"),
55 cl::value_desc("pipeline"));
56
Davide Italiano463cfe42016-09-16 21:03:21 +000057static cl::opt<std::string> AAPipeline("aa-pipeline",
58 cl::desc("Alias Analysis Pipeline"),
59 cl::value_desc("aapipeline"));
60
Teresa Johnson2d320e52016-08-11 14:58:12 +000061static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
62
Mehdi Aminicb9042a2016-08-19 23:54:40 +000063static cl::opt<bool>
64 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
65 cl::desc("Write out individual index and "
66 "import files for the "
67 "distributed backend case"));
68
Mehdi Aminiec1ef032016-12-23 23:54:34 +000069static cl::opt<int> Threads("thinlto-threads",
Teresa Johnson740d8712016-10-19 17:35:01 +000070 cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Aminicb9042a2016-08-19 23:54:40 +000071
Teresa Johnson2d320e52016-08-11 14:58:12 +000072static cl::list<std::string> SymbolResolutions(
73 "r",
74 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
75 "where \"resolution\" is a sequence (which may be empty) of the\n"
76 "following characters:\n"
77 " p - prevailing: the linker has chosen this definition of the\n"
78 " symbol\n"
79 " l - local: the definition of this symbol is unpreemptable at\n"
80 " runtime and is known to be in this linkage unit\n"
81 " x - externally visible: the definition of this symbol is\n"
82 " visible outside of the LTO unit\n"
83 "A resolution for each symbol must be specified."),
84 cl::ZeroOrMore);
85
Peter Collingbourne8bb25c42016-12-08 05:28:30 +000086static cl::opt<std::string> OverrideTriple(
87 "override-triple",
88 cl::desc("Replace target triples in input files with this triple"));
89
90static cl::opt<std::string> DefaultTriple(
91 "default-triple",
92 cl::desc(
93 "Replace unspecified target triples in input files with this triple"));
94
Davide Italiano9c7400c2017-02-12 03:31:30 +000095static cl::opt<std::string>
96 OptRemarksOutput("pass-remarks-output",
97 cl::desc("YAML output file for optimization remarks"));
98
Davide Italiano3a0219a2017-02-13 16:08:36 +000099static cl::opt<bool> OptRemarksWithHotness(
Davide Italiano820dc662017-02-12 05:05:35 +0000100 "pass-remarks-with-hotness",
101 cl::desc("Whether to include hotness informations in the remarks.\n"
102 "Has effect only if -pass-remarks-output is specified."));
103
Tobias Edler von Kochc99ec632017-07-28 23:43:22 +0000104static cl::opt<std::string>
105 SamplePGOFile("lto-sample-profile-file",
106 cl::desc("Specify a SamplePGO profile file"));
107
Tim Shena950eb92017-06-01 23:13:44 +0000108static cl::opt<bool>
109 UseNewPM("use-new-pm",
110 cl::desc("Run LTO passes using the new pass manager"),
111 cl::init(false), cl::Hidden);
112
Dehao Chenb929c3e2017-08-02 03:03:19 +0000113static cl::opt<bool>
114 DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
115 cl::desc("Print pass management debugging information"));
116
Florian Hahna2fbfc92018-04-20 10:18:36 +0000117static cl::opt<std::string>
118 StatsFile("stats-file", cl::desc("Filename to write statistics to"));
119
Teresa Johnson2d320e52016-08-11 14:58:12 +0000120static void check(Error E, std::string Msg) {
121 if (!E)
122 return;
123 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
Davide Italiano92346962017-02-12 03:42:09 +0000124 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
Teresa Johnson2d320e52016-08-11 14:58:12 +0000125 });
126 exit(1);
127}
128
129template <typename T> static T check(Expected<T> E, std::string Msg) {
130 if (E)
131 return std::move(*E);
132 check(E.takeError(), Msg);
133 return T();
134}
135
136static void check(std::error_code EC, std::string Msg) {
137 check(errorCodeToError(EC), Msg);
138}
139
140template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
141 if (E)
142 return std::move(*E);
143 check(E.getError(), Msg);
144 return T();
145}
146
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000147static int usage() {
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000148 errs() << "Available subcommands: dump-symtab run\n";
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000149 return 1;
150}
Teresa Johnson2d320e52016-08-11 14:58:12 +0000151
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000152static int run(int argc, char **argv) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000153 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
154
Peter Collingbourne5c1bc632016-11-30 23:19:05 +0000155 // FIXME: Workaround PR30396 which means that a symbol can appear
156 // more than once if it is defined in module-level assembly and
157 // has a GV declaration. We allow (file, symbol) pairs to have multiple
158 // resolutions and apply them in the order observed.
159 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson2d320e52016-08-11 14:58:12 +0000160 CommandLineResolutions;
161 for (std::string R : SymbolResolutions) {
162 StringRef Rest = R;
163 StringRef FileName, SymbolName;
164 std::tie(FileName, Rest) = Rest.split(',');
165 if (Rest.empty()) {
166 llvm::errs() << "invalid resolution: " << R << '\n';
167 return 1;
168 }
169 std::tie(SymbolName, Rest) = Rest.split(',');
170 SymbolResolution Res;
171 for (char C : Rest) {
172 if (C == 'p')
173 Res.Prevailing = true;
174 else if (C == 'l')
175 Res.FinalDefinitionInLinkageUnit = true;
176 else if (C == 'x')
177 Res.VisibleToRegularObj = true;
Dmitry Mikulin75fb58c2017-06-05 16:24:25 +0000178 else if (C == 'r')
179 Res.LinkerRedefined = true;
Teresa Johnson67cf6a42017-03-07 18:15:13 +0000180 else {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000181 llvm::errs() << "invalid character " << C << " in resolution: " << R
182 << '\n';
Teresa Johnson67cf6a42017-03-07 18:15:13 +0000183 return 1;
184 }
Teresa Johnson2d320e52016-08-11 14:58:12 +0000185 }
Peter Collingbourne5c1bc632016-11-30 23:19:05 +0000186 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000187 }
188
189 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
190
191 Config Conf;
Mehdi Aminide4b9a32016-12-23 23:54:17 +0000192 Conf.DiagHandler = [](const DiagnosticInfo &DI) {
193 DiagnosticPrinterRawOStream DP(errs());
194 DI.print(DP);
195 errs() << '\n';
Teresa Johnson61d9a692018-05-04 23:59:34 +0000196 if (DI.getSeverity() == DS_Error)
197 exit(1);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000198 };
199
Peter Collingbourne8bb25c42016-12-08 05:28:30 +0000200 Conf.CPU = MCPU;
201 Conf.Options = InitTargetOptionsFromCodeGenFlags();
202 Conf.MAttrs = MAttrs;
203 if (auto RM = getRelocModel())
204 Conf.RelocModel = *RM;
Rafael Espindola9aafb852017-08-03 02:16:21 +0000205 Conf.CodeModel = getCodeModel();
Peter Collingbourne8bb25c42016-12-08 05:28:30 +0000206
Dehao Chenb929c3e2017-08-02 03:03:19 +0000207 Conf.DebugPassManager = DebugPassManager;
208
Teresa Johnson2d320e52016-08-11 14:58:12 +0000209 if (SaveTemps)
Mehdi Aminia53e50c2016-08-18 00:12:33 +0000210 check(Conf.addSaveTemps(OutputFilename + "."),
211 "Config::addSaveTemps failed");
Teresa Johnson2d320e52016-08-11 14:58:12 +0000212
Davide Italiano9c7400c2017-02-12 03:31:30 +0000213 // Optimization remarks.
214 Conf.RemarksFilename = OptRemarksOutput;
Davide Italiano3a0219a2017-02-13 16:08:36 +0000215 Conf.RemarksWithHotness = OptRemarksWithHotness;
Davide Italiano9c7400c2017-02-12 03:31:30 +0000216
Tobias Edler von Kochc99ec632017-07-28 23:43:22 +0000217 Conf.SampleProfile = SamplePGOFile;
218
Davide Italianofab897d2016-09-07 17:46:16 +0000219 // Run a custom pipeline, if asked for.
220 Conf.OptPipeline = OptPipeline;
Davide Italiano463cfe42016-09-16 21:03:21 +0000221 Conf.AAPipeline = AAPipeline;
Davide Italianofab897d2016-09-07 17:46:16 +0000222
Teresa Johnson485ef162016-10-31 22:12:21 +0000223 Conf.OptLevel = OptLevel - '0';
Tim Shena950eb92017-06-01 23:13:44 +0000224 Conf.UseNewPM = UseNewPM;
Peter Collingbourne8bb25c42016-12-08 05:28:30 +0000225 switch (CGOptLevel) {
226 case '0':
227 Conf.CGOptLevel = CodeGenOpt::None;
228 break;
229 case '1':
230 Conf.CGOptLevel = CodeGenOpt::Less;
231 break;
232 case '2':
233 Conf.CGOptLevel = CodeGenOpt::Default;
234 break;
235 case '3':
236 Conf.CGOptLevel = CodeGenOpt::Aggressive;
237 break;
238 default:
239 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
240 return 1;
241 }
242
Tobias Edler von Koch01c2fde2017-02-15 20:36:36 +0000243 if (FileType.getNumOccurrences())
244 Conf.CGFileType = FileType;
245
Peter Collingbourne8bb25c42016-12-08 05:28:30 +0000246 Conf.OverrideTriple = OverrideTriple;
247 Conf.DefaultTriple = DefaultTriple;
Florian Hahna2fbfc92018-04-20 10:18:36 +0000248 Conf.StatsFile = StatsFile;
Teresa Johnson485ef162016-10-31 22:12:21 +0000249
Mehdi Aminicb9042a2016-08-19 23:54:40 +0000250 ThinBackend Backend;
251 if (ThinLTODistributedIndexes)
Vitaly Buka55523de2018-02-22 19:06:15 +0000252 Backend = createWriteIndexesThinBackend(/* OldPrefix */ "",
253 /* NewPrefix */ "",
254 /* ShouldEmitImportsFiles */ true,
255 /* LinkedObjectsFile */ nullptr,
256 /* OnWrite */ {});
Mehdi Aminicb9042a2016-08-19 23:54:40 +0000257 else
258 Backend = createInProcessThinBackend(Threads);
259 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000260
261 bool HasErrors = false;
262 for (std::string F : InputFilenames) {
263 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
264 std::unique_ptr<InputFile> Input =
265 check(InputFile::create(MB->getMemBufferRef()), F);
266
267 std::vector<SymbolResolution> Res;
268 for (const InputFile::Symbol &Sym : Input->symbols()) {
269 auto I = CommandLineResolutions.find({F, Sym.getName()});
270 if (I == CommandLineResolutions.end()) {
271 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
272 << ',' << Sym.getName() << '\n';
273 HasErrors = true;
274 } else {
Peter Collingbourne5c1bc632016-11-30 23:19:05 +0000275 Res.push_back(I->second.front());
276 I->second.pop_front();
277 if (I->second.empty())
278 CommandLineResolutions.erase(I);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000279 }
280 }
281
282 if (HasErrors)
283 continue;
284
285 MBs.push_back(std::move(MB));
286 check(Lto.add(std::move(Input), Res), F);
287 }
288
289 if (!CommandLineResolutions.empty()) {
290 HasErrors = true;
291 for (auto UnusedRes : CommandLineResolutions)
292 llvm::errs() << argv[0] << ": unused symbol resolution for "
293 << UnusedRes.first.first << ',' << UnusedRes.first.second
294 << '\n';
295 }
296 if (HasErrors)
297 return 1;
298
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000299 auto AddStream =
300 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000301 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Amini242275b2016-08-23 21:30:12 +0000302
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000303 std::error_code EC;
304 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
305 check(EC, Path);
306 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000307 };
308
Teresa Johnson761281e2018-02-20 20:21:53 +0000309 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Peter Collingbourneec179d72017-03-17 00:34:07 +0000310 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000311 };
312
313 NativeObjectCache Cache;
314 if (!CacheDir.empty())
Peter Collingbourneec179d72017-03-17 00:34:07 +0000315 Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000316
317 check(Lto.run(AddStream, Cache), "LTO::run failed");
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000318 return 0;
319}
320
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000321static int dumpSymtab(int argc, char **argv) {
322 for (StringRef F : make_range(argv + 1, argv + argc)) {
323 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
Peter Collingbournea4799ad2017-06-27 23:50:24 +0000324 BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F);
325
326 if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
327 auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
328 BFC.Symtab.data());
329 outs() << "version: " << Hdr->Version << '\n';
330 if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
331 outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
332 << '\n';
333 }
334
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000335 std::unique_ptr<InputFile> Input =
336 check(InputFile::create(MB->getMemBufferRef()), F);
337
Peter Collingbournea9b9e012017-04-14 02:55:06 +0000338 outs() << "target triple: " << Input->getTargetTriple() << '\n';
339 Triple TT(Input->getTargetTriple());
340
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000341 outs() << "source filename: " << Input->getSourceFileName() << '\n';
Peter Collingbournea9b9e012017-04-14 02:55:06 +0000342
343 if (TT.isOSBinFormatCOFF())
344 outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000345
346 std::vector<StringRef> ComdatTable = Input->getComdatTable();
347 for (const InputFile::Symbol &Sym : Input->symbols()) {
348 switch (Sym.getVisibility()) {
349 case GlobalValue::HiddenVisibility:
350 outs() << 'H';
351 break;
352 case GlobalValue::ProtectedVisibility:
353 outs() << 'P';
354 break;
355 case GlobalValue::DefaultVisibility:
356 outs() << 'D';
357 break;
358 }
359
360 auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
361 PrintBool('U', Sym.isUndefined());
362 PrintBool('C', Sym.isCommon());
363 PrintBool('W', Sym.isWeak());
364 PrintBool('I', Sym.isIndirect());
365 PrintBool('O', Sym.canBeOmittedFromSymbolTable());
366 PrintBool('T', Sym.isTLS());
Tobias Edler von Koch7f80f1b2017-04-13 16:24:14 +0000367 PrintBool('X', Sym.isExecutable());
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000368 outs() << ' ' << Sym.getName() << '\n';
369
370 if (Sym.isCommon())
Tobias Edler von Koch7f80f1b2017-04-13 16:24:14 +0000371 outs() << " size " << Sym.getCommonSize() << " align "
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000372 << Sym.getCommonAlignment() << '\n';
373
374 int Comdat = Sym.getComdatIndex();
375 if (Comdat != -1)
Tobias Edler von Koch7f80f1b2017-04-13 16:24:14 +0000376 outs() << " comdat " << ComdatTable[Comdat] << '\n';
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000377
Peter Collingbournea9b9e012017-04-14 02:55:06 +0000378 if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
Tobias Edler von Koch7f80f1b2017-04-13 16:24:14 +0000379 outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
Teresa Johnsona63ab3c92017-07-25 19:42:32 +0000380
381 if (!Sym.getSectionName().empty())
382 outs() << " section " << Sym.getSectionName() << "\n";
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000383 }
384
385 outs() << '\n';
386 }
387
388 return 0;
389}
390
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000391int main(int argc, char **argv) {
Teresa Johnsondb949a72018-10-16 17:37:45 +0000392 InitLLVM X(argc, argv);
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000393 InitializeAllTargets();
394 InitializeAllTargetMCs();
395 InitializeAllAsmPrinters();
396 InitializeAllAsmParsers();
397
398 // FIXME: This should use llvm::cl subcommands, but it isn't currently
399 // possible to pass an argument not associated with a subcommand to a
Tim Shena950eb92017-06-01 23:13:44 +0000400 // subcommand (e.g. -use-new-pm).
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000401 if (argc < 2)
402 return usage();
403
404 StringRef Subcommand = argv[1];
405 // Ensure that argv[0] is correct after adjusting argv/argc.
406 argv[1] = argv[0];
Peter Collingbourne1c404b42017-04-12 18:27:00 +0000407 if (Subcommand == "dump-symtab")
408 return dumpSymtab(argc - 1, argv + 1);
Peter Collingbournebe0ad752017-04-11 18:12:00 +0000409 if (Subcommand == "run")
410 return run(argc - 1, argv + 1);
411 return usage();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000412}