1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility may be invoked in the following manner:
11 // llvm-link a.bc b.bc c.bc -o x.bc
13 //===----------------------------------------------------------------------===//
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"
39 static cl::list<std::string>
40 InputFilenames(cl::Positional, cl::OneOrMore,
41 cl::desc("<input bitcode files>"));
43 static cl::list<std::string> OverridingInputs(
44 "override", cl::ZeroOrMore, cl::value_desc("filename"),
46 "input bitcode file which can override previously defined symbol(s)"));
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"));
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"),
63 cl::value_desc("filename"));
65 static cl::opt<std::string>
66 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
67 cl::value_desc("filename"));
70 Internalize("internalize", cl::desc("Internalize linked symbols"));
73 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
76 Force("f", cl::desc("Enable binary output on terminals"));
80 cl::desc("Write output as LLVM assembly"), cl::Hidden);
83 Verbose("v", cl::desc("Print information about actions taken"));
86 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
89 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
93 PreserveModules("preserve-modules",
94 cl::desc("Preserve linked modules for testing"));
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);
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);
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...
109 static std::unique_ptr<Module>
110 loadFile(const char *argv0, const std::string &FN, LLVMContext &Context) {
112 if (Verbose) errs() << "Loading '" << FN << "'\n";
113 std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context);
115 Err.print(argv0, errs());
117 Result->materializeMetadata();
118 UpgradeDebugInfo(*Result);
123 static void diagnosticHandler(const DiagnosticInfo &DI) {
124 unsigned Severity = DI.getSeverity();
130 if (SuppressWarnings)
132 errs() << "WARNING: ";
136 llvm_unreachable("Only expecting warnings and errors");
139 DiagnosticPrinterRawOStream DP(errs());
144 static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) {
145 diagnosticHandler(DI);
148 /// Import any functions requested via the -import option.
149 static bool importFunctions(const char *argv0, LLVMContext &Context,
151 for (const auto &Import : Imports) {
152 // Identify the requested function and its bitcode source file.
153 size_t Idx = Import.find(':');
154 if (Idx == std::string::npos) {
155 errs() << "Import parameter bad format: " << Import << "\n";
158 std::string FunctionName = Import.substr(0, Idx);
159 std::string FileName = Import.substr(Idx + 1, std::string::npos);
161 // Load the specified source module.
162 std::unique_ptr<Module> M = loadFile(argv0, FileName, Context);
164 errs() << argv0 << ": error loading file '" << FileName << "'\n";
168 if (verifyModule(*M, &errs())) {
169 errs() << argv0 << ": " << FileName
170 << ": error: input module is broken!\n";
174 Function *F = M->getFunction(FunctionName);
176 errs() << "Ignoring import request for non-existent function "
177 << FunctionName << " from " << FileName << "\n";
180 // We cannot import weak_any functions without possibly affecting the
181 // order they are seen and selected by the linker, changing program
183 if (F->hasWeakAnyLinkage()) {
184 errs() << "Ignoring import request for weak-any function " << FunctionName
185 << " from " << FileName << "\n";
190 errs() << "Importing " << FunctionName << " from " << FileName << "\n";
192 std::unique_ptr<FunctionInfoIndex> Index;
193 if (!FunctionIndex.empty()) {
194 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
195 llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
196 std::error_code EC = IndexOrErr.getError();
198 errs() << EC.message() << '\n';
201 Index = std::move(IndexOrErr.get());
204 // Link in the specified function.
205 DenseSet<const GlobalValue *> FunctionsToImport;
206 FunctionsToImport.insert(F);
207 if (L.linkInModule(*M, Linker::Flags::None, Index.get(),
214 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
215 const cl::list<std::string> &Files,
217 // Filter out flags that don't apply to the first file we load.
218 unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
219 for (const auto &File : Files) {
220 std::unique_ptr<Module> M = loadFile(argv0, File, Context);
222 errs() << argv0 << ": error loading file '" << File << "'\n";
226 if (verifyModule(*M, &errs())) {
227 errs() << argv0 << ": " << File << ": error: input module is broken!\n";
231 // If a function index is supplied, load it so linkInModule can treat
232 // local functions/variables as exported and promote if necessary.
233 std::unique_ptr<FunctionInfoIndex> Index;
234 if (!FunctionIndex.empty()) {
235 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
236 llvm::getFunctionIndexForFile(FunctionIndex, diagnosticHandler);
237 std::error_code EC = IndexOrErr.getError();
239 errs() << EC.message() << '\n';
242 Index = std::move(IndexOrErr.get());
246 errs() << "Linking in '" << File << "'\n";
248 if (L.linkInModule(*M, ApplicableFlags, Index.get()))
250 // All linker flags apply to linking of subsequent files.
251 ApplicableFlags = Flags;
253 // If requested for testing, preserve modules by releasing them from
254 // the unique_ptr before the are freed. This can help catch any
255 // cross-module references from e.g. unneeded metadata references
256 // that aren't properly set to null but instead mapped to the source
257 // module version. The bitcode writer will assert if it finds any such
258 // cross-module references.
266 int main(int argc, char **argv) {
267 // Print a stack trace if we signal out.
268 sys::PrintStackTraceOnErrorSignal();
269 PrettyStackTraceProgram X(argc, argv);
271 LLVMContext &Context = getGlobalContext();
272 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
274 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
275 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
277 auto Composite = make_unique<Module>("llvm-link", Context);
278 Linker L(*Composite);
280 unsigned Flags = Linker::Flags::None;
282 Flags |= Linker::Flags::InternalizeLinkedSymbols;
284 Flags |= Linker::Flags::LinkOnlyNeeded;
286 // First add all the regular input files
287 if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
290 // Next the -override ones.
291 if (!linkFiles(argv[0], Context, L, OverridingInputs,
292 Flags | Linker::Flags::OverrideFromSrc))
295 // Import any functions requested via -import
296 if (!importFunctions(argv[0], Context, L))
299 if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
302 tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
304 errs() << EC.message() << '\n';
308 if (verifyModule(*Composite, &errs())) {
309 errs() << argv[0] << ": error: linked module is broken!\n";
313 if (Verbose) errs() << "Writing bitcode...\n";
314 if (OutputAssembly) {
315 Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
316 } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
317 WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);