1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
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 file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LinkDiagnosticInfo.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Linker/Linker.h"
21 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
22 using namespace llvm;
23 
24 namespace {
25 
26 /// This is an implementation class for the LinkModules function, which is the
27 /// entrypoint for this file.
28 class ModuleLinker {
29   IRMover &Mover;
30   std::unique_ptr<Module> SrcM;
31 
32   SetVector<GlobalValue *> ValuesToLink;
33   StringSet<> Internalize;
34 
35   /// For symbol clashes, prefer those from Src.
36   unsigned Flags;
37 
38   /// Functions to import from source module, all other functions are
39   /// imported as declarations instead of definitions.
40   DenseSet<const GlobalValue *> *GlobalsToImport;
41 
42   /// Association between metadata value id and temporary metadata that
43   /// remains unmapped after function importing. Saved during function
44   /// importing and consumed during the metadata linking postpass.
45   DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
46 
47   /// Used as the callback for lazy linking.
48   /// The mover has just hit GV and we have to decide if it, and other members
49   /// of the same comdat, should be linked. Every member to be linked is passed
50   /// to Add.
51   void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
52 
53   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
54   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
55   bool shouldInternalizeLinkedSymbols() {
56     return Flags & Linker::InternalizeLinkedSymbols;
57   }
58 
59   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
60                             const GlobalValue &Src);
61 
62   /// Should we have mover and linker error diag info?
63   bool emitError(const Twine &Message) {
64     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
65     return true;
66   }
67 
68   bool getComdatLeader(Module &M, StringRef ComdatName,
69                        const GlobalVariable *&GVar);
70   bool computeResultingSelectionKind(StringRef ComdatName,
71                                      Comdat::SelectionKind Src,
72                                      Comdat::SelectionKind Dst,
73                                      Comdat::SelectionKind &Result,
74                                      bool &LinkFromSrc);
75   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
76       ComdatsChosen;
77   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
78                        bool &LinkFromSrc);
79   // Keep track of the lazy linked global members of each comdat in source.
80   DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
81 
82   /// Given a global in the source module, return the global in the
83   /// destination module that is being linked to, if any.
84   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
85     Module &DstM = Mover.getModule();
86     // If the source has no name it can't link.  If it has local linkage,
87     // there is no name match-up going on.
88     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
89       return nullptr;
90 
91     // Otherwise see if we have a match in the destination module's symtab.
92     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
93     if (!DGV)
94       return nullptr;
95 
96     // If we found a global with the same name in the dest module, but it has
97     // internal linkage, we are really not doing any linkage here.
98     if (DGV->hasLocalLinkage())
99       return nullptr;
100 
101     // Otherwise, we do in fact link to the destination global.
102     return DGV;
103   }
104 
105   /// Drop GV if it is a member of a comdat that we are dropping.
106   /// This can happen with COFF's largest selection kind.
107   void dropReplacedComdat(GlobalValue &GV,
108                           const DenseSet<const Comdat *> &ReplacedDstComdats);
109 
110   bool linkIfNeeded(GlobalValue &GV);
111 
112   /// Helper method to check if we are importing from the current source
113   /// module.
114   bool isPerformingImport() const { return GlobalsToImport != nullptr; }
115 
116   /// If we are importing from the source module, checks if we should
117   /// import SGV as a definition, otherwise import as a declaration.
118   bool doImportAsDefinition(const GlobalValue *SGV);
119 
120 public:
121   ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
122                DenseSet<const GlobalValue *> *GlobalsToImport = nullptr,
123                DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
124       : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
125         GlobalsToImport(GlobalsToImport), ValIDToTempMDMap(ValIDToTempMDMap) {}
126 
127   bool run();
128 };
129 }
130 
131 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
132   if (!isPerformingImport())
133     return false;
134   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
135                                                               GlobalsToImport);
136 }
137 
138 static GlobalValue::VisibilityTypes
139 getMinVisibility(GlobalValue::VisibilityTypes A,
140                  GlobalValue::VisibilityTypes B) {
141   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
142     return GlobalValue::HiddenVisibility;
143   if (A == GlobalValue::ProtectedVisibility ||
144       B == GlobalValue::ProtectedVisibility)
145     return GlobalValue::ProtectedVisibility;
146   return GlobalValue::DefaultVisibility;
147 }
148 
149 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
150                                    const GlobalVariable *&GVar) {
151   const GlobalValue *GVal = M.getNamedValue(ComdatName);
152   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
153     GVal = GA->getBaseObject();
154     if (!GVal)
155       // We cannot resolve the size of the aliasee yet.
156       return emitError("Linking COMDATs named '" + ComdatName +
157                        "': COMDAT key involves incomputable alias size.");
158   }
159 
160   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
161   if (!GVar)
162     return emitError(
163         "Linking COMDATs named '" + ComdatName +
164         "': GlobalVariable required for data dependent selection!");
165 
166   return false;
167 }
168 
169 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
170                                                  Comdat::SelectionKind Src,
171                                                  Comdat::SelectionKind Dst,
172                                                  Comdat::SelectionKind &Result,
173                                                  bool &LinkFromSrc) {
174   Module &DstM = Mover.getModule();
175   // The ability to mix Comdat::SelectionKind::Any with
176   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
177   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
178                          Dst == Comdat::SelectionKind::Largest;
179   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
180                          Src == Comdat::SelectionKind::Largest;
181   if (DstAnyOrLargest && SrcAnyOrLargest) {
182     if (Dst == Comdat::SelectionKind::Largest ||
183         Src == Comdat::SelectionKind::Largest)
184       Result = Comdat::SelectionKind::Largest;
185     else
186       Result = Comdat::SelectionKind::Any;
187   } else if (Src == Dst) {
188     Result = Dst;
189   } else {
190     return emitError("Linking COMDATs named '" + ComdatName +
191                      "': invalid selection kinds!");
192   }
193 
194   switch (Result) {
195   case Comdat::SelectionKind::Any:
196     // Go with Dst.
197     LinkFromSrc = false;
198     break;
199   case Comdat::SelectionKind::NoDuplicates:
200     return emitError("Linking COMDATs named '" + ComdatName +
201                      "': noduplicates has been violated!");
202   case Comdat::SelectionKind::ExactMatch:
203   case Comdat::SelectionKind::Largest:
204   case Comdat::SelectionKind::SameSize: {
205     const GlobalVariable *DstGV;
206     const GlobalVariable *SrcGV;
207     if (getComdatLeader(DstM, ComdatName, DstGV) ||
208         getComdatLeader(*SrcM, ComdatName, SrcGV))
209       return true;
210 
211     const DataLayout &DstDL = DstM.getDataLayout();
212     const DataLayout &SrcDL = SrcM->getDataLayout();
213     uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
214     uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
215     if (Result == Comdat::SelectionKind::ExactMatch) {
216       if (SrcGV->getInitializer() != DstGV->getInitializer())
217         return emitError("Linking COMDATs named '" + ComdatName +
218                          "': ExactMatch violated!");
219       LinkFromSrc = false;
220     } else if (Result == Comdat::SelectionKind::Largest) {
221       LinkFromSrc = SrcSize > DstSize;
222     } else if (Result == Comdat::SelectionKind::SameSize) {
223       if (SrcSize != DstSize)
224         return emitError("Linking COMDATs named '" + ComdatName +
225                          "': SameSize violated!");
226       LinkFromSrc = false;
227     } else {
228       llvm_unreachable("unknown selection kind");
229     }
230     break;
231   }
232   }
233 
234   return false;
235 }
236 
237 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
238                                    Comdat::SelectionKind &Result,
239                                    bool &LinkFromSrc) {
240   Module &DstM = Mover.getModule();
241   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
242   StringRef ComdatName = SrcC->getName();
243   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
244   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
245 
246   if (DstCI == ComdatSymTab.end()) {
247     // Use the comdat if it is only available in one of the modules.
248     LinkFromSrc = true;
249     Result = SSK;
250     return false;
251   }
252 
253   const Comdat *DstC = &DstCI->second;
254   Comdat::SelectionKind DSK = DstC->getSelectionKind();
255   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
256                                        LinkFromSrc);
257 }
258 
259 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
260                                         const GlobalValue &Dest,
261                                         const GlobalValue &Src) {
262 
263   // Should we unconditionally use the Src?
264   if (shouldOverrideFromSrc()) {
265     LinkFromSrc = true;
266     return false;
267   }
268 
269   // We always have to add Src if it has appending linkage.
270   if (Src.hasAppendingLinkage()) {
271     // Should have prevented importing for appending linkage in linkIfNeeded.
272     assert(!isPerformingImport());
273     LinkFromSrc = true;
274     return false;
275   }
276 
277   bool SrcIsDeclaration = Src.isDeclarationForLinker();
278   bool DestIsDeclaration = Dest.isDeclarationForLinker();
279 
280   if (isPerformingImport()) {
281     if (isa<Function>(&Src)) {
282       // For functions, LinkFromSrc iff this is a function requested
283       // for importing. For variables, decide below normally.
284       LinkFromSrc = GlobalsToImport->count(&Src);
285       return false;
286     }
287 
288     // Check if this is an alias with an already existing definition
289     // in Dest, which must have come from a prior importing pass from
290     // the same Src module. Unlike imported function and variable
291     // definitions, which are imported as available_externally and are
292     // not definitions for the linker, that is not a valid linkage for
293     // imported aliases which must be definitions. Simply use the existing
294     // Dest copy.
295     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
296       assert(isa<GlobalAlias>(&Dest));
297       LinkFromSrc = false;
298       return false;
299     }
300   }
301 
302   if (SrcIsDeclaration) {
303     // If Src is external or if both Src & Dest are external..  Just link the
304     // external globals, we aren't adding anything.
305     if (Src.hasDLLImportStorageClass()) {
306       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
307       LinkFromSrc = DestIsDeclaration;
308       return false;
309     }
310     // If the Dest is weak, use the source linkage.
311     if (Dest.hasExternalWeakLinkage()) {
312       LinkFromSrc = true;
313       return false;
314     }
315     // Link an available_externally over a declaration.
316     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
317     return false;
318   }
319 
320   if (DestIsDeclaration) {
321     // If Dest is external but Src is not:
322     LinkFromSrc = true;
323     return false;
324   }
325 
326   if (Src.hasCommonLinkage()) {
327     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
328       LinkFromSrc = true;
329       return false;
330     }
331 
332     if (!Dest.hasCommonLinkage()) {
333       LinkFromSrc = false;
334       return false;
335     }
336 
337     const DataLayout &DL = Dest.getParent()->getDataLayout();
338     uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
339     uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
340     LinkFromSrc = SrcSize > DestSize;
341     return false;
342   }
343 
344   if (Src.isWeakForLinker()) {
345     assert(!Dest.hasExternalWeakLinkage());
346     assert(!Dest.hasAvailableExternallyLinkage());
347 
348     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
349       LinkFromSrc = true;
350       return false;
351     }
352 
353     LinkFromSrc = false;
354     return false;
355   }
356 
357   if (Dest.isWeakForLinker()) {
358     assert(Src.hasExternalLinkage());
359     LinkFromSrc = true;
360     return false;
361   }
362 
363   assert(!Src.hasExternalWeakLinkage());
364   assert(!Dest.hasExternalWeakLinkage());
365   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
366          "Unexpected linkage type!");
367   return emitError("Linking globals named '" + Src.getName() +
368                    "': symbol multiply defined!");
369 }
370 
371 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
372   GlobalValue *DGV = getLinkedToGlobal(&GV);
373 
374   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
375     return false;
376 
377   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
378     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
379     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
380     if (DGVar && SGVar) {
381       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
382           (!DGVar->isConstant() || !SGVar->isConstant())) {
383         DGVar->setConstant(false);
384         SGVar->setConstant(false);
385       }
386       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
387         unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
388         SGVar->setAlignment(Align);
389         DGVar->setAlignment(Align);
390       }
391     }
392 
393     GlobalValue::VisibilityTypes Visibility =
394         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
395     DGV->setVisibility(Visibility);
396     GV.setVisibility(Visibility);
397 
398     bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
399     DGV->setUnnamedAddr(HasUnnamedAddr);
400     GV.setUnnamedAddr(HasUnnamedAddr);
401   }
402 
403   // Don't want to append to global_ctors list, for example, when we
404   // are importing for ThinLTO, otherwise the global ctors and dtors
405   // get executed multiple times for local variables (the latter causing
406   // double frees).
407   if (GV.hasAppendingLinkage() && isPerformingImport())
408     return false;
409 
410   if (isPerformingImport()) {
411     if (!doImportAsDefinition(&GV))
412       return false;
413   } else if (!DGV && !shouldOverrideFromSrc() &&
414              (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
415               GV.hasAvailableExternallyLinkage()))
416     return false;
417 
418   if (GV.isDeclaration())
419     return false;
420 
421   if (const Comdat *SC = GV.getComdat()) {
422     bool LinkFromSrc;
423     Comdat::SelectionKind SK;
424     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
425     if (!LinkFromSrc)
426       return false;
427   }
428 
429   bool LinkFromSrc = true;
430   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
431     return true;
432   if (LinkFromSrc)
433     ValuesToLink.insert(&GV);
434   return false;
435 }
436 
437 void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
438   // Add these to the internalize list
439   if (!GV.hasLinkOnceLinkage())
440     return;
441 
442   if (shouldInternalizeLinkedSymbols())
443     Internalize.insert(GV.getName());
444   Add(GV);
445 
446   const Comdat *SC = GV.getComdat();
447   if (!SC)
448     return;
449   for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
450     GlobalValue *DGV = getLinkedToGlobal(GV2);
451     bool LinkFromSrc = true;
452     if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
453       return;
454     if (!LinkFromSrc)
455       continue;
456     if (shouldInternalizeLinkedSymbols())
457       Internalize.insert(GV2->getName());
458     Add(*GV2);
459   }
460 }
461 
462 void ModuleLinker::dropReplacedComdat(
463     GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
464   Comdat *C = GV.getComdat();
465   if (!C)
466     return;
467   if (!ReplacedDstComdats.count(C))
468     return;
469   if (GV.use_empty()) {
470     GV.eraseFromParent();
471     return;
472   }
473 
474   if (auto *F = dyn_cast<Function>(&GV)) {
475     F->deleteBody();
476   } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
477     Var->setInitializer(nullptr);
478   } else {
479     auto &Alias = cast<GlobalAlias>(GV);
480     Module &M = *Alias.getParent();
481     PointerType &Ty = *cast<PointerType>(Alias.getType());
482     GlobalValue *Declaration;
483     if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
484       Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
485     } else {
486       Declaration =
487           new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
488                              GlobalValue::ExternalLinkage,
489                              /*Initializer*/ nullptr);
490     }
491     Declaration->takeName(&Alias);
492     Alias.replaceAllUsesWith(Declaration);
493     Alias.eraseFromParent();
494   }
495 }
496 
497 bool ModuleLinker::run() {
498   Module &DstM = Mover.getModule();
499   DenseSet<const Comdat *> ReplacedDstComdats;
500 
501   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
502     const Comdat &C = SMEC.getValue();
503     if (ComdatsChosen.count(&C))
504       continue;
505     Comdat::SelectionKind SK;
506     bool LinkFromSrc;
507     if (getComdatResult(&C, SK, LinkFromSrc))
508       return true;
509     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
510 
511     if (!LinkFromSrc)
512       continue;
513 
514     Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
515     Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
516     if (DstCI == ComdatSymTab.end())
517       continue;
518 
519     // The source comdat is replacing the dest one.
520     const Comdat *DstC = &DstCI->second;
521     ReplacedDstComdats.insert(DstC);
522   }
523 
524   // Alias have to go first, since we are not able to find their comdats
525   // otherwise.
526   for (auto I = DstM.alias_begin(), E = DstM.alias_end(); I != E;) {
527     GlobalAlias &GV = *I++;
528     dropReplacedComdat(GV, ReplacedDstComdats);
529   }
530 
531   for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
532     GlobalVariable &GV = *I++;
533     dropReplacedComdat(GV, ReplacedDstComdats);
534   }
535 
536   for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
537     Function &GV = *I++;
538     dropReplacedComdat(GV, ReplacedDstComdats);
539   }
540 
541   for (GlobalVariable &GV : SrcM->globals())
542     if (GV.hasLinkOnceLinkage())
543       if (const Comdat *SC = GV.getComdat())
544         LazyComdatMembers[SC].push_back(&GV);
545 
546   for (Function &SF : *SrcM)
547     if (SF.hasLinkOnceLinkage())
548       if (const Comdat *SC = SF.getComdat())
549         LazyComdatMembers[SC].push_back(&SF);
550 
551   for (GlobalAlias &GA : SrcM->aliases())
552     if (GA.hasLinkOnceLinkage())
553       if (const Comdat *SC = GA.getComdat())
554         LazyComdatMembers[SC].push_back(&GA);
555 
556   // Insert all of the globals in src into the DstM module... without linking
557   // initializers (which could refer to functions not yet mapped over).
558   for (GlobalVariable &GV : SrcM->globals())
559     if (linkIfNeeded(GV))
560       return true;
561 
562   for (Function &SF : *SrcM)
563     if (linkIfNeeded(SF))
564       return true;
565 
566   for (GlobalAlias &GA : SrcM->aliases())
567     if (linkIfNeeded(GA))
568       return true;
569 
570   for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
571     GlobalValue *GV = ValuesToLink[I];
572     const Comdat *SC = GV->getComdat();
573     if (!SC)
574       continue;
575     for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
576       GlobalValue *DGV = getLinkedToGlobal(GV2);
577       bool LinkFromSrc = true;
578       if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
579         return true;
580       if (LinkFromSrc)
581         ValuesToLink.insert(GV2);
582     }
583   }
584 
585   if (shouldInternalizeLinkedSymbols()) {
586     for (GlobalValue *GV : ValuesToLink)
587       Internalize.insert(GV->getName());
588   }
589 
590   if (Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
591                  [this](GlobalValue &GV, IRMover::ValueAdder Add) {
592                    addLazyFor(GV, Add);
593                  },
594                  ValIDToTempMDMap, false))
595     return true;
596   for (auto &P : Internalize) {
597     GlobalValue *GV = DstM.getNamedValue(P.first());
598     GV->setLinkage(GlobalValue::InternalLinkage);
599   }
600 
601   return false;
602 }
603 
604 Linker::Linker(Module &M) : Mover(M) {}
605 
606 bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
607                           DenseSet<const GlobalValue *> *GlobalsToImport,
608                           DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
609   ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport,
610                          ValIDToTempMDMap);
611   return ModLinker.run();
612 }
613 
614 bool Linker::linkInMetadata(std::unique_ptr<Module> Src,
615                             DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
616   SetVector<GlobalValue *> ValuesToLink;
617   if (Mover.move(
618           std::move(Src), ValuesToLink.getArrayRef(),
619           [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
620           ValIDToTempMDMap, true))
621     return true;
622   return false;
623 }
624 
625 //===----------------------------------------------------------------------===//
626 // LinkModules entrypoint.
627 //===----------------------------------------------------------------------===//
628 
629 /// This function links two modules together, with the resulting Dest module
630 /// modified to be the composite of the two input modules. If an error occurs,
631 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
632 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
633 /// relied on to be consistent.
634 bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
635                          unsigned Flags) {
636   Linker L(Dest);
637   return L.linkInModule(std::move(Src), Flags);
638 }
639 
640 //===----------------------------------------------------------------------===//
641 // C API.
642 //===----------------------------------------------------------------------===//
643 
644 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
645   Module *D = unwrap(Dest);
646   std::unique_ptr<Module> M(unwrap(Src));
647   return Linker::linkModules(*D, std::move(M));
648 }
649