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