Do not require a Context to extract the FunctionIndex from Bitcode (NFC)
[oota-llvm.git] / tools / llvm-link / llvm-link.cpp
1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
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 utility may be invoked in the following manner:
11 //  llvm-link a.bc b.bc c.bc -o x.bc
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Linker/Linker.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/FunctionInfo.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/Object/FunctionIndexObjectFile.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include <memory>
37 using namespace llvm;
38
39 static cl::list<std::string>
40 InputFilenames(cl::Positional, cl::OneOrMore,
41                cl::desc("<input bitcode files>"));
42
43 static cl::list<std::string> OverridingInputs(
44     "override", cl::ZeroOrMore, cl::value_desc("filename"),
45     cl::desc(
46         "input bitcode file which can override previously defined symbol(s)"));
47
48 // Option to simulate function importing for testing. This enables using
49 // llvm-link to simulate ThinLTO backend processes.
50 static cl::list<std::string> Imports(
51     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
52     cl::desc("Pair of function name and filename, where function should be "
53              "imported from bitcode in filename"));
54
55 // Option to support testing of function importing. The function index
56 // must be specified in the case were we request imports via the -import
57 // option, as well as when compiling any module with functions that may be
58 // exported (imported by a different llvm-link -import invocation), to ensure
59 // consistent promotion and renaming of locals.
60 static cl::opt<std::string> FunctionIndex("functionindex",
61                                           cl::desc("Function index filename"),
62                                           cl::init(""),
63                                           cl::value_desc("filename"));
64
65 static cl::opt<std::string>
66 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
67                cl::value_desc("filename"));
68
69 static cl::opt<bool>
70 Internalize("internalize", cl::desc("Internalize linked symbols"));
71
72 static cl::opt<bool>
73 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
74
75 static cl::opt<bool>
76 Force("f", cl::desc("Enable binary output on terminals"));
77
78 static cl::opt<bool>
79 OutputAssembly("S",
80          cl::desc("Write output as LLVM assembly"), cl::Hidden);
81
82 static cl::opt<bool>
83 Verbose("v", cl::desc("Print information about actions taken"));
84
85 static cl::opt<bool>
86 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
87
88 static cl::opt<bool>
89 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
90                  cl::init(false));
91
92 static cl::opt<bool> PreserveBitcodeUseListOrder(
93     "preserve-bc-uselistorder",
94     cl::desc("Preserve use-list order when writing LLVM bitcode."),
95     cl::init(true), cl::Hidden);
96
97 static cl::opt<bool> PreserveAssemblyUseListOrder(
98     "preserve-ll-uselistorder",
99     cl::desc("Preserve use-list order when writing LLVM assembly."),
100     cl::init(false), cl::Hidden);
101
102 // Read the specified bitcode file in and return it. This routine searches the
103 // link path for the specified file to try to find it...
104 //
105 static std::unique_ptr<Module>
106 loadFile(const char *argv0, const std::string &FN, LLVMContext &Context) {
107   SMDiagnostic Err;
108   if (Verbose) errs() << "Loading '" << FN << "'\n";
109   std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context);
110   if (!Result)
111     Err.print(argv0, errs());
112
113   Result->materializeMetadata();
114   UpgradeDebugInfo(*Result);
115
116   return Result;
117 }
118
119 static void diagnosticHandler(const DiagnosticInfo &DI) {
120   unsigned Severity = DI.getSeverity();
121   switch (Severity) {
122   case DS_Error:
123     errs() << "ERROR: ";
124     break;
125   case DS_Warning:
126     if (SuppressWarnings)
127       return;
128     errs() << "WARNING: ";
129     break;
130   case DS_Remark:
131   case DS_Note:
132     llvm_unreachable("Only expecting warnings and errors");
133   }
134
135   DiagnosticPrinterRawOStream DP(errs());
136   DI.print(DP);
137   errs() << '\n';
138 }
139
140 /// Load a function index if requested by the -functionindex option.
141 static ErrorOr<std::unique_ptr<FunctionInfoIndex>>
142 loadIndex(LLVMContext &Context, const Module *ExportingModule = nullptr) {
143   assert(!FunctionIndex.empty());
144   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
145       MemoryBuffer::getFileOrSTDIN(FunctionIndex);
146   std::error_code EC = FileOrErr.getError();
147   if (EC)
148     return EC;
149   MemoryBufferRef BufferRef = (FileOrErr.get())->getMemBufferRef();
150   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
151       object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler,
152                                               ExportingModule);
153   EC = ObjOrErr.getError();
154   if (EC)
155     return EC;
156
157   object::FunctionIndexObjectFile &Obj = **ObjOrErr;
158   return Obj.takeIndex();
159 }
160
161 /// Import any functions requested via the -import option.
162 static bool importFunctions(const char *argv0, LLVMContext &Context,
163                             Linker &L) {
164   for (const auto &Import : Imports) {
165     // Identify the requested function and its bitcode source file.
166     size_t Idx = Import.find(':');
167     if (Idx == std::string::npos) {
168       errs() << "Import parameter bad format: " << Import << "\n";
169       return false;
170     }
171     std::string FunctionName = Import.substr(0, Idx);
172     std::string FileName = Import.substr(Idx + 1, std::string::npos);
173
174     // Load the specified source module.
175     std::unique_ptr<Module> M = loadFile(argv0, FileName, Context);
176     if (!M.get()) {
177       errs() << argv0 << ": error loading file '" << FileName << "'\n";
178       return false;
179     }
180
181     if (verifyModule(*M, &errs())) {
182       errs() << argv0 << ": " << FileName
183              << ": error: input module is broken!\n";
184       return false;
185     }
186
187     Function *F = M->getFunction(FunctionName);
188     if (!F) {
189       errs() << "Ignoring import request for non-existent function "
190              << FunctionName << " from " << FileName << "\n";
191       continue;
192     }
193     // We cannot import weak_any functions without possibly affecting the
194     // order they are seen and selected by the linker, changing program
195     // semantics.
196     if (F->hasWeakAnyLinkage()) {
197       errs() << "Ignoring import request for weak-any function " << FunctionName
198              << " from " << FileName << "\n";
199       continue;
200     }
201
202     if (Verbose)
203       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
204
205     std::unique_ptr<FunctionInfoIndex> Index;
206     if (!FunctionIndex.empty()) {
207       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
208           loadIndex(Context);
209       std::error_code EC = IndexOrErr.getError();
210       if (EC) {
211         errs() << EC.message() << '\n';
212         return false;
213       }
214       Index = std::move(IndexOrErr.get());
215     }
216
217     // Link in the specified function.
218     if (L.linkInModule(M.get(), Linker::Flags::None, Index.get(), F))
219       return false;
220   }
221   return true;
222 }
223
224 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
225                       const cl::list<std::string> &Files,
226                       unsigned Flags) {
227   // Filter out flags that don't apply to the first file we load.
228   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
229   for (const auto &File : Files) {
230     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
231     if (!M.get()) {
232       errs() << argv0 << ": error loading file '" << File << "'\n";
233       return false;
234     }
235
236     if (verifyModule(*M, &errs())) {
237       errs() << argv0 << ": " << File << ": error: input module is broken!\n";
238       return false;
239     }
240
241     // If a function index is supplied, load it so linkInModule can treat
242     // local functions/variables as exported and promote if necessary.
243     std::unique_ptr<FunctionInfoIndex> Index;
244     if (!FunctionIndex.empty()) {
245       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
246           loadIndex(Context, &*M);
247       std::error_code EC = IndexOrErr.getError();
248       if (EC) {
249         errs() << EC.message() << '\n';
250         return false;
251       }
252       Index = std::move(IndexOrErr.get());
253     }
254
255     if (Verbose)
256       errs() << "Linking in '" << File << "'\n";
257
258     if (L.linkInModule(M.get(), ApplicableFlags, Index.get()))
259       return false;
260     // All linker flags apply to linking of subsequent files.
261     ApplicableFlags = Flags;
262   }
263
264   return true;
265 }
266
267 int main(int argc, char **argv) {
268   // Print a stack trace if we signal out.
269   sys::PrintStackTraceOnErrorSignal();
270   PrettyStackTraceProgram X(argc, argv);
271
272   LLVMContext &Context = getGlobalContext();
273   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
274   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
275
276   auto Composite = make_unique<Module>("llvm-link", Context);
277   Linker L(Composite.get(), diagnosticHandler);
278
279   unsigned Flags = Linker::Flags::None;
280   if (Internalize)
281     Flags |= Linker::Flags::InternalizeLinkedSymbols;
282   if (OnlyNeeded)
283     Flags |= Linker::Flags::LinkOnlyNeeded;
284
285   // First add all the regular input files
286   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
287     return 1;
288
289   // Next the -override ones.
290   if (!linkFiles(argv[0], Context, L, OverridingInputs,
291                  Flags | Linker::Flags::OverrideFromSrc))
292     return 1;
293
294   // Import any functions requested via -import
295   if (!importFunctions(argv[0], Context, L))
296     return 1;
297
298   if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
299
300   std::error_code EC;
301   tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
302   if (EC) {
303     errs() << EC.message() << '\n';
304     return 1;
305   }
306
307   if (verifyModule(*Composite, &errs())) {
308     errs() << argv[0] << ": error: linked module is broken!\n";
309     return 1;
310   }
311
312   if (Verbose) errs() << "Writing bitcode...\n";
313   if (OutputAssembly) {
314     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
315   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
316     WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
317
318   // Declare success.
319   Out.keep();
320
321   return 0;
322 }