blob: bff50aa2dc628f900ce43a0031e329d4c9dbbf5c [file] [log] [blame]
Teresa Johnson9ba95f92016-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
Mehdi Aminiadc0e262016-08-23 21:30:12 +000019#include "llvm/LTO/Caching.h"
Peter Collingbournef4257522016-12-08 05:28:30 +000020#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini14f19bd2016-12-23 23:54:17 +000021#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000022#include "llvm/LTO/LTO.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/TargetSelect.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000025#include "llvm/Support/Threading.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026
27using namespace llvm;
28using namespace lto;
29using namespace object;
30
Teresa Johnson002af9b2016-10-31 22:12:21 +000031static cl::opt<char>
32 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
33 "(default = '-O2')"),
34 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
35
Peter Collingbournef4257522016-12-08 05:28:30 +000036static cl::opt<char> CGOptLevel(
37 "cg-opt-level",
38 cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
39 cl::init('2'));
40
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
42 cl::desc("<input bitcode files>"));
43
44static cl::opt<std::string> OutputFilename("o", cl::Required,
45 cl::desc("Output filename"),
46 cl::value_desc("filename"));
47
Mehdi Aminiadc0e262016-08-23 21:30:12 +000048static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
49 cl::value_desc("directory"));
50
Davide Italianoec9612d2016-09-07 17:46:16 +000051static cl::opt<std::string> OptPipeline("opt-pipeline",
52 cl::desc("Optimizer Pipeline"),
53 cl::value_desc("pipeline"));
54
Davide Italiano14e9e8a2016-09-16 21:03:21 +000055static cl::opt<std::string> AAPipeline("aa-pipeline",
56 cl::desc("Alias Analysis Pipeline"),
57 cl::value_desc("aapipeline"));
58
Teresa Johnson9ba95f92016-08-11 14:58:12 +000059static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
60
Mehdi Amini458f8052016-08-19 23:54:40 +000061static cl::opt<bool>
62 ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
63 cl::desc("Write out individual index and "
64 "import files for the "
65 "distributed backend case"));
66
Mehdi Amini95c1f912016-12-23 23:54:34 +000067static cl::opt<int> Threads("thinlto-threads",
Teresa Johnsonec544c52016-10-19 17:35:01 +000068 cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini458f8052016-08-19 23:54:40 +000069
Teresa Johnson9ba95f92016-08-11 14:58:12 +000070static cl::list<std::string> SymbolResolutions(
71 "r",
72 cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
73 "where \"resolution\" is a sequence (which may be empty) of the\n"
74 "following characters:\n"
75 " p - prevailing: the linker has chosen this definition of the\n"
76 " symbol\n"
77 " l - local: the definition of this symbol is unpreemptable at\n"
78 " runtime and is known to be in this linkage unit\n"
79 " x - externally visible: the definition of this symbol is\n"
80 " visible outside of the LTO unit\n"
81 "A resolution for each symbol must be specified."),
82 cl::ZeroOrMore);
83
Peter Collingbournef4257522016-12-08 05:28:30 +000084static cl::opt<std::string> OverrideTriple(
85 "override-triple",
86 cl::desc("Replace target triples in input files with this triple"));
87
88static cl::opt<std::string> DefaultTriple(
89 "default-triple",
90 cl::desc(
91 "Replace unspecified target triples in input files with this triple"));
92
Davide Italianoebd47192017-02-12 03:31:30 +000093static cl::opt<std::string>
94 OptRemarksOutput("pass-remarks-output",
95 cl::desc("YAML output file for optimization remarks"));
96
Teresa Johnson9ba95f92016-08-11 14:58:12 +000097static void check(Error E, std::string Msg) {
98 if (!E)
99 return;
100 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
Davide Italianofb6ed912017-02-12 03:42:09 +0000101 errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102 });
103 exit(1);
104}
105
106template <typename T> static T check(Expected<T> E, std::string Msg) {
107 if (E)
108 return std::move(*E);
109 check(E.takeError(), Msg);
110 return T();
111}
112
113static void check(std::error_code EC, std::string Msg) {
114 check(errorCodeToError(EC), Msg);
115}
116
117template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
118 if (E)
119 return std::move(*E);
120 check(E.getError(), Msg);
121 return T();
122}
123
124int main(int argc, char **argv) {
125 InitializeAllTargets();
126 InitializeAllTargetMCs();
127 InitializeAllAsmPrinters();
128 InitializeAllAsmParsers();
129
130 cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
131
Peter Collingbournea5b71642016-11-30 23:19:05 +0000132 // FIXME: Workaround PR30396 which means that a symbol can appear
133 // more than once if it is defined in module-level assembly and
134 // has a GV declaration. We allow (file, symbol) pairs to have multiple
135 // resolutions and apply them in the order observed.
136 std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000137 CommandLineResolutions;
138 for (std::string R : SymbolResolutions) {
139 StringRef Rest = R;
140 StringRef FileName, SymbolName;
141 std::tie(FileName, Rest) = Rest.split(',');
142 if (Rest.empty()) {
143 llvm::errs() << "invalid resolution: " << R << '\n';
144 return 1;
145 }
146 std::tie(SymbolName, Rest) = Rest.split(',');
147 SymbolResolution Res;
148 for (char C : Rest) {
149 if (C == 'p')
150 Res.Prevailing = true;
151 else if (C == 'l')
152 Res.FinalDefinitionInLinkageUnit = true;
153 else if (C == 'x')
154 Res.VisibleToRegularObj = true;
155 else
156 llvm::errs() << "invalid character " << C << " in resolution: " << R
157 << '\n';
158 }
Peter Collingbournea5b71642016-11-30 23:19:05 +0000159 CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000160 }
161
162 std::vector<std::unique_ptr<MemoryBuffer>> MBs;
163
164 Config Conf;
Mehdi Amini14f19bd2016-12-23 23:54:17 +0000165 Conf.DiagHandler = [](const DiagnosticInfo &DI) {
166 DiagnosticPrinterRawOStream DP(errs());
167 DI.print(DP);
168 errs() << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000169 exit(1);
170 };
171
Peter Collingbournef4257522016-12-08 05:28:30 +0000172 Conf.CPU = MCPU;
173 Conf.Options = InitTargetOptionsFromCodeGenFlags();
174 Conf.MAttrs = MAttrs;
175 if (auto RM = getRelocModel())
176 Conf.RelocModel = *RM;
177 Conf.CodeModel = CMModel;
178
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000179 if (SaveTemps)
Mehdi Aminieccffad2016-08-18 00:12:33 +0000180 check(Conf.addSaveTemps(OutputFilename + "."),
181 "Config::addSaveTemps failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000182
Davide Italianoebd47192017-02-12 03:31:30 +0000183 // Optimization remarks.
184 Conf.RemarksFilename = OptRemarksOutput;
185
Davide Italianoec9612d2016-09-07 17:46:16 +0000186 // Run a custom pipeline, if asked for.
187 Conf.OptPipeline = OptPipeline;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000188 Conf.AAPipeline = AAPipeline;
Davide Italianoec9612d2016-09-07 17:46:16 +0000189
Teresa Johnson002af9b2016-10-31 22:12:21 +0000190 Conf.OptLevel = OptLevel - '0';
Peter Collingbournef4257522016-12-08 05:28:30 +0000191 switch (CGOptLevel) {
192 case '0':
193 Conf.CGOptLevel = CodeGenOpt::None;
194 break;
195 case '1':
196 Conf.CGOptLevel = CodeGenOpt::Less;
197 break;
198 case '2':
199 Conf.CGOptLevel = CodeGenOpt::Default;
200 break;
201 case '3':
202 Conf.CGOptLevel = CodeGenOpt::Aggressive;
203 break;
204 default:
205 llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
206 return 1;
207 }
208
209 Conf.OverrideTriple = OverrideTriple;
210 Conf.DefaultTriple = DefaultTriple;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000211
Mehdi Amini458f8052016-08-19 23:54:40 +0000212 ThinBackend Backend;
213 if (ThinLTODistributedIndexes)
214 Backend = createWriteIndexesThinBackend("", "", true, "");
215 else
216 Backend = createInProcessThinBackend(Threads);
217 LTO Lto(std::move(Conf), std::move(Backend));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000218
219 bool HasErrors = false;
220 for (std::string F : InputFilenames) {
221 std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
222 std::unique_ptr<InputFile> Input =
223 check(InputFile::create(MB->getMemBufferRef()), F);
224
225 std::vector<SymbolResolution> Res;
226 for (const InputFile::Symbol &Sym : Input->symbols()) {
227 auto I = CommandLineResolutions.find({F, Sym.getName()});
228 if (I == CommandLineResolutions.end()) {
229 llvm::errs() << argv[0] << ": missing symbol resolution for " << F
230 << ',' << Sym.getName() << '\n';
231 HasErrors = true;
232 } else {
Peter Collingbournea5b71642016-11-30 23:19:05 +0000233 Res.push_back(I->second.front());
234 I->second.pop_front();
235 if (I->second.empty())
236 CommandLineResolutions.erase(I);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237 }
238 }
239
240 if (HasErrors)
241 continue;
242
243 MBs.push_back(std::move(MB));
244 check(Lto.add(std::move(Input), Res), F);
245 }
246
247 if (!CommandLineResolutions.empty()) {
248 HasErrors = true;
249 for (auto UnusedRes : CommandLineResolutions)
250 llvm::errs() << argv[0] << ": unused symbol resolution for "
251 << UnusedRes.first.first << ',' << UnusedRes.first.second
252 << '\n';
253 }
254 if (HasErrors)
255 return 1;
256
Peter Collingbourne80186a52016-09-23 21:33:43 +0000257 auto AddStream =
258 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000259 std::string Path = OutputFilename + "." + utostr(Task);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000260
Peter Collingbourne80186a52016-09-23 21:33:43 +0000261 std::error_code EC;
262 auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
263 check(EC, Path);
264 return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000265 };
266
Peter Collingbourne80186a52016-09-23 21:33:43 +0000267 auto AddFile = [&](size_t Task, StringRef Path) {
268 auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path);
269 if (auto EC = ReloadedBufferOrErr.getError())
270 report_fatal_error(Twine("Can't reload cached file '") + Path + "': " +
271 EC.message() + "\n");
272
273 *AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer();
274 };
275
276 NativeObjectCache Cache;
277 if (!CacheDir.empty())
278 Cache = localCache(CacheDir, AddFile);
279
280 check(Lto.run(AddStream, Cache), "LTO::run failed");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000281}