blob: 39034aaf672c991b187e2eb833271a4e4176d671 [file] [log] [blame]
Chris Lattner825937d2003-09-20 02:42:54 +00001//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner9d810e02001-10-13 07:06:23 +00009//
10// This utility may be invoked in the following manner:
Misha Brukmancf0c7442003-09-15 18:34:34 +000011// llvm-link a.bc b.bc c.bc -o x.bc
Chris Lattner9d810e02001-10-13 07:06:23 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6cc07df2014-03-06 03:42:23 +000015#include "llvm/Linker/Linker.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Chris Lattner27936992007-05-06 05:13:17 +000017#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000018#include "llvm/IR/AutoUpgrade.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000019#include "llvm/IR/DiagnosticInfo.h"
20#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000021#include "llvm/IR/FunctionInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Verifier.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000025#include "llvm/IRReader/IRReader.h"
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000026#include "llvm/Object/FunctionIndexObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000028#include "llvm/Support/FileSystem.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000030#include "llvm/Support/Path.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000031#include "llvm/Support/PrettyStackTrace.h"
32#include "llvm/Support/Signals.h"
Chandler Carruthe60e57b2013-03-26 02:25:37 +000033#include "llvm/Support/SourceMgr.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/Support/SystemUtils.h"
35#include "llvm/Support/ToolOutputFile.h"
Chris Lattner9d810e02001-10-13 07:06:23 +000036#include <memory>
Brian Gaeke960707c2003-11-11 22:41:34 +000037using namespace llvm;
38
Chris Lattnerf5cad152002-07-22 02:10:13 +000039static cl::list<std::string>
40InputFilenames(cl::Positional, cl::OneOrMore,
Gabor Greife16561c2007-07-05 17:07:56 +000041 cl::desc("<input bitcode files>"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000042
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000043static 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
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000048// Option to simulate function importing for testing. This enables using
49// llvm-link to simulate ThinLTO backend processes.
50static 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.
60static cl::opt<std::string> FunctionIndex("functionindex",
61 cl::desc("Function index filename"),
62 cl::init(""),
63 cl::value_desc("filename"));
64
Chris Lattnerf5cad152002-07-22 02:10:13 +000065static cl::opt<std::string>
66OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
67 cl::value_desc("filename"));
68
Dan Gohman61a87962009-08-25 15:34:52 +000069static cl::opt<bool>
Artem Belevich020d4fb2015-09-01 17:55:55 +000070Internalize("internalize", cl::desc("Internalize linked symbols"));
71
72static cl::opt<bool>
73OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
74
75static cl::opt<bool>
Dan Gohman61a87962009-08-25 15:34:52 +000076Force("f", cl::desc("Enable binary output on terminals"));
Chris Lattnerf5cad152002-07-22 02:10:13 +000077
78static cl::opt<bool>
Dan Gohman2b09de92009-09-15 15:35:07 +000079OutputAssembly("S",
80 cl::desc("Write output as LLVM assembly"), cl::Hidden);
81
82static cl::opt<bool>
Chris Lattnerf5cad152002-07-22 02:10:13 +000083Verbose("v", cl::desc("Print information about actions taken"));
84
85static cl::opt<bool>
86DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
87
Eli Bendersky7da92ed2014-02-20 22:19:24 +000088static cl::opt<bool>
89SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
90 cl::init(false));
91
Teresa Johnson5bc88be2015-11-21 00:35:38 +000092static cl::opt<bool>
93 PreserveModules("preserve-modules",
94 cl::desc("Preserve linked modules for testing"));
95
Duncan P. N. Exon Smith8a7b84b2015-04-15 03:14:06 +000096static 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
101static 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
Rafael Espindolad233b062014-08-26 17:29:46 +0000106// 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...
Reid Spencerb956fc12004-09-12 23:39:42 +0000108//
Rafael Espindolad233b062014-08-26 17:29:46 +0000109static std::unique_ptr<Module>
110loadFile(const char *argv0, const std::string &FN, LLVMContext &Context) {
Dan Gohman3d2c9142009-09-12 21:55:12 +0000111 SMDiagnostic Err;
Rafael Espindolaf1f12732013-06-17 17:32:19 +0000112 if (Verbose) errs() << "Loading '" << FN << "'\n";
Rafael Espindola957eae22014-10-23 19:40:45 +0000113 std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context);
Rafael Espindola5c4f4a62014-08-26 18:03:35 +0000114 if (!Result)
115 Err.print(argv0, errs());
Reid Spencerfe020a32004-09-11 04:32:42 +0000116
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000117 Result->materializeMetadata();
118 UpgradeDebugInfo(*Result);
Rafael Espindola2fcfb5e2015-03-27 15:55:06 +0000119
Rafael Espindola5c4f4a62014-08-26 18:03:35 +0000120 return Result;
Chris Lattnerae31f5b2001-10-24 06:23:00 +0000121}
Chris Lattner9d810e02001-10-13 07:06:23 +0000122
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000123static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000124 unsigned Severity = DI.getSeverity();
125 switch (Severity) {
126 case DS_Error:
127 errs() << "ERROR: ";
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000128 break;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000129 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);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000141 errs() << '\n';
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000142}
143
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000144/// Import any functions requested via the -import option.
145static bool importFunctions(const char *argv0, LLVMContext &Context,
146 Linker &L) {
147 for (const auto &Import : Imports) {
148 // Identify the requested function and its bitcode source file.
149 size_t Idx = Import.find(':');
150 if (Idx == std::string::npos) {
151 errs() << "Import parameter bad format: " << Import << "\n";
152 return false;
153 }
154 std::string FunctionName = Import.substr(0, Idx);
155 std::string FileName = Import.substr(Idx + 1, std::string::npos);
156
157 // Load the specified source module.
158 std::unique_ptr<Module> M = loadFile(argv0, FileName, Context);
159 if (!M.get()) {
160 errs() << argv0 << ": error loading file '" << FileName << "'\n";
161 return false;
162 }
163
164 if (verifyModule(*M, &errs())) {
165 errs() << argv0 << ": " << FileName
166 << ": error: input module is broken!\n";
167 return false;
168 }
169
170 Function *F = M->getFunction(FunctionName);
171 if (!F) {
172 errs() << "Ignoring import request for non-existent function "
173 << FunctionName << " from " << FileName << "\n";
174 continue;
175 }
176 // We cannot import weak_any functions without possibly affecting the
177 // order they are seen and selected by the linker, changing program
178 // semantics.
179 if (F->hasWeakAnyLinkage()) {
180 errs() << "Ignoring import request for weak-any function " << FunctionName
181 << " from " << FileName << "\n";
182 continue;
183 }
184
185 if (Verbose)
186 errs() << "Importing " << FunctionName << " from " << FileName << "\n";
187
188 std::unique_ptr<FunctionInfoIndex> Index;
189 if (!FunctionIndex.empty()) {
Teresa Johnson6b923162015-11-23 19:19:11 +0000190 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
191 llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000192 std::error_code EC = IndexOrErr.getError();
193 if (EC) {
194 errs() << EC.message() << '\n';
195 return false;
196 }
197 Index = std::move(IndexOrErr.get());
198 }
199
200 // Link in the specified function.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000201 DenseSet<const GlobalValue *> FunctionToImport;
202 FunctionToImport.insert(F);
203 if (L.linkInModule(*M, Linker::Flags::None, Index.get(),
204 &FunctionToImport))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000205 return false;
206 }
207 return true;
208}
209
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000210static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000211 const cl::list<std::string> &Files,
Artem Belevich020d4fb2015-09-01 17:55:55 +0000212 unsigned Flags) {
213 // Filter out flags that don't apply to the first file we load.
214 unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000215 for (const auto &File : Files) {
216 std::unique_ptr<Module> M = loadFile(argv0, File, Context);
217 if (!M.get()) {
218 errs() << argv0 << ": error loading file '" << File << "'\n";
219 return false;
220 }
221
222 if (verifyModule(*M, &errs())) {
223 errs() << argv0 << ": " << File << ": error: input module is broken!\n";
224 return false;
225 }
226
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000227 // If a function index is supplied, load it so linkInModule can treat
228 // local functions/variables as exported and promote if necessary.
229 std::unique_ptr<FunctionInfoIndex> Index;
230 if (!FunctionIndex.empty()) {
Teresa Johnson6b923162015-11-23 19:19:11 +0000231 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
Mehdi Amini9abe1082015-12-03 02:37:23 +0000232 llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000233 std::error_code EC = IndexOrErr.getError();
234 if (EC) {
235 errs() << EC.message() << '\n';
236 return false;
237 }
238 Index = std::move(IndexOrErr.get());
239 }
240
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000241 if (Verbose)
242 errs() << "Linking in '" << File << "'\n";
243
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000244 if (L.linkInModule(*M, ApplicableFlags, Index.get()))
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000245 return false;
Artem Belevich020d4fb2015-09-01 17:55:55 +0000246 // All linker flags apply to linking of subsequent files.
247 ApplicableFlags = Flags;
Teresa Johnson5bc88be2015-11-21 00:35:38 +0000248
249 // If requested for testing, preserve modules by releasing them from
250 // the unique_ptr before the are freed. This can help catch any
251 // cross-module references from e.g. unneeded metadata references
252 // that aren't properly set to null but instead mapped to the source
253 // module version. The bitcode writer will assert if it finds any such
254 // cross-module references.
255 if (PreserveModules)
256 M.release();
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000257 }
258
259 return true;
260}
261
Chris Lattner9d810e02001-10-13 07:06:23 +0000262int main(int argc, char **argv) {
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000263 // Print a stack trace if we signal out.
Chris Lattner27936992007-05-06 05:13:17 +0000264 sys::PrintStackTraceOnErrorSignal();
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000265 PrettyStackTraceProgram X(argc, argv);
Andrew Trickdc073ad2013-09-18 23:31:10 +0000266
Owen Anderson19251ec2009-07-15 22:16:10 +0000267 LLVMContext &Context = getGlobalContext();
Chris Lattnere3fc2d12009-03-06 05:34:10 +0000268 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
269 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
Chris Lattner9d810e02001-10-13 07:06:23 +0000270
Rafael Espindola957eae22014-10-23 19:40:45 +0000271 auto Composite = make_unique<Module>("llvm-link", Context);
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000272 Linker L(*Composite, diagnosticHandler);
Rafael Espindola957eae22014-10-23 19:40:45 +0000273
Artem Belevich020d4fb2015-09-01 17:55:55 +0000274 unsigned Flags = Linker::Flags::None;
275 if (Internalize)
276 Flags |= Linker::Flags::InternalizeLinkedSymbols;
277 if (OnlyNeeded)
278 Flags |= Linker::Flags::LinkOnlyNeeded;
279
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000280 // First add all the regular input files
Artem Belevich020d4fb2015-09-01 17:55:55 +0000281 if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000282 return 1;
283
284 // Next the -override ones.
Artem Belevich020d4fb2015-09-01 17:55:55 +0000285 if (!linkFiles(argv[0], Context, L, OverridingInputs,
286 Flags | Linker::Flags::OverrideFromSrc))
Duncan P. N. Exon Smith0de129d2015-04-22 04:08:22 +0000287 return 1;
Reid Spencer996ec722004-12-30 05:36:08 +0000288
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000289 // Import any functions requested via -import
290 if (!importFunctions(argv[0], Context, L))
291 return 1;
292
Dan Gohman2b09de92009-09-15 15:35:07 +0000293 if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
Reid Spencer996ec722004-12-30 05:36:08 +0000294
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000295 std::error_code EC;
296 tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
297 if (EC) {
298 errs() << EC.message() << '\n';
Chris Lattnerabd17362009-08-23 02:56:05 +0000299 return 1;
300 }
Reid Spencer996ec722004-12-30 05:36:08 +0000301
Duncan P. N. Exon Smith46282822015-03-31 03:07:23 +0000302 if (verifyModule(*Composite, &errs())) {
303 errs() << argv[0] << ": error: linked module is broken!\n";
Chris Lattner27936992007-05-06 05:13:17 +0000304 return 1;
305 }
306
Dan Gohmanee051522009-07-16 15:30:09 +0000307 if (Verbose) errs() << "Writing bitcode...\n";
Dan Gohman2b09de92009-09-15 15:35:07 +0000308 if (OutputAssembly) {
Duncan P. N. Exon Smith8a7b84b2015-04-15 03:14:06 +0000309 Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
Dan Gohmana2233f22010-09-01 14:20:41 +0000310 } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
Duncan P. N. Exon Smith8a7b84b2015-04-15 03:14:06 +0000311 WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
Dan Gohman4cc73ba2010-08-20 01:12:13 +0000312
313 // Declare success.
314 Out.keep();
Chris Lattner27936992007-05-06 05:13:17 +0000315
Chris Lattner27936992007-05-06 05:13:17 +0000316 return 0;
Chris Lattner9d810e02001-10-13 07:06:23 +0000317}