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/ADT/STLExtras.h"
16 #include "llvm/Bitcode/ReaderWriter.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/ModuleSummaryIndexObjectFile.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 "llvm/Transforms/Utils/FunctionImportUtils.h"
37 
38 #include <memory>
39 using namespace llvm;
40 
41 static cl::list<std::string>
42 InputFilenames(cl::Positional, cl::OneOrMore,
43                cl::desc("<input bitcode files>"));
44 
45 static cl::list<std::string> OverridingInputs(
46     "override", cl::ZeroOrMore, cl::value_desc("filename"),
47     cl::desc(
48         "input bitcode file which can override previously defined symbol(s)"));
49 
50 // Option to simulate function importing for testing. This enables using
51 // llvm-link to simulate ThinLTO backend processes.
52 static cl::list<std::string> Imports(
53     "import", cl::ZeroOrMore, cl::value_desc("function:filename"),
54     cl::desc("Pair of function name and filename, where function should be "
55              "imported from bitcode in filename"));
56 
57 // Option to support testing of function importing. The module summary
58 // must be specified in the case were we request imports via the -import
59 // option, as well as when compiling any module with functions that may be
60 // exported (imported by a different llvm-link -import invocation), to ensure
61 // consistent promotion and renaming of locals.
62 static cl::opt<std::string>
63     SummaryIndex("summary-index", cl::desc("Module summary index filename"),
64                  cl::init(""), cl::value_desc("filename"));
65 
66 static cl::opt<std::string>
67 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
68                cl::value_desc("filename"));
69 
70 static cl::opt<bool>
71 Internalize("internalize", cl::desc("Internalize linked symbols"));
72 
73 static cl::opt<bool>
74 OnlyNeeded("only-needed", cl::desc("Link only needed symbols"));
75 
76 static cl::opt<bool>
77 Force("f", cl::desc("Enable binary output on terminals"));
78 
79 static cl::opt<bool>
80 OutputAssembly("S",
81          cl::desc("Write output as LLVM assembly"), cl::Hidden);
82 
83 static cl::opt<bool>
84 Verbose("v", cl::desc("Print information about actions taken"));
85 
86 static cl::opt<bool>
87 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
88 
89 static cl::opt<bool>
90 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
91                  cl::init(false));
92 
93 static cl::opt<bool> PreserveBitcodeUseListOrder(
94     "preserve-bc-uselistorder",
95     cl::desc("Preserve use-list order when writing LLVM bitcode."),
96     cl::init(true), cl::Hidden);
97 
98 static cl::opt<bool> PreserveAssemblyUseListOrder(
99     "preserve-ll-uselistorder",
100     cl::desc("Preserve use-list order when writing LLVM assembly."),
101     cl::init(false), cl::Hidden);
102 
103 // Read the specified bitcode file in and return it. This routine searches the
104 // link path for the specified file to try to find it...
105 //
106 static std::unique_ptr<Module> loadFile(const char *argv0,
107                                         const std::string &FN,
108                                         LLVMContext &Context,
109                                         bool MaterializeMetadata = true) {
110   SMDiagnostic Err;
111   if (Verbose) errs() << "Loading '" << FN << "'\n";
112   std::unique_ptr<Module> Result =
113       getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata);
114   if (!Result) {
115     Err.print(argv0, errs());
116     return nullptr;
117   }
118 
119   if (MaterializeMetadata) {
120     Result->materializeMetadata();
121     UpgradeDebugInfo(*Result);
122   }
123 
124   return Result;
125 }
126 
127 namespace {
128 
129 /// Helper to load on demand a Module from file and cache it for subsequent
130 /// queries during function importing.
131 class ModuleLazyLoaderCache {
132   /// Cache of lazily loaded module for import.
133   StringMap<std::unique_ptr<Module>> ModuleMap;
134 
135   /// Retrieve a Module from the cache or lazily load it on demand.
136   std::function<std::unique_ptr<Module>(const char *argv0,
137                                         const std::string &FileName)>
138       createLazyModule;
139 
140 public:
141   /// Create the loader, Module will be initialized in \p Context.
142   ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>(
143                             const char *argv0, const std::string &FileName)>
144                             createLazyModule)
145       : createLazyModule(createLazyModule) {}
146 
147   /// Retrieve a Module from the cache or lazily load it on demand.
148   Module &operator()(const char *argv0, const std::string &FileName);
149 
150   std::unique_ptr<Module> takeModule(const std::string &FileName) {
151     auto I = ModuleMap.find(FileName);
152     assert(I != ModuleMap.end());
153     std::unique_ptr<Module> Ret = std::move(I->second);
154     ModuleMap.erase(I);
155     return Ret;
156   }
157 };
158 
159 // Get a Module for \p FileName from the cache, or load it lazily.
160 Module &ModuleLazyLoaderCache::operator()(const char *argv0,
161                                           const std::string &Identifier) {
162   auto &Module = ModuleMap[Identifier];
163   if (!Module)
164     Module = createLazyModule(argv0, Identifier);
165   return *Module;
166 }
167 } // anonymous namespace
168 
169 static void diagnosticHandler(const DiagnosticInfo &DI) {
170   unsigned Severity = DI.getSeverity();
171   switch (Severity) {
172   case DS_Error:
173     errs() << "ERROR: ";
174     break;
175   case DS_Warning:
176     if (SuppressWarnings)
177       return;
178     errs() << "WARNING: ";
179     break;
180   case DS_Remark:
181   case DS_Note:
182     llvm_unreachable("Only expecting warnings and errors");
183   }
184 
185   DiagnosticPrinterRawOStream DP(errs());
186   DI.print(DP);
187   errs() << '\n';
188 }
189 
190 static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) {
191   diagnosticHandler(DI);
192 }
193 
194 /// Import any functions requested via the -import option.
195 static bool importFunctions(const char *argv0, LLVMContext &Context,
196                             Linker &L) {
197   if (SummaryIndex.empty())
198     return true;
199   ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
200       llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler);
201   std::error_code EC = IndexOrErr.getError();
202   if (EC) {
203     errs() << EC.message() << '\n';
204     return false;
205   }
206   auto Index = std::move(IndexOrErr.get());
207 
208   // Map of Module -> List of globals to import from the Module
209   std::map<StringRef, DenseSet<const GlobalValue *>> ModuleToGlobalsToImportMap;
210   auto ModuleLoader = [&Context](const char *argv0,
211                                  const std::string &Identifier) {
212     return loadFile(argv0, Identifier, Context, false);
213   };
214   ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
215   for (const auto &Import : Imports) {
216     // Identify the requested function and its bitcode source file.
217     size_t Idx = Import.find(':');
218     if (Idx == std::string::npos) {
219       errs() << "Import parameter bad format: " << Import << "\n";
220       return false;
221     }
222     std::string FunctionName = Import.substr(0, Idx);
223     std::string FileName = Import.substr(Idx + 1, std::string::npos);
224 
225     // Load the specified source module.
226     auto &SrcModule = ModuleLoaderCache(argv0, FileName);
227 
228     if (verifyModule(SrcModule, &errs())) {
229       errs() << argv0 << ": " << FileName
230              << ": error: input module is broken!\n";
231       return false;
232     }
233 
234     Function *F = SrcModule.getFunction(FunctionName);
235     if (!F) {
236       errs() << "Ignoring import request for non-existent function "
237              << FunctionName << " from " << FileName << "\n";
238       continue;
239     }
240     // We cannot import weak_any functions without possibly affecting the
241     // order they are seen and selected by the linker, changing program
242     // semantics.
243     if (F->hasWeakAnyLinkage()) {
244       errs() << "Ignoring import request for weak-any function " << FunctionName
245              << " from " << FileName << "\n";
246       continue;
247     }
248 
249     if (Verbose)
250       errs() << "Importing " << FunctionName << " from " << FileName << "\n";
251 
252     auto &Entry = ModuleToGlobalsToImportMap[SrcModule.getModuleIdentifier()];
253     Entry.insert(F);
254 
255     F->materialize();
256   }
257 
258   // Do the actual import of globals now, one Module at a time
259   for (auto &GlobalsToImportPerModule : ModuleToGlobalsToImportMap) {
260     // Get the module for the import
261     auto &GlobalsToImport = GlobalsToImportPerModule.second;
262     std::unique_ptr<Module> SrcModule =
263         ModuleLoaderCache.takeModule(GlobalsToImportPerModule.first);
264     assert(&Context == &SrcModule->getContext() && "Context mismatch");
265 
266     // If modules were created with lazy metadata loading, materialize it
267     // now, before linking it (otherwise this will be a noop).
268     SrcModule->materializeMetadata();
269     UpgradeDebugInfo(*SrcModule);
270 
271     // Linkage Promotion and renaming
272     if (renameModuleForThinLTO(*SrcModule, *Index, &GlobalsToImport))
273       return true;
274 
275     if (L.linkInModule(std::move(SrcModule), Linker::Flags::None,
276                        &GlobalsToImport))
277       return false;
278   }
279 
280   return true;
281 }
282 
283 static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
284                       const cl::list<std::string> &Files,
285                       unsigned Flags) {
286   // Filter out flags that don't apply to the first file we load.
287   unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc;
288   for (const auto &File : Files) {
289     std::unique_ptr<Module> M = loadFile(argv0, File, Context);
290     if (!M.get()) {
291       errs() << argv0 << ": error loading file '" << File << "'\n";
292       return false;
293     }
294 
295     if (verifyModule(*M, &errs())) {
296       errs() << argv0 << ": " << File << ": error: input module is broken!\n";
297       return false;
298     }
299 
300     // If a module summary index is supplied, load it so linkInModule can treat
301     // local functions/variables as exported and promote if necessary.
302     if (!SummaryIndex.empty()) {
303       ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
304           llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler);
305       std::error_code EC = IndexOrErr.getError();
306       if (EC) {
307         errs() << EC.message() << '\n';
308         return false;
309       }
310       auto Index = std::move(IndexOrErr.get());
311 
312       // Promotion
313       if (renameModuleForThinLTO(*M, *Index))
314         return true;
315     }
316 
317     if (Verbose)
318       errs() << "Linking in '" << File << "'\n";
319 
320     if (L.linkInModule(std::move(M), ApplicableFlags))
321       return false;
322     // All linker flags apply to linking of subsequent files.
323     ApplicableFlags = Flags;
324   }
325 
326   return true;
327 }
328 
329 int main(int argc, char **argv) {
330   // Print a stack trace if we signal out.
331   sys::PrintStackTraceOnErrorSignal();
332   PrettyStackTraceProgram X(argc, argv);
333 
334   LLVMContext &Context = getGlobalContext();
335   Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
336 
337   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
338   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
339 
340   auto Composite = make_unique<Module>("llvm-link", Context);
341   Linker L(*Composite);
342 
343   unsigned Flags = Linker::Flags::None;
344   if (Internalize)
345     Flags |= Linker::Flags::InternalizeLinkedSymbols;
346   if (OnlyNeeded)
347     Flags |= Linker::Flags::LinkOnlyNeeded;
348 
349   // First add all the regular input files
350   if (!linkFiles(argv[0], Context, L, InputFilenames, Flags))
351     return 1;
352 
353   // Next the -override ones.
354   if (!linkFiles(argv[0], Context, L, OverridingInputs,
355                  Flags | Linker::Flags::OverrideFromSrc))
356     return 1;
357 
358   // Import any functions requested via -import
359   if (!importFunctions(argv[0], Context, L))
360     return 1;
361 
362   if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
363 
364   std::error_code EC;
365   tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
366   if (EC) {
367     errs() << EC.message() << '\n';
368     return 1;
369   }
370 
371   if (verifyModule(*Composite, &errs())) {
372     errs() << argv[0] << ": error: linked module is broken!\n";
373     return 1;
374   }
375 
376   if (Verbose) errs() << "Writing bitcode...\n";
377   if (OutputAssembly) {
378     Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
379   } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
380     WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
381 
382   // Declare success.
383   Out.keep();
384 
385   return 0;
386 }
387