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