Do not require a Context to extract the FunctionIndex from Bitcode (NFC)
[oota-llvm.git] / tools / llvm-lto / llvm-lto.cpp
1 //===-- llvm-lto: a simple command-line program to link modules with LTO --===//
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, performs link-time
11 // optimization, and outputs an object file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/LTO/LTOCodeGenerator.h"
21 #include "llvm/LTO/LTOModule.h"
22 #include "llvm/Object/FunctionIndexObjectFile.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/TargetSelect.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <list>
32
33 using namespace llvm;
34
35 static cl::opt<char>
36 OptLevel("O",
37          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
38                   "(default = '-O2')"),
39          cl::Prefix,
40          cl::ZeroOrMore,
41          cl::init('2'));
42
43 static cl::opt<bool> DisableVerify(
44     "disable-verify", cl::init(false),
45     cl::desc("Do not run the verifier during the optimization pipeline"));
46
47 static cl::opt<bool>
48 DisableInline("disable-inlining", cl::init(false),
49   cl::desc("Do not run the inliner pass"));
50
51 static cl::opt<bool>
52 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
53   cl::desc("Do not run the GVN load PRE pass"));
54
55 static cl::opt<bool>
56 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
57   cl::desc("Do not run loop or slp vectorization during LTO"));
58
59 static cl::opt<bool>
60 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
61   cl::desc("Use a diagnostic handler to test the handler interface"));
62
63 static cl::opt<bool>
64     ThinLTO("thinlto", cl::init(false),
65             cl::desc("Only write combined global index for ThinLTO backends"));
66
67 static cl::list<std::string>
68 InputFilenames(cl::Positional, cl::OneOrMore,
69   cl::desc("<input bitcode files>"));
70
71 static cl::opt<std::string>
72 OutputFilename("o", cl::init(""),
73   cl::desc("Override output filename"),
74   cl::value_desc("filename"));
75
76 static cl::list<std::string>
77 ExportedSymbols("exported-symbol",
78   cl::desc("Symbol to export from the resulting object file"),
79   cl::ZeroOrMore);
80
81 static cl::list<std::string>
82 DSOSymbols("dso-symbol",
83   cl::desc("Symbol to put in the symtab in the resulting dso"),
84   cl::ZeroOrMore);
85
86 static cl::opt<bool> ListSymbolsOnly(
87     "list-symbols-only", cl::init(false),
88     cl::desc("Instead of running LTO, list the symbols in each IR file"));
89
90 static cl::opt<bool> SetMergedModule(
91     "set-merged-module", cl::init(false),
92     cl::desc("Use the first input module as the merged module"));
93
94 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
95                                      cl::desc("Number of backend threads"));
96
97 namespace {
98 struct ModuleInfo {
99   std::vector<bool> CanBeHidden;
100 };
101 }
102
103 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
104                               const char *Msg, void *) {
105   errs() << "llvm-lto: ";
106   switch (Severity) {
107   case LTO_DS_NOTE:
108     errs() << "note: ";
109     break;
110   case LTO_DS_REMARK:
111     errs() << "remark: ";
112     break;
113   case LTO_DS_ERROR:
114     errs() << "error: ";
115     break;
116   case LTO_DS_WARNING:
117     errs() << "warning: ";
118     break;
119   }
120   errs() << Msg << "\n";
121 }
122
123 static void diagnosticHandler(const DiagnosticInfo &DI) {
124   raw_ostream &OS = errs();
125   OS << "llvm-lto: ";
126   switch (DI.getSeverity()) {
127   case DS_Error:
128     OS << "error: ";
129     break;
130   case DS_Warning:
131     OS << "warning: ";
132     break;
133   case DS_Remark:
134     OS << "remark: ";
135     break;
136   case DS_Note:
137     OS << "note: ";
138     break;
139   }
140
141   DiagnosticPrinterRawOStream DP(OS);
142   DI.print(DP);
143   OS << '\n';
144
145   if (DI.getSeverity() == DS_Error)
146     exit(1);
147 }
148
149 static std::unique_ptr<LTOModule>
150 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
151                   const TargetOptions &Options, std::string &Error) {
152   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
153       MemoryBuffer::getFile(Path);
154   if (std::error_code EC = BufferOrErr.getError()) {
155     Error = EC.message();
156     return nullptr;
157   }
158   Buffer = std::move(BufferOrErr.get());
159   return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
160       Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
161 }
162
163 /// \brief List symbols in each IR file.
164 ///
165 /// The main point here is to provide lit-testable coverage for the LTOModule
166 /// functionality that's exposed by the C API to list symbols.  Moreover, this
167 /// provides testing coverage for modules that have been created in their own
168 /// contexts.
169 static int listSymbols(StringRef Command, const TargetOptions &Options) {
170   for (auto &Filename : InputFilenames) {
171     std::string Error;
172     std::unique_ptr<MemoryBuffer> Buffer;
173     std::unique_ptr<LTOModule> Module =
174         getLocalLTOModule(Filename, Buffer, Options, Error);
175     if (!Module) {
176       errs() << Command << ": error loading file '" << Filename
177              << "': " << Error << "\n";
178       return 1;
179     }
180
181     // List the symbols.
182     outs() << Filename << ":\n";
183     for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
184       outs() << Module->getSymbolName(I) << "\n";
185   }
186   return 0;
187 }
188
189 /// Parse the function index out of an IR file and return the function
190 /// index object if found, or nullptr if not.
191 static std::unique_ptr<FunctionInfoIndex>
192 getFunctionIndexForFile(StringRef Path, std::string &Error,
193                         DiagnosticHandlerFunction DiagnosticHandler) {
194   std::unique_ptr<MemoryBuffer> Buffer;
195   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
196       MemoryBuffer::getFile(Path);
197   if (std::error_code EC = BufferOrErr.getError()) {
198     Error = EC.message();
199     return nullptr;
200   }
201   Buffer = std::move(BufferOrErr.get());
202   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
203       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
204                                               DiagnosticHandler);
205   if (std::error_code EC = ObjOrErr.getError()) {
206     Error = EC.message();
207     return nullptr;
208   }
209   return (*ObjOrErr)->takeIndex();
210 }
211
212 /// Create a combined index file from the input IR files and write it.
213 ///
214 /// This is meant to enable testing of ThinLTO combined index generation,
215 /// currently available via the gold plugin via -thinlto.
216 static int createCombinedFunctionIndex(StringRef Command) {
217   FunctionInfoIndex CombinedIndex;
218   uint64_t NextModuleId = 0;
219   for (auto &Filename : InputFilenames) {
220     std::string Error;
221     std::unique_ptr<FunctionInfoIndex> Index =
222         getFunctionIndexForFile(Filename, Error, diagnosticHandler);
223     if (!Index) {
224       errs() << Command << ": error loading file '" << Filename
225              << "': " << Error << "\n";
226       return 1;
227     }
228     CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
229   }
230   std::error_code EC;
231   assert(!OutputFilename.empty());
232   raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
233                     sys::fs::OpenFlags::F_None);
234   if (EC) {
235     errs() << Command << ": error opening the file '" << OutputFilename
236            << ".thinlto.bc': " << EC.message() << "\n";
237     return 1;
238   }
239   WriteFunctionSummaryToFile(CombinedIndex, OS);
240   OS.close();
241   return 0;
242 }
243
244 int main(int argc, char **argv) {
245   // Print a stack trace if we signal out.
246   sys::PrintStackTraceOnErrorSignal();
247   PrettyStackTraceProgram X(argc, argv);
248
249   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
250   cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
251
252   if (OptLevel < '0' || OptLevel > '3') {
253     errs() << argv[0] << ": optimization level must be between 0 and 3\n";
254     return 1;
255   }
256
257   // Initialize the configured targets.
258   InitializeAllTargets();
259   InitializeAllTargetMCs();
260   InitializeAllAsmPrinters();
261   InitializeAllAsmParsers();
262
263   // set up the TargetOptions for the machine
264   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
265
266   if (ListSymbolsOnly)
267     return listSymbols(argv[0], Options);
268
269   if (ThinLTO)
270     return createCombinedFunctionIndex(argv[0]);
271
272   unsigned BaseArg = 0;
273
274   LTOCodeGenerator CodeGen;
275
276   if (UseDiagnosticHandler)
277     CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
278
279   CodeGen.setCodePICModel(RelocModel);
280
281   CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
282   CodeGen.setTargetOptions(Options);
283
284   llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
285   for (unsigned i = 0; i < DSOSymbols.size(); ++i)
286     DSOSymbolsSet.insert(DSOSymbols[i]);
287
288   std::vector<std::string> KeptDSOSyms;
289
290   for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
291     std::string error;
292     std::unique_ptr<LTOModule> Module(
293         LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
294     if (!error.empty()) {
295       errs() << argv[0] << ": error loading file '" << InputFilenames[i]
296              << "': " << error << "\n";
297       return 1;
298     }
299
300     unsigned NumSyms = Module->getSymbolCount();
301     for (unsigned I = 0; I < NumSyms; ++I) {
302       StringRef Name = Module->getSymbolName(I);
303       if (!DSOSymbolsSet.count(Name))
304         continue;
305       lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
306       unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
307       if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
308         KeptDSOSyms.push_back(Name);
309     }
310
311     // We use the first input module as the destination module when
312     // SetMergedModule is true.
313     if (SetMergedModule && i == BaseArg) {
314       // Transfer ownership to the code generator.
315       CodeGen.setModule(std::move(Module));
316     } else if (!CodeGen.addModule(Module.get())) {
317       // Print a message here so that we know addModule() did not abort.
318       errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
319       return 1;
320     }
321   }
322
323   // Add all the exported symbols to the table of symbols to preserve.
324   for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
325     CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
326
327   // Add all the dso symbols to the table of symbols to expose.
328   for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
329     CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
330
331   // Set cpu and attrs strings for the default target/subtarget.
332   CodeGen.setCpu(MCPU.c_str());
333
334   CodeGen.setOptLevel(OptLevel - '0');
335
336   std::string attrs;
337   for (unsigned i = 0; i < MAttrs.size(); ++i) {
338     if (i > 0)
339       attrs.append(",");
340     attrs.append(MAttrs[i]);
341   }
342
343   if (!attrs.empty())
344     CodeGen.setAttr(attrs.c_str());
345
346   if (!OutputFilename.empty()) {
347     if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
348                           DisableLTOVectorization)) {
349       // Diagnostic messages should have been printed by the handler.
350       errs() << argv[0] << ": error optimizing the code\n";
351       return 1;
352     }
353
354     std::list<tool_output_file> OSs;
355     std::vector<raw_pwrite_stream *> OSPtrs;
356     for (unsigned I = 0; I != Parallelism; ++I) {
357       std::string PartFilename = OutputFilename;
358       if (Parallelism != 1)
359         PartFilename += "." + utostr(I);
360       std::error_code EC;
361       OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
362       if (EC) {
363         errs() << argv[0] << ": error opening the file '" << PartFilename
364                << "': " << EC.message() << "\n";
365         return 1;
366       }
367       OSPtrs.push_back(&OSs.back().os());
368     }
369
370     if (!CodeGen.compileOptimized(OSPtrs)) {
371       // Diagnostic messages should have been printed by the handler.
372       errs() << argv[0] << ": error compiling the code\n";
373       return 1;
374     }
375
376     for (tool_output_file &OS : OSs)
377       OS.keep();
378   } else {
379     if (Parallelism != 1) {
380       errs() << argv[0] << ": -j must be specified together with -o\n";
381       return 1;
382     }
383
384     const char *OutputName = nullptr;
385     if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
386                                  DisableGVNLoadPRE, DisableLTOVectorization)) {
387       // Diagnostic messages should have been printed by the handler.
388       errs() << argv[0] << ": error compiling the code\n";
389       return 1;
390     }
391
392     outs() << "Wrote native object file '" << OutputName << "'\n";
393   }
394
395   return 0;
396 }