Remove unused function parameter (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>
93     PreserveModules("preserve-modules",
94                     cl::desc("Preserve linked modules for testing"));
95
96 static cl::opt<bool> PreserveBitcodeUseListOrder(
97     "preserve-bc-uselistorder",
98     cl::desc("Preserve use-list order when writing LLVM bitcode."),
99     cl::init(true), cl::Hidden);
100
101 static cl::opt<bool> PreserveAssemblyUseListOrder(
102     "preserve-ll-uselistorder",
103     cl::desc("Preserve use-list order when writing LLVM assembly."),
104     cl::init(false), cl::Hidden);
105
106 // Read the specified bitcode file in and return it. This routine searches the
107 // link path for the specified file to try to find it...
108 //
109 static std::unique_ptr<Module>
110 loadFile(const char *argv0, const std::string &FN, LLVMContext &Context) {
111   SMDiagnostic Err;
112   if (Verbose) errs() << "Loading '" << FN << "'\n";
113   std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context);
114   if (!Result)
115     Err.print(argv0, errs());
116
117   Result->materializeMetadata();
118   UpgradeDebugInfo(*Result);
119
120   return Result;
121 }
122
123 static void diagnosticHandler(const DiagnosticInfo &DI) {
124   unsigned Severity = DI.getSeverity();
125   switch (Severity) {
126   case DS_Error:
127     errs() << "ERROR: ";
128     break;
129   case DS_Warning:
130     if (SuppressWarnings)
131       return;
132     errs() << "WARNING: ";
133     break;
134   case DS_Remark:
135   case DS_Note:
136     llvm_unreachable("Only expecting warnings and errors");
137   }
138
139   DiagnosticPrinterRawOStream DP(errs());
140   DI.print(DP);
141   errs() << '\n';
142 }
143
144 /// Load a function index if requested by the -functionindex option.
145 static ErrorOr<std::unique_ptr<FunctionInfoIndex>>
146 loadIndex(const Module *ExportingModule = nullptr) {
147   assert(!FunctionIndex.empty());
148   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
149       MemoryBuffer::getFileOrSTDIN(FunctionIndex);
150   std::error_code EC = FileOrErr.getError();
151   if (EC)
152     return EC;
153   MemoryBufferRef BufferRef = (FileOrErr.get())->getMemBufferRef();
154   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
155       object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler,
156                                               ExportingModule);
157   EC = ObjOrErr.getError();
158   if (EC)
159     return EC;
160
161   object::FunctionIndexObjectFile &Obj = **ObjOrErr;
162   return Obj.takeIndex();
163 }
164
165 /// Import any functions requested via the -import option.
166 static bool importFunctions(const char *argv0, LLVMContext &Context,
167                             Linker &L) {
168   for (const auto &Import : Imports) {
169     // Identify the requested function and its bitcode source file.
170     size_t Idx = Import.find(':');
171     if (Idx == std::string::npos) {
172       errs() << "Import parameter bad format: " << Import << "\n";
173       return false;
174     }
175     std::string FunctionName = Import.substr(0, Idx);
176     std::string FileName = Import.substr(Idx + 1, std::string::npos);
177
178     // Load the specified source module.
179     std::unique_ptr<Module> M = loadFile(argv0, FileName, Context);
180     if (!M.get()) {
181       errs() << argv0 << ": error loading file '" << FileName << "'\n";
182       return false;
183     }
184
185     if (verifyModule(*M, &errs())) {
186       errs() << argv0 << ": " << FileName
187              << ": error: input module is broken!\n";
188       return false;
189     }
190
191     Function *F = M->getFunction(FunctionName);
192     if (!F) {
193       errs() << "Ignoring import request for non-existent function "
194              << FunctionName << " from " << FileName << "\n";
195       continue;
196     }
197     // We cannot import weak_any functions without possibly affecting the
198     // order they are seen and selected by the linker, changing program
199     // semantics.
200     if (F->hasWeakAnyLinkage()) {
201       errs() << "Ignoring import request for weak-any function " << FunctionName
202              << " from " << FileName << "\n";
203       continue;
204     }
205
206     if (Verbose)
207       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
208
209     std::unique_ptr<FunctionInfoIndex> Index;
210     if (!FunctionIndex.empty()) {
211       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr = loadIndex();
212       std::error_code EC = IndexOrErr.getError();
213       if (EC) {
214         errs() << EC.message() << '\n';
215         return false;
216       }
217       Index = std::move(IndexOrErr.get());
218     }
219
220     // Link in the specified function.
221     if (L.linkInModule(M.get(), Linker::Flags::None, Index.get(), F))
222       return false;
223   }
224   return true;
225 }
226
227 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
228                       const cl::list<std::string> &Files,
229                       unsigned Flags) {
230   // Filter out flags that don't apply to the first file we load.
231   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
232   for (const auto &File : Files) {
233     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
234     if (!M.get()) {
235       errs() << argv0 << ": error loading file '" << File << "'\n";
236       return false;
237     }
238
239     if (verifyModule(*M, &errs())) {
240       errs() << argv0 << ": " << File << ": error: input module is broken!\n";
241       return false;
242     }
243
244     // If a function index is supplied, load it so linkInModule can treat
245     // local functions/variables as exported and promote if necessary.
246     std::unique_ptr<FunctionInfoIndex> Index;
247     if (!FunctionIndex.empty()) {
248       ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr = loadIndex(&*M);
249       std::error_code EC = IndexOrErr.getError();
250       if (EC) {
251         errs() << EC.message() << '\n';
252         return false;
253       }
254       Index = std::move(IndexOrErr.get());
255     }
256
257     if (Verbose)
258       errs() << "Linking in '" << File << "'\n";
259
260     if (L.linkInModule(M.get(), ApplicableFlags, Index.get()))
261       return false;
262     // All linker flags apply to linking of subsequent files.
263     ApplicableFlags = Flags;
264
265     // If requested for testing, preserve modules by releasing them from
266     // the unique_ptr before the are freed. This can help catch any
267     // cross-module references from e.g. unneeded metadata references
268     // that aren't properly set to null but instead mapped to the source
269     // module version. The bitcode writer will assert if it finds any such
270     // cross-module references.
271     if (PreserveModules)
272       M.release();
273   }
274
275   return true;
276 }
277
278 int main(int argc, char **argv) {
279   // Print a stack trace if we signal out.
280   sys::PrintStackTraceOnErrorSignal();
281   PrettyStackTraceProgram X(argc, argv);
282
283   LLVMContext &Context = getGlobalContext();
284   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
285   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
286
287   auto Composite = make_unique<Module>("llvm-link", Context);
288   Linker L(Composite.get(), diagnosticHandler);
289
290   unsigned Flags = Linker::Flags::None;
291   if (Internalize)
292     Flags |= Linker::Flags::InternalizeLinkedSymbols;
293   if (OnlyNeeded)
294     Flags |= Linker::Flags::LinkOnlyNeeded;
295
296   // First add all the regular input files
297   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
298     return 1;
299
300   // Next the -override ones.
301   if (!linkFiles(argv[0], Context, L, OverridingInputs,
302                  Flags | Linker::Flags::OverrideFromSrc))
303     return 1;
304
305   // Import any functions requested via -import
306   if (!importFunctions(argv[0], Context, L))
307     return 1;
308
309   if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
310
311   std::error_code EC;
312   tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
313   if (EC) {
314     errs() << EC.message() << '\n';
315     return 1;
316   }
317
318   if (verifyModule(*Composite, &errs())) {
319     errs() << argv[0] << ": error: linked module is broken!\n";
320     return 1;
321   }
322
323   if (Verbose) errs() << "Writing bitcode...\n";
324   if (OutputAssembly) {
325     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
326   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
327     WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
328
329   // Declare success.
330   Out.keep();
331
332   return 0;
333 }