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