]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-lto2/llvm-lto2.cpp
MFV r329770: 9035 zfs: this statement may fall through
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-lto2 / llvm-lto2.cpp
1 //===-- 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
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/CodeGen/CommandFlags.def"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/LTO/Caching.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/Threading.h"
28
29 using namespace llvm;
30 using namespace lto;
31
32 static cl::opt<char>
33     OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
34                            "(default = '-O2')"),
35              cl::Prefix, cl::ZeroOrMore, cl::init('2'));
36
37 static cl::opt<char> CGOptLevel(
38     "cg-opt-level",
39     cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
40     cl::init('2'));
41
42 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
43                                             cl::desc("<input bitcode files>"));
44
45 static cl::opt<std::string> OutputFilename("o", cl::Required,
46                                            cl::desc("Output filename"),
47                                            cl::value_desc("filename"));
48
49 static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
50                                      cl::value_desc("directory"));
51
52 static cl::opt<std::string> OptPipeline("opt-pipeline",
53                                         cl::desc("Optimizer Pipeline"),
54                                         cl::value_desc("pipeline"));
55
56 static cl::opt<std::string> AAPipeline("aa-pipeline",
57                                        cl::desc("Alias Analysis Pipeline"),
58                                        cl::value_desc("aapipeline"));
59
60 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
61
62 static cl::opt<bool>
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"));
67
68 static cl::opt<int> Threads("thinlto-threads",
69                             cl::init(llvm::heavyweight_hardware_concurrency()));
70
71 static cl::list<std::string> SymbolResolutions(
72     "r",
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"
77              "     symbol\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."),
83     cl::ZeroOrMore);
84
85 static cl::opt<std::string> OverrideTriple(
86     "override-triple",
87     cl::desc("Replace target triples in input files with this triple"));
88
89 static cl::opt<std::string> DefaultTriple(
90     "default-triple",
91     cl::desc(
92         "Replace unspecified target triples in input files with this triple"));
93
94 static cl::opt<std::string>
95     OptRemarksOutput("pass-remarks-output",
96                      cl::desc("YAML output file for optimization remarks"));
97
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."));
102
103 static cl::opt<std::string>
104     SamplePGOFile("lto-sample-profile-file",
105                   cl::desc("Specify a SamplePGO profile file"));
106
107 static cl::opt<bool>
108     UseNewPM("use-new-pm",
109              cl::desc("Run LTO passes using the new pass manager"),
110              cl::init(false), cl::Hidden);
111
112 static cl::opt<bool>
113     DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
114                      cl::desc("Print pass management debugging information"));
115
116 static void check(Error E, std::string Msg) {
117   if (!E)
118     return;
119   handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
120     errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
121   });
122   exit(1);
123 }
124
125 template <typename T> static T check(Expected<T> E, std::string Msg) {
126   if (E)
127     return std::move(*E);
128   check(E.takeError(), Msg);
129   return T();
130 }
131
132 static void check(std::error_code EC, std::string Msg) {
133   check(errorCodeToError(EC), Msg);
134 }
135
136 template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
137   if (E)
138     return std::move(*E);
139   check(E.getError(), Msg);
140   return T();
141 }
142
143 static int usage() {
144   errs() << "Available subcommands: dump-symtab run\n";
145   return 1;
146 }
147
148 static int run(int argc, char **argv) {
149   cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
150
151   // FIXME: Workaround PR30396 which means that a symbol can appear
152   // more than once if it is defined in module-level assembly and
153   // has a GV declaration. We allow (file, symbol) pairs to have multiple
154   // resolutions and apply them in the order observed.
155   std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
156       CommandLineResolutions;
157   for (std::string R : SymbolResolutions) {
158     StringRef Rest = R;
159     StringRef FileName, SymbolName;
160     std::tie(FileName, Rest) = Rest.split(',');
161     if (Rest.empty()) {
162       llvm::errs() << "invalid resolution: " << R << '\n';
163       return 1;
164     }
165     std::tie(SymbolName, Rest) = Rest.split(',');
166     SymbolResolution Res;
167     for (char C : Rest) {
168       if (C == 'p')
169         Res.Prevailing = true;
170       else if (C == 'l')
171         Res.FinalDefinitionInLinkageUnit = true;
172       else if (C == 'x')
173         Res.VisibleToRegularObj = true;
174       else if (C == 'r')
175         Res.LinkerRedefined = true;
176       else {
177         llvm::errs() << "invalid character " << C << " in resolution: " << R
178                      << '\n';
179         return 1;
180       }
181     }
182     CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
183   }
184
185   std::vector<std::unique_ptr<MemoryBuffer>> MBs;
186
187   Config Conf;
188   Conf.DiagHandler = [](const DiagnosticInfo &DI) {
189     DiagnosticPrinterRawOStream DP(errs());
190     DI.print(DP);
191     errs() << '\n';
192     exit(1);
193   };
194
195   Conf.CPU = MCPU;
196   Conf.Options = InitTargetOptionsFromCodeGenFlags();
197   Conf.MAttrs = MAttrs;
198   if (auto RM = getRelocModel())
199     Conf.RelocModel = *RM;
200   Conf.CodeModel = getCodeModel();
201
202   Conf.DebugPassManager = DebugPassManager;
203
204   if (SaveTemps)
205     check(Conf.addSaveTemps(OutputFilename + "."),
206           "Config::addSaveTemps failed");
207
208   // Optimization remarks.
209   Conf.RemarksFilename = OptRemarksOutput;
210   Conf.RemarksWithHotness = OptRemarksWithHotness;
211
212   Conf.SampleProfile = SamplePGOFile;
213
214   // Run a custom pipeline, if asked for.
215   Conf.OptPipeline = OptPipeline;
216   Conf.AAPipeline = AAPipeline;
217
218   Conf.OptLevel = OptLevel - '0';
219   Conf.UseNewPM = UseNewPM;
220   switch (CGOptLevel) {
221   case '0':
222     Conf.CGOptLevel = CodeGenOpt::None;
223     break;
224   case '1':
225     Conf.CGOptLevel = CodeGenOpt::Less;
226     break;
227   case '2':
228     Conf.CGOptLevel = CodeGenOpt::Default;
229     break;
230   case '3':
231     Conf.CGOptLevel = CodeGenOpt::Aggressive;
232     break;
233   default:
234     llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
235     return 1;
236   }
237
238   if (FileType.getNumOccurrences())
239     Conf.CGFileType = FileType;
240
241   Conf.OverrideTriple = OverrideTriple;
242   Conf.DefaultTriple = DefaultTriple;
243
244   ThinBackend Backend;
245   if (ThinLTODistributedIndexes)
246     Backend = createWriteIndexesThinBackend("", "", true, "");
247   else
248     Backend = createInProcessThinBackend(Threads);
249   LTO Lto(std::move(Conf), std::move(Backend));
250
251   bool HasErrors = false;
252   for (std::string F : InputFilenames) {
253     std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
254     std::unique_ptr<InputFile> Input =
255         check(InputFile::create(MB->getMemBufferRef()), F);
256
257     std::vector<SymbolResolution> Res;
258     for (const InputFile::Symbol &Sym : Input->symbols()) {
259       auto I = CommandLineResolutions.find({F, Sym.getName()});
260       if (I == CommandLineResolutions.end()) {
261         llvm::errs() << argv[0] << ": missing symbol resolution for " << F
262                      << ',' << Sym.getName() << '\n';
263         HasErrors = true;
264       } else {
265         Res.push_back(I->second.front());
266         I->second.pop_front();
267         if (I->second.empty())
268           CommandLineResolutions.erase(I);
269       }
270     }
271
272     if (HasErrors)
273       continue;
274
275     MBs.push_back(std::move(MB));
276     check(Lto.add(std::move(Input), Res), F);
277   }
278
279   if (!CommandLineResolutions.empty()) {
280     HasErrors = true;
281     for (auto UnusedRes : CommandLineResolutions)
282       llvm::errs() << argv[0] << ": unused symbol resolution for "
283                    << UnusedRes.first.first << ',' << UnusedRes.first.second
284                    << '\n';
285   }
286   if (HasErrors)
287     return 1;
288
289   auto AddStream =
290       [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
291     std::string Path = OutputFilename + "." + utostr(Task);
292
293     std::error_code EC;
294     auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
295     check(EC, Path);
296     return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
297   };
298
299   auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB,
300                        StringRef Path) {
301     *AddStream(Task)->OS << MB->getBuffer();
302   };
303
304   NativeObjectCache Cache;
305   if (!CacheDir.empty())
306     Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
307
308   check(Lto.run(AddStream, Cache), "LTO::run failed");
309   return 0;
310 }
311
312 static int dumpSymtab(int argc, char **argv) {
313   for (StringRef F : make_range(argv + 1, argv + argc)) {
314     std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
315     BitcodeFileContents BFC = check(getBitcodeFileContents(*MB), F);
316
317     if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
318       auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
319           BFC.Symtab.data());
320       outs() << "version: " << Hdr->Version << '\n';
321       if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
322         outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
323                << '\n';
324     }
325
326     std::unique_ptr<InputFile> Input =
327         check(InputFile::create(MB->getMemBufferRef()), F);
328
329     outs() << "target triple: " << Input->getTargetTriple() << '\n';
330     Triple TT(Input->getTargetTriple());
331
332     outs() << "source filename: " << Input->getSourceFileName() << '\n';
333
334     if (TT.isOSBinFormatCOFF())
335       outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
336
337     std::vector<StringRef> ComdatTable = Input->getComdatTable();
338     for (const InputFile::Symbol &Sym : Input->symbols()) {
339       switch (Sym.getVisibility()) {
340       case GlobalValue::HiddenVisibility:
341         outs() << 'H';
342         break;
343       case GlobalValue::ProtectedVisibility:
344         outs() << 'P';
345         break;
346       case GlobalValue::DefaultVisibility:
347         outs() << 'D';
348         break;
349       }
350
351       auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
352       PrintBool('U', Sym.isUndefined());
353       PrintBool('C', Sym.isCommon());
354       PrintBool('W', Sym.isWeak());
355       PrintBool('I', Sym.isIndirect());
356       PrintBool('O', Sym.canBeOmittedFromSymbolTable());
357       PrintBool('T', Sym.isTLS());
358       PrintBool('X', Sym.isExecutable());
359       outs() << ' ' << Sym.getName() << '\n';
360
361       if (Sym.isCommon())
362         outs() << "         size " << Sym.getCommonSize() << " align "
363                << Sym.getCommonAlignment() << '\n';
364
365       int Comdat = Sym.getComdatIndex();
366       if (Comdat != -1)
367         outs() << "         comdat " << ComdatTable[Comdat] << '\n';
368
369       if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
370         outs() << "         fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
371
372       if (!Sym.getSectionName().empty())
373         outs() << "         section " << Sym.getSectionName() << "\n";
374     }
375
376     outs() << '\n';
377   }
378
379   return 0;
380 }
381
382 int main(int argc, char **argv) {
383   InitializeAllTargets();
384   InitializeAllTargetMCs();
385   InitializeAllAsmPrinters();
386   InitializeAllAsmParsers();
387
388   // FIXME: This should use llvm::cl subcommands, but it isn't currently
389   // possible to pass an argument not associated with a subcommand to a
390   // subcommand (e.g. -use-new-pm).
391   if (argc < 2)
392     return usage();
393
394   StringRef Subcommand = argv[1];
395   // Ensure that argv[0] is correct after adjusting argv/argc.
396   argv[1] = argv[0];
397   if (Subcommand == "dump-symtab")
398     return dumpSymtab(argc - 1, argv + 1);
399   if (Subcommand == "run")
400     return run(argc - 1, argv + 1);
401   return usage();
402 }