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