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