1//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This utility may be invoked in the following manner:
10// llvm-link a.bc b.bc c.bc -o x.bc
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/BinaryFormat/Magic.h"
15#include "llvm/Bitcode/BitcodeReader.h"
16#include "llvm/Bitcode/BitcodeWriter.h"
17#include "llvm/IR/AutoUpgrade.h"
18#include "llvm/IR/DiagnosticInfo.h"
19#include "llvm/IR/DiagnosticPrinter.h"
20#include "llvm/IR/LLVMContext.h"
21#include "llvm/IR/Module.h"
22#include "llvm/IR/ModuleSummaryIndex.h"
23#include "llvm/IR/Verifier.h"
24#include "llvm/IRReader/IRReader.h"
25#include "llvm/Linker/Linker.h"
26#include "llvm/Object/Archive.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/InitLLVM.h"
30#include "llvm/Support/SourceMgr.h"
31#include "llvm/Support/SystemUtils.h"
32#include "llvm/Support/ToolOutputFile.h"
33#include "llvm/Support/WithColor.h"
34#include "llvm/Transforms/IPO/FunctionImport.h"
35#include "llvm/Transforms/IPO/Internalize.h"
36#include "llvm/Transforms/Utils/FunctionImportUtils.h"
37
38#include <memory>
39#include <utility>
40using namespace llvm;
41
42static cl::OptionCategory LinkCategory("Link Options");
43
44static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bitcode files>"),
46 cl::cat(LinkCategory));
47
48static cl::list<std::string> OverridingInputs(
49 "override", cl::value_desc("filename"),
50 cl::desc(
51 "input bitcode file which can override previously defined symbol(s)"),
52 cl::cat(LinkCategory));
53
54// Option to simulate function importing for testing. This enables using
55// llvm-link to simulate ThinLTO backend processes.
56static cl::list<std::string> Imports(
57 "import", cl::value_desc("function:filename"),
58 cl::desc("Pair of function name and filename, where function should be "
59 "imported from bitcode in filename"),
60 cl::cat(LinkCategory));
61
62// Option to support testing of function importing. The module summary
63// must be specified in the case were we request imports via the -import
64// option, as well as when compiling any module with functions that may be
65// exported (imported by a different llvm-link -import invocation), to ensure
66// consistent promotion and renaming of locals.
67static cl::opt<std::string>
68 SummaryIndex("summary-index", cl::desc("Module summary index filename"),
69 cl::init(Val: ""), cl::value_desc("filename"),
70 cl::cat(LinkCategory));
71
72static cl::opt<std::string>
73 OutputFilename("o", cl::desc("Override output filename"), cl::init(Val: "-"),
74 cl::value_desc("filename"), cl::cat(LinkCategory));
75
76static cl::opt<bool>
77 Internalize("internalize",
78 cl::desc("Internalize linked symbols - maintains existing "
79 "linkage for the first input and converts linkage in"
80 " all other inputs to `internal`"),
81 cl::cat(LinkCategory));
82
83static cl::opt<bool>
84 DisableDITypeMap("disable-debug-info-type-map",
85 cl::desc("Don't use a uniquing type map for debug info"),
86 cl::cat(LinkCategory));
87
88static cl::opt<bool> OnlyNeeded("only-needed",
89 cl::desc("Link only needed symbols"),
90 cl::cat(LinkCategory));
91
92static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
93 cl::cat(LinkCategory));
94
95static cl::opt<bool> DisableLazyLoad("disable-lazy-loading",
96 cl::desc("Disable lazy module loading"),
97 cl::cat(LinkCategory));
98
99static cl::opt<bool> OutputAssembly("S",
100 cl::desc("Write output as LLVM assembly"),
101 cl::Hidden, cl::cat(LinkCategory));
102
103static cl::opt<bool> Verbose("v",
104 cl::desc("Print information about actions taken"),
105 cl::cat(LinkCategory));
106
107static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as linked"),
108 cl::Hidden, cl::cat(LinkCategory));
109
110static cl::opt<bool> SuppressWarnings("suppress-warnings",
111 cl::desc("Suppress all linking warnings"),
112 cl::init(Val: false), cl::cat(LinkCategory));
113
114static cl::opt<bool> NoVerify("disable-verify",
115 cl::desc("Do not run the verifier"), cl::Hidden,
116 cl::cat(LinkCategory));
117
118static cl::opt<bool> IgnoreNonBitcode(
119 "ignore-non-bitcode",
120 cl::desc("Do not report an error for non-bitcode files in archives"),
121 cl::Hidden);
122
123static ExitOnError ExitOnErr;
124
125// Read the specified bitcode file in and return it. This routine searches the
126// link path for the specified file to try to find it...
127//
128static std::unique_ptr<Module> loadFile(const char *argv0,
129 std::unique_ptr<MemoryBuffer> Buffer,
130 LLVMContext &Context,
131 bool MaterializeMetadata = true) {
132 SMDiagnostic Err;
133 if (Verbose)
134 errs() << "Loading '" << Buffer->getBufferIdentifier() << "'\n";
135 std::unique_ptr<Module> Result;
136 if (DisableLazyLoad)
137 Result = parseIR(Buffer: *Buffer, Err, Context);
138 else
139 Result =
140 getLazyIRModule(Buffer: std::move(Buffer), Err, Context, ShouldLazyLoadMetadata: !MaterializeMetadata);
141
142 if (!Result) {
143 Err.print(ProgName: argv0, S&: errs());
144 return nullptr;
145 }
146
147 if (MaterializeMetadata) {
148 ExitOnErr(Result->materializeMetadata());
149 UpgradeDebugInfo(M&: *Result);
150 }
151
152 return Result;
153}
154
155static std::unique_ptr<Module> loadArFile(const char *Argv0,
156 std::unique_ptr<MemoryBuffer> Buffer,
157 LLVMContext &Context) {
158 std::unique_ptr<Module> Result(new Module("ArchiveModule", Context));
159 StringRef ArchiveName = Buffer->getBufferIdentifier();
160 if (Verbose)
161 errs() << "Reading library archive file '" << ArchiveName
162 << "' to memory\n";
163 Expected<std::unique_ptr<object::Archive>> ArchiveOrError =
164 object::Archive::create(Source: Buffer->getMemBufferRef());
165 if (!ArchiveOrError)
166 ExitOnErr(ArchiveOrError.takeError());
167
168 std::unique_ptr<object::Archive> Archive = std::move(ArchiveOrError.get());
169
170 Linker L(*Result);
171 Error Err = Error::success();
172 for (const object::Archive::Child &C : Archive->children(Err)) {
173 Expected<StringRef> Ename = C.getName();
174 if (Error E = Ename.takeError()) {
175 errs() << Argv0 << ": ";
176 WithColor::error() << " failed to read name of archive member"
177 << ArchiveName << "'\n";
178 return nullptr;
179 }
180 std::string ChildName = Ename.get().str();
181 if (Verbose)
182 errs() << "Parsing member '" << ChildName
183 << "' of archive library to module.\n";
184 SMDiagnostic ParseErr;
185 Expected<MemoryBufferRef> MemBuf = C.getMemoryBufferRef();
186 if (Error E = MemBuf.takeError()) {
187 errs() << Argv0 << ": ";
188 WithColor::error() << " loading memory for member '" << ChildName
189 << "' of archive library failed'" << ArchiveName
190 << "'\n";
191 return nullptr;
192 };
193
194 if (!isBitcode(BufPtr: reinterpret_cast<const unsigned char *>(
195 MemBuf.get().getBufferStart()),
196 BufEnd: reinterpret_cast<const unsigned char *>(
197 MemBuf.get().getBufferEnd()))) {
198 if (IgnoreNonBitcode)
199 continue;
200 errs() << Argv0 << ": ";
201 WithColor::error() << " member of archive is not a bitcode file: '"
202 << ChildName << "'\n";
203 return nullptr;
204 }
205
206 std::unique_ptr<Module> M;
207 if (DisableLazyLoad)
208 M = parseIR(Buffer: MemBuf.get(), Err&: ParseErr, Context);
209 else
210 M = getLazyIRModule(Buffer: MemoryBuffer::getMemBuffer(Ref: MemBuf.get(), RequiresNullTerminator: false),
211 Err&: ParseErr, Context);
212
213 if (!M) {
214 errs() << Argv0 << ": ";
215 WithColor::error() << " parsing member '" << ChildName
216 << "' of archive library failed'" << ArchiveName
217 << "'\n";
218 return nullptr;
219 }
220 if (Verbose)
221 errs() << "Linking member '" << ChildName << "' of archive library.\n";
222 if (L.linkInModule(Src: std::move(M)))
223 return nullptr;
224 } // end for each child
225 ExitOnErr(std::move(Err));
226 return Result;
227}
228
229namespace {
230
231/// Helper to load on demand a Module from file and cache it for subsequent
232/// queries during function importing.
233class ModuleLazyLoaderCache {
234 /// Cache of lazily loaded module for import.
235 StringMap<std::unique_ptr<Module>> ModuleMap;
236
237 /// Retrieve a Module from the cache or lazily load it on demand.
238 std::function<std::unique_ptr<Module>(const char *argv0,
239 const std::string &FileName)>
240 createLazyModule;
241
242public:
243 /// Create the loader, Module will be initialized in \p Context.
244 ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>(
245 const char *argv0, const std::string &FileName)>
246 createLazyModule)
247 : createLazyModule(std::move(createLazyModule)) {}
248
249 /// Retrieve a Module from the cache or lazily load it on demand.
250 Module &operator()(const char *argv0, const std::string &FileName);
251
252 std::unique_ptr<Module> takeModule(const std::string &FileName) {
253 auto I = ModuleMap.find(Key: FileName);
254 assert(I != ModuleMap.end());
255 std::unique_ptr<Module> Ret = std::move(I->second);
256 ModuleMap.erase(I);
257 return Ret;
258 }
259};
260
261// Get a Module for \p FileName from the cache, or load it lazily.
262Module &ModuleLazyLoaderCache::operator()(const char *argv0,
263 const std::string &Identifier) {
264 auto &Module = ModuleMap[Identifier];
265 if (!Module) {
266 Module = createLazyModule(argv0, Identifier);
267 assert(Module && "Failed to create lazy module!");
268 }
269 return *Module;
270}
271} // anonymous namespace
272
273namespace {
274struct LLVMLinkDiagnosticHandler : public DiagnosticHandler {
275 bool handleDiagnostics(const DiagnosticInfo &DI) override {
276 unsigned Severity = DI.getSeverity();
277 switch (Severity) {
278 case DS_Error:
279 WithColor::error();
280 break;
281 case DS_Warning:
282 if (SuppressWarnings)
283 return true;
284 WithColor::warning();
285 break;
286 case DS_Remark:
287 case DS_Note:
288 llvm_unreachable("Only expecting warnings and errors");
289 }
290
291 DiagnosticPrinterRawOStream DP(errs());
292 DI.print(DP);
293 errs() << '\n';
294 return true;
295 }
296};
297} // namespace
298
299/// Import any functions requested via the -import option.
300static bool importFunctions(const char *argv0, Module &DestModule) {
301 if (SummaryIndex.empty())
302 return true;
303 std::unique_ptr<ModuleSummaryIndex> Index =
304 ExitOnErr(llvm::getModuleSummaryIndexForFile(Path: SummaryIndex));
305
306 // Map of Module -> List of globals to import from the Module
307 FunctionImporter::ImportIDTable ImportIDs;
308 FunctionImporter::ImportMapTy ImportList(ImportIDs);
309
310 auto ModuleLoader = [&DestModule](const char *argv0,
311 const std::string &Identifier) {
312 std::unique_ptr<MemoryBuffer> Buffer = ExitOnErr(errorOrToExpected(
313 EO: MemoryBuffer::getFileOrSTDIN(Filename: Identifier, /*IsText=*/true)));
314 return loadFile(argv0, Buffer: std::move(Buffer), Context&: DestModule.getContext(), MaterializeMetadata: false);
315 };
316
317 ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
318 // Owns the filename strings used to key into the ImportList. Normally this is
319 // constructed from the index and the strings are owned by the index, however,
320 // since we are synthesizing this data structure from options we need a cache
321 // to own those strings.
322 StringSet<> FileNameStringCache;
323 for (const auto &Import : Imports) {
324 // Identify the requested function and its bitcode source file.
325 size_t Idx = Import.find(c: ':');
326 if (Idx == std::string::npos) {
327 errs() << "Import parameter bad format: " << Import << "\n";
328 return false;
329 }
330 std::string FunctionName = Import.substr(pos: 0, n: Idx);
331 std::string FileName = Import.substr(pos: Idx + 1, n: std::string::npos);
332
333 // Load the specified source module.
334 auto &SrcModule = ModuleLoaderCache(argv0, FileName);
335
336 if (!NoVerify && verifyModule(M: SrcModule, OS: &errs())) {
337 errs() << argv0 << ": " << FileName;
338 WithColor::error() << "input module is broken!\n";
339 return false;
340 }
341
342 Function *F = SrcModule.getFunction(Name: FunctionName);
343 if (!F) {
344 errs() << "Ignoring import request for non-existent function "
345 << FunctionName << " from " << FileName << "\n";
346 continue;
347 }
348 // We cannot import weak_any functions without possibly affecting the
349 // order they are seen and selected by the linker, changing program
350 // semantics.
351 if (F->hasWeakAnyLinkage()) {
352 errs() << "Ignoring import request for weak-any function " << FunctionName
353 << " from " << FileName << "\n";
354 continue;
355 }
356
357 if (Verbose)
358 errs() << "Importing " << FunctionName << " from " << FileName << "\n";
359
360 // `-import` specifies the `<filename,function-name>` pairs to import as
361 // definition, so make the import type definition directly.
362 // FIXME: A follow-up patch should add test coverage for import declaration
363 // in `llvm-link` CLI (e.g., by introducing a new command line option).
364 const auto GUID = F->getGUIDOrFallback();
365 ImportList.addDefinition(
366 FromModule: FileNameStringCache.insert(key: FileName).first->getKey(), GUID);
367 }
368 auto CachedModuleLoader = [&](StringRef Identifier) {
369 return ModuleLoaderCache.takeModule(FileName: std::string(Identifier));
370 };
371 FunctionImporter Importer(*Index, CachedModuleLoader,
372 /*ClearDSOLocalOnDeclarations=*/false);
373 ExitOnErr(Importer.importFunctions(M&: DestModule, ImportList));
374
375 return true;
376}
377
378static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
379 const cl::list<std::string> &Files, unsigned Flags) {
380 // Filter out flags that don't apply to the first file we load.
381 unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
382 // Similar to some flags, internalization doesn't apply to the first file.
383 bool InternalizeLinkedSymbols = false;
384 for (const auto &File : Files) {
385 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename: File, /*IsText=*/true);
386
387 // When we encounter a missing file, make sure we expose its name.
388 if (auto EC = BufferOrErr.getError())
389 if (EC == std::errc::no_such_file_or_directory)
390 ExitOnErr(createStringError(EC, Fmt: "No such file or directory: '%s'",
391 Vals: File.c_str()));
392
393 std::unique_ptr<MemoryBuffer> Buffer =
394 ExitOnErr(errorOrToExpected(EO: std::move(BufferOrErr)));
395
396 std::unique_ptr<Module> M =
397 identify_magic(magic: Buffer->getBuffer()) == file_magic::archive
398 ? loadArFile(Argv0: argv0, Buffer: std::move(Buffer), Context)
399 : loadFile(argv0, Buffer: std::move(Buffer), Context);
400 if (!M) {
401 errs() << argv0 << ": ";
402 WithColor::error() << " loading file '" << File << "'\n";
403 return false;
404 }
405
406 // Note that when ODR merging types cannot verify input files in here When
407 // doing that debug metadata in the src module might already be pointing to
408 // the destination.
409 if (DisableDITypeMap && !NoVerify && verifyModule(M: *M, OS: &errs())) {
410 errs() << argv0 << ": " << File << ": ";
411 WithColor::error() << "input module is broken!\n";
412 return false;
413 }
414
415 // If a module summary index is supplied, load it so linkInModule can treat
416 // local functions/variables as exported and promote if necessary.
417 if (!SummaryIndex.empty()) {
418 std::unique_ptr<ModuleSummaryIndex> Index =
419 ExitOnErr(llvm::getModuleSummaryIndexForFile(Path: SummaryIndex));
420
421 // Conservatively mark all internal values as promoted, since this tool
422 // does not do the ThinLink that would normally determine what values to
423 // promote.
424 for (auto &I : *Index) {
425 for (auto &S : I.second.getSummaryList()) {
426 if (GlobalValue::isLocalLinkage(Linkage: S->linkage()))
427 S->setExternalLinkageForTest();
428 }
429 }
430
431 // Promotion
432 renameModuleForThinLTO(M&: *M, Index: *Index,
433 /*ClearDSOLocalOnDeclarations=*/false);
434 }
435
436 if (Verbose)
437 errs() << "Linking in '" << File << "'\n";
438
439 bool Err = false;
440 if (InternalizeLinkedSymbols) {
441 Err = L.linkInModule(
442 Src: std::move(M), Flags: ApplicableFlags, InternalizeCallback: [](Module &M, const StringSet<> &GVS) {
443 internalizeModule(TheModule&: M, MustPreserveGV: [&GVS](const GlobalValue &GV) {
444 return !GV.hasName() || (GVS.count(Key: GV.getName()) == 0);
445 });
446 });
447 } else {
448 Err = L.linkInModule(Src: std::move(M), Flags: ApplicableFlags);
449 }
450
451 if (Err)
452 return false;
453
454 // Internalization applies to linking of subsequent files.
455 InternalizeLinkedSymbols = Internalize;
456
457 // All linker flags apply to linking of subsequent files.
458 ApplicableFlags = Flags;
459 }
460
461 return true;
462}
463
464int main(int argc, char **argv) {
465 InitLLVM X(argc, argv);
466 ExitOnErr.setBanner(std::string(argv[0]) + ": ");
467
468 cl::HideUnrelatedOptions(Categories: {&LinkCategory, &getColorCategory()});
469 LLVMContext Context;
470 cl::parseCommandLineOptions(Context&: Context.getLibraryOptions(), Args: ArrayRef(argv, argc),
471 Overview: "llvm linker\n");
472
473 Context.setDiagnosticHandler(DH: std::make_unique<LLVMLinkDiagnosticHandler>(),
474 RespectFilters: true);
475
476 if (!DisableDITypeMap)
477 Context.enableDebugTypeODRUniquing();
478
479 auto Composite = std::make_unique<Module>(args: "llvm-link", args&: Context);
480 Linker L(*Composite);
481
482 unsigned Flags = Linker::Flags::None;
483 if (OnlyNeeded)
484 Flags |= Linker::Flags::LinkOnlyNeeded;
485
486 // First add all the regular input files
487 if (!linkFiles(argv0: argv[0], Context, L, Files: InputFilenames, Flags))
488 return 1;
489
490 // Next the -override ones.
491 if (!linkFiles(argv0: argv[0], Context, L, Files: OverridingInputs,
492 Flags: Flags | Linker::Flags::OverrideFromSrc))
493 return 1;
494
495 // Import any functions requested via -import
496 if (!importFunctions(argv0: argv[0], DestModule&: *Composite))
497 return 1;
498
499 if (DumpAsm)
500 errs() << "Here's the assembly:\n" << *Composite;
501
502 std::error_code EC;
503 ToolOutputFile Out(OutputFilename, EC,
504 OutputAssembly ? sys::fs::OF_TextWithCRLF
505 : sys::fs::OF_None);
506 if (EC) {
507 WithColor::error() << EC.message() << '\n';
508 return 1;
509 }
510
511 if (!NoVerify && verifyModule(M: *Composite, OS: &errs())) {
512 errs() << argv[0] << ": ";
513 WithColor::error() << "linked module is broken!\n";
514 return 1;
515 }
516
517 if (Verbose)
518 errs() << "Writing bitcode...\n";
519 if (OutputAssembly) {
520 Composite->renumberMetadataForAssembly();
521 Composite->print(OS&: Out.os(), AAW: nullptr, /* ShouldPreserveUseListOrder */ false);
522 } else if (Force || !CheckBitcodeOutputToConsole(stream_to_check&: Out.os())) {
523 WriteBitcodeToFile(M: *Composite, Out&: Out.os(),
524 /* ShouldPreserveUseListOrder */ true);
525 }
526
527 // Declare success.
528 Out.keep();
529
530 return 0;
531}
532