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