e580a5df57824d022b3cd1f45667453576b13597
[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::opt<bool>
68 SaveModuleFile("save-merged-module", cl::init(false),
69                cl::desc("Write merged LTO module to file before CodeGen"));
70
71 static cl::list<std::string>
72 InputFilenames(cl::Positional, cl::OneOrMore,
73   cl::desc("<input bitcode files>"));
74
75 static cl::opt<std::string>
76 OutputFilename("o", cl::init(""),
77   cl::desc("Override output filename"),
78   cl::value_desc("filename"));
79
80 static cl::list<std::string>
81 ExportedSymbols("exported-symbol",
82   cl::desc("Symbol to export from the resulting object file"),
83   cl::ZeroOrMore);
84
85 static cl::list<std::string>
86 DSOSymbols("dso-symbol",
87   cl::desc("Symbol to put in the symtab in the resulting dso"),
88   cl::ZeroOrMore);
89
90 static cl::opt<bool> ListSymbolsOnly(
91     "list-symbols-only", cl::init(false),
92     cl::desc("Instead of running LTO, list the symbols in each IR file"));
93
94 static cl::opt<bool> SetMergedModule(
95     "set-merged-module", cl::init(false),
96     cl::desc("Use the first input module as the merged module"));
97
98 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
99                                      cl::desc("Number of backend threads"));
100
101 namespace {
102 struct ModuleInfo {
103   std::vector<bool> CanBeHidden;
104 };
105 }
106
107 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
108                               const char *Msg, void *) {
109   errs() << "llvm-lto: ";
110   switch (Severity) {
111   case LTO_DS_NOTE:
112     errs() << "note: ";
113     break;
114   case LTO_DS_REMARK:
115     errs() << "remark: ";
116     break;
117   case LTO_DS_ERROR:
118     errs() << "error: ";
119     break;
120   case LTO_DS_WARNING:
121     errs() << "warning: ";
122     break;
123   }
124   errs() << Msg << "\n";
125 }
126
127 static void diagnosticHandler(const DiagnosticInfo &DI) {
128   raw_ostream &OS = errs();
129   OS << "llvm-lto: ";
130   switch (DI.getSeverity()) {
131   case DS_Error:
132     OS << "error: ";
133     break;
134   case DS_Warning:
135     OS << "warning: ";
136     break;
137   case DS_Remark:
138     OS << "remark: ";
139     break;
140   case DS_Note:
141     OS << "note: ";
142     break;
143   }
144
145   DiagnosticPrinterRawOStream DP(OS);
146   DI.print(DP);
147   OS << '\n';
148
149   if (DI.getSeverity() == DS_Error)
150     exit(1);
151 }
152
153 static std::unique_ptr<LTOModule>
154 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
155                   const TargetOptions &Options, std::string &Error) {
156   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
157       MemoryBuffer::getFile(Path);
158   if (std::error_code EC = BufferOrErr.getError()) {
159     Error = EC.message();
160     return nullptr;
161   }
162   Buffer = std::move(BufferOrErr.get());
163   return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
164       Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
165 }
166
167 /// \brief List symbols in each IR file.
168 ///
169 /// The main point here is to provide lit-testable coverage for the LTOModule
170 /// functionality that's exposed by the C API to list symbols.  Moreover, this
171 /// provides testing coverage for modules that have been created in their own
172 /// contexts.
173 static int listSymbols(StringRef Command, const TargetOptions &Options) {
174   for (auto &Filename : InputFilenames) {
175     std::string Error;
176     std::unique_ptr<MemoryBuffer> Buffer;
177     std::unique_ptr<LTOModule> Module =
178         getLocalLTOModule(Filename, Buffer, Options, Error);
179     if (!Module) {
180       errs() << Command << ": error loading file '" << Filename
181              << "': " << Error << "\n";
182       return 1;
183     }
184
185     // List the symbols.
186     outs() << Filename << ":\n";
187     for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
188       outs() << Module->getSymbolName(I) << "\n";
189   }
190   return 0;
191 }
192
193 /// Parse the function index out of an IR file and return the function
194 /// index object if found, or nullptr if not.
195 static ErrorOr<std::unique_ptr<FunctionInfoIndex>>
196 getFunctionIndexForFile(StringRef Path,
197                         DiagnosticHandlerFunction DiagnosticHandler) {
198   std::unique_ptr<MemoryBuffer> Buffer;
199   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
200       MemoryBuffer::getFile(Path);
201   if (std::error_code EC = BufferOrErr.getError())
202     return EC;
203   Buffer = std::move(BufferOrErr.get());
204
205   // Don't bother trying to build an index if there is no summary information
206   // in this bitcode file.
207   if (!object::FunctionIndexObjectFile::hasFunctionSummaryInMemBuffer(
208           Buffer->getMemBufferRef(), DiagnosticHandler))
209     return std::unique_ptr<FunctionInfoIndex>(nullptr);
210
211   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
212       object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
213                                               DiagnosticHandler);
214   if (std::error_code EC = ObjOrErr.getError())
215     return EC;
216   return (*ObjOrErr)->takeIndex();
217 }
218
219 /// Create a combined index file from the input IR files and write it.
220 ///
221 /// This is meant to enable testing of ThinLTO combined index generation,
222 /// currently available via the gold plugin via -thinlto.
223 static int createCombinedFunctionIndex(StringRef Command) {
224   FunctionInfoIndex CombinedIndex;
225   uint64_t NextModuleId = 0;
226   for (auto &Filename : InputFilenames) {
227     ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
228         getFunctionIndexForFile(Filename, diagnosticHandler);
229     if (std::error_code EC = IndexOrErr.getError()) {
230       std::string Error = EC.message();
231       errs() << Command << ": error loading file '" << Filename
232              << "': " << Error << "\n";
233       return 1;
234     }
235     std::unique_ptr<FunctionInfoIndex> Index = std::move(IndexOrErr.get());
236     // Skip files without a function summary.
237     if (!Index)
238       continue;
239     CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
240   }
241   std::error_code EC;
242   assert(!OutputFilename.empty());
243   raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
244                     sys::fs::OpenFlags::F_None);
245   if (EC) {
246     errs() << Command << ": error opening the file '" << OutputFilename
247            << ".thinlto.bc': " << EC.message() << "\n";
248     return 1;
249   }
250   WriteFunctionSummaryToFile(CombinedIndex, OS);
251   OS.close();
252   return 0;
253 }
254
255 int main(int argc, char **argv) {
256   // Print a stack trace if we signal out.
257   sys::PrintStackTraceOnErrorSignal();
258   PrettyStackTraceProgram X(argc, argv);
259
260   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
261   cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
262
263   if (OptLevel < '0' || OptLevel > '3') {
264     errs() << argv[0] << ": optimization level must be between 0 and 3\n";
265     return 1;
266   }
267
268   // Initialize the configured targets.
269   InitializeAllTargets();
270   InitializeAllTargetMCs();
271   InitializeAllAsmPrinters();
272   InitializeAllAsmParsers();
273
274   // set up the TargetOptions for the machine
275   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
276
277   if (ListSymbolsOnly)
278     return listSymbols(argv[0], Options);
279
280   if (ThinLTO)
281     return createCombinedFunctionIndex(argv[0]);
282
283   unsigned BaseArg = 0;
284
285   LTOCodeGenerator CodeGen;
286
287   if (UseDiagnosticHandler)
288     CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
289
290   CodeGen.setCodePICModel(RelocModel);
291
292   CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
293   CodeGen.setTargetOptions(Options);
294
295   llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
296   for (unsigned i = 0; i < DSOSymbols.size(); ++i)
297     DSOSymbolsSet.insert(DSOSymbols[i]);
298
299   std::vector<std::string> KeptDSOSyms;
300
301   for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
302     std::string error;
303     std::unique_ptr<LTOModule> Module(
304         LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
305     if (!error.empty()) {
306       errs() << argv[0] << ": error loading file '" << InputFilenames[i]
307              << "': " << error << "\n";
308       return 1;
309     }
310
311     unsigned NumSyms = Module->getSymbolCount();
312     for (unsigned I = 0; I < NumSyms; ++I) {
313       StringRef Name = Module->getSymbolName(I);
314       if (!DSOSymbolsSet.count(Name))
315         continue;
316       lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
317       unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
318       if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
319         KeptDSOSyms.push_back(Name);
320     }
321
322     // We use the first input module as the destination module when
323     // SetMergedModule is true.
324     if (SetMergedModule && i == BaseArg) {
325       // Transfer ownership to the code generator.
326       CodeGen.setModule(std::move(Module));
327     } else if (!CodeGen.addModule(Module.get())) {
328       // Print a message here so that we know addModule() did not abort.
329       errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
330       return 1;
331     }
332   }
333
334   // Add all the exported symbols to the table of symbols to preserve.
335   for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
336     CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
337
338   // Add all the dso symbols to the table of symbols to expose.
339   for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
340     CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
341
342   // Set cpu and attrs strings for the default target/subtarget.
343   CodeGen.setCpu(MCPU.c_str());
344
345   CodeGen.setOptLevel(OptLevel - '0');
346
347   std::string attrs;
348   for (unsigned i = 0; i < MAttrs.size(); ++i) {
349     if (i > 0)
350       attrs.append(",");
351     attrs.append(MAttrs[i]);
352   }
353
354   if (!attrs.empty())
355     CodeGen.setAttr(attrs.c_str());
356
357   if (FileType.getNumOccurrences())
358     CodeGen.setFileType(FileType);
359
360   if (!OutputFilename.empty()) {
361     if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
362                           DisableLTOVectorization)) {
363       // Diagnostic messages should have been printed by the handler.
364       errs() << argv[0] << ": error optimizing the code\n";
365       return 1;
366     }
367
368     if (SaveModuleFile) {
369       std::string ModuleFilename = OutputFilename;
370       ModuleFilename += ".merged.bc";
371       std::string ErrMsg;
372
373       if (!CodeGen.writeMergedModules(ModuleFilename.c_str())) {
374         errs() << argv[0] << ": writing merged module failed.\n";
375         return 1;
376       }
377     }
378
379     std::list<tool_output_file> OSs;
380     std::vector<raw_pwrite_stream *> OSPtrs;
381     for (unsigned I = 0; I != Parallelism; ++I) {
382       std::string PartFilename = OutputFilename;
383       if (Parallelism != 1)
384         PartFilename += "." + utostr(I);
385       std::error_code EC;
386       OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
387       if (EC) {
388         errs() << argv[0] << ": error opening the file '" << PartFilename
389                << "': " << EC.message() << "\n";
390         return 1;
391       }
392       OSPtrs.push_back(&OSs.back().os());
393     }
394
395     if (!CodeGen.compileOptimized(OSPtrs)) {
396       // Diagnostic messages should have been printed by the handler.
397       errs() << argv[0] << ": error compiling the code\n";
398       return 1;
399     }
400
401     for (tool_output_file &OS : OSs)
402       OS.keep();
403   } else {
404     if (Parallelism != 1) {
405       errs() << argv[0] << ": -j must be specified together with -o\n";
406       return 1;
407     }
408
409     if (SaveModuleFile) {
410       errs() << argv[0] << ": -save-merged-module must be specified with -o\n";
411       return 1;
412     }
413
414     const char *OutputName = nullptr;
415     if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
416                                  DisableGVNLoadPRE, DisableLTOVectorization)) {
417       // Diagnostic messages should have been printed by the handler.
418       errs() << argv[0] << ": error compiling the code\n";
419       return 1;
420     }
421
422     outs() << "Wrote native object file '" << OutputName << "'\n";
423   }
424
425   return 0;
426 }