1a10796a6050c976f33cd1c3690cf1bdc1430506
[oota-llvm.git] / lib / Linker / LinkModules.cpp
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 "llvm/Linker/Linker.h"
15 #include "LinkDiagnosticInfo.h"
16 #include "llvm-c/Linker.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
20 #include "llvm/IR/LLVMContext.h"
21 using namespace llvm;
22
23 namespace {
24
25 /// This is an implementation class for the LinkModules function, which is the
26 /// entrypoint for this file.
27 class ModuleLinker {
28   IRMover &Mover;
29   Module &SrcM;
30
31   SetVector<GlobalValue *> ValuesToLink;
32   StringSet<> Internalize;
33
34   /// For symbol clashes, prefer those from Src.
35   unsigned Flags;
36
37   /// Function index passed into ModuleLinker for using in function
38   /// importing/exporting handling.
39   const FunctionInfoIndex *ImportIndex;
40
41   /// Function to import from source module, all other functions are
42   /// imported as declarations instead of definitions.
43   DenseSet<const GlobalValue *> *ImportFunction;
44
45   /// Set to true if the given FunctionInfoIndex contains any functions
46   /// from this source module, in which case we must conservatively assume
47   /// that any of its functions may be imported into another module
48   /// as part of a different backend compilation process.
49   bool HasExportedFunctions = false;
50
51   /// Used as the callback for lazy linking.
52   /// The mover has just hit GV and we have to decide if it, and other members
53   /// of the same comdat, should be linked. Every member to be linked is passed
54   /// to Add.
55   void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
56
57   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
58   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
59   bool shouldInternalizeLinkedSymbols() {
60     return Flags & Linker::InternalizeLinkedSymbols;
61   }
62
63   /// Check if we should promote the given local value to global scope.
64   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
65
66   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
67                             const GlobalValue &Src);
68
69   /// Should we have mover and linker error diag info?
70   bool emitError(const Twine &Message) {
71     SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
72     return true;
73   }
74
75   bool getComdatLeader(Module &M, StringRef ComdatName,
76                        const GlobalVariable *&GVar);
77   bool computeResultingSelectionKind(StringRef ComdatName,
78                                      Comdat::SelectionKind Src,
79                                      Comdat::SelectionKind Dst,
80                                      Comdat::SelectionKind &Result,
81                                      bool &LinkFromSrc);
82   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
83       ComdatsChosen;
84   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
85                        bool &LinkFromSrc);
86   // Keep track of the global value members of each comdat in source.
87   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
88
89   /// Given a global in the source module, return the global in the
90   /// destination module that is being linked to, if any.
91   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
92     Module &DstM = Mover.getModule();
93     // If the source has no name it can't link.  If it has local linkage,
94     // there is no name match-up going on.
95     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
96       return nullptr;
97
98     // Otherwise see if we have a match in the destination module's symtab.
99     GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
100     if (!DGV)
101       return nullptr;
102
103     // If we found a global with the same name in the dest module, but it has
104     // internal linkage, we are really not doing any linkage here.
105     if (DGV->hasLocalLinkage())
106       return nullptr;
107
108     // Otherwise, we do in fact link to the destination global.
109     return DGV;
110   }
111
112   bool linkIfNeeded(GlobalValue &GV);
113
114   /// Helper methods to check if we are importing from or potentially
115   /// exporting from the current source module.
116   bool isPerformingImport() { return ImportFunction != nullptr; }
117   bool isModuleExporting() { return HasExportedFunctions; }
118
119   /// If we are importing from the source module, checks if we should
120   /// import SGV as a definition, otherwise import as a declaration.
121   bool doImportAsDefinition(const GlobalValue *SGV);
122
123   /// Get the name for SGV that should be used in the linked destination
124   /// module. Specifically, this handles the case where we need to rename
125   /// a local that is being promoted to global scope.
126   std::string getName(const GlobalValue *SGV);
127
128   /// Process globals so that they can be used in ThinLTO. This includes
129   /// promoting local variables so that they can be reference externally by
130   /// thin lto imported globals and converting strong external globals to
131   /// available_externally.
132   void processGlobalsForThinLTO();
133   void processGlobalForThinLTO(GlobalValue &GV);
134
135   /// Get the new linkage for SGV that should be used in the linked destination
136   /// module. Specifically, for ThinLTO importing or exporting it may need
137   /// to be adjusted.
138   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
139
140   /// Copies the necessary global value attributes and name from the source
141   /// to the newly cloned global value.
142   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
143
144   /// Updates the visibility for the new global cloned from the source
145   /// and, if applicable, linked with an existing destination global.
146   /// Handles visibility change required for promoted locals.
147   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
148                      const GlobalValue *DGV = nullptr);
149
150 public:
151   ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
152                const FunctionInfoIndex *Index = nullptr,
153                DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
154       : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
155         ImportFunction(FunctionsToImport) {
156     assert((ImportIndex || !ImportFunction) &&
157            "Expect a FunctionInfoIndex when importing");
158     // If we have a FunctionInfoIndex but no function to import,
159     // then this is the primary module being compiled in a ThinLTO
160     // backend compilation, and we need to see if it has functions that
161     // may be exported to another backend compilation.
162     if (ImportIndex && !ImportFunction)
163       HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
164   }
165
166   bool run();
167 };
168 }
169
170 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
171 /// table. This is good for all clients except for us. Go through the trouble
172 /// to force this back.
173 static void forceRenaming(GlobalValue *GV, StringRef Name) {
174   // If the global doesn't force its name or if it already has the right name,
175   // there is nothing for us to do.
176   // Note that any required local to global promotion should already be done,
177   // so promoted locals will not skip this handling as their linkage is no
178   // longer local.
179   if (GV->hasLocalLinkage() || GV->getName() == Name)
180     return;
181
182   Module *M = GV->getParent();
183
184   // If there is a conflict, rename the conflict.
185   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
186     GV->takeName(ConflictGV);
187     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
188     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
189   } else {
190     GV->setName(Name); // Force the name back
191   }
192 }
193
194 /// copy additional attributes (those not needed to construct a GlobalValue)
195 /// from the SrcGV to the DestGV.
196 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
197                                     const GlobalValue *SrcGV) {
198   NewGV->copyAttributesFrom(SrcGV);
199   forceRenaming(NewGV, getName(SrcGV));
200 }
201
202 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
203   if (!isPerformingImport())
204     return false;
205   auto *GA = dyn_cast<GlobalAlias>(SGV);
206   if (GA) {
207     if (GA->hasWeakAnyLinkage())
208       return false;
209     const GlobalObject *GO = GA->getBaseObject();
210     if (!GO->hasLinkOnceODRLinkage())
211       return false;
212     return doImportAsDefinition(GO);
213   }
214   // Always import GlobalVariable definitions, except for the special
215   // case of WeakAny which are imported as ExternalWeak declarations
216   // (see comments in ModuleLinker::getLinkage). The linkage changes
217   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
218   // global variables with external linkage are transformed to
219   // available_externally definitions, which are ultimately turned into
220   // declarations after the EliminateAvailableExternally pass).
221   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
222       !SGV->hasWeakAnyLinkage())
223     return true;
224   // Only import the function requested for importing.
225   auto *SF = dyn_cast<Function>(SGV);
226   if (SF && ImportFunction->count(SF))
227     return true;
228   // Otherwise no.
229   return false;
230 }
231
232 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
233   assert(SGV->hasLocalLinkage());
234   // Both the imported references and the original local variable must
235   // be promoted.
236   if (!isPerformingImport() && !isModuleExporting())
237     return false;
238
239   // Local const variables never need to be promoted unless they are address
240   // taken. The imported uses can simply use the clone created in this module.
241   // For now we are conservative in determining which variables are not
242   // address taken by checking the unnamed addr flag. To be more aggressive,
243   // the address taken information must be checked earlier during parsing
244   // of the module and recorded in the function index for use when importing
245   // from that module.
246   auto *GVar = dyn_cast<GlobalVariable>(SGV);
247   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
248     return false;
249
250   // Eventually we only need to promote functions in the exporting module that
251   // are referenced by a potentially exported function (i.e. one that is in the
252   // function index).
253   return true;
254 }
255
256 std::string ModuleLinker::getName(const GlobalValue *SGV) {
257   // For locals that must be promoted to global scope, ensure that
258   // the promoted name uniquely identifies the copy in the original module,
259   // using the ID assigned during combined index creation. When importing,
260   // we rename all locals (not just those that are promoted) in order to
261   // avoid naming conflicts between locals imported from different modules.
262   if (SGV->hasLocalLinkage() &&
263       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
264     return FunctionInfoIndex::getGlobalNameForLocal(
265         SGV->getName(),
266         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
267   return SGV->getName();
268 }
269
270 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
271   // Any local variable that is referenced by an exported function needs
272   // to be promoted to global scope. Since we don't currently know which
273   // functions reference which local variables/functions, we must treat
274   // all as potentially exported if this module is exporting anything.
275   if (isModuleExporting()) {
276     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
277       return GlobalValue::ExternalLinkage;
278     return SGV->getLinkage();
279   }
280
281   // Otherwise, if we aren't importing, no linkage change is needed.
282   if (!isPerformingImport())
283     return SGV->getLinkage();
284
285   switch (SGV->getLinkage()) {
286   case GlobalValue::ExternalLinkage:
287     // External defnitions are converted to available_externally
288     // definitions upon import, so that they are available for inlining
289     // and/or optimization, but are turned into declarations later
290     // during the EliminateAvailableExternally pass.
291     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
292       return GlobalValue::AvailableExternallyLinkage;
293     // An imported external declaration stays external.
294     return SGV->getLinkage();
295
296   case GlobalValue::AvailableExternallyLinkage:
297     // An imported available_externally definition converts
298     // to external if imported as a declaration.
299     if (!doImportAsDefinition(SGV))
300       return GlobalValue::ExternalLinkage;
301     // An imported available_externally declaration stays that way.
302     return SGV->getLinkage();
303
304   case GlobalValue::LinkOnceAnyLinkage:
305   case GlobalValue::LinkOnceODRLinkage:
306     // These both stay the same when importing the definition.
307     // The ThinLTO pass will eventually force-import their definitions.
308     return SGV->getLinkage();
309
310   case GlobalValue::WeakAnyLinkage:
311     // Can't import weak_any definitions correctly, or we might change the
312     // program semantics, since the linker will pick the first weak_any
313     // definition and importing would change the order they are seen by the
314     // linker. The module linking caller needs to enforce this.
315     assert(!doImportAsDefinition(SGV));
316     // If imported as a declaration, it becomes external_weak.
317     return GlobalValue::ExternalWeakLinkage;
318
319   case GlobalValue::WeakODRLinkage:
320     // For weak_odr linkage, there is a guarantee that all copies will be
321     // equivalent, so the issue described above for weak_any does not exist,
322     // and the definition can be imported. It can be treated similarly
323     // to an imported externally visible global value.
324     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
325       return GlobalValue::AvailableExternallyLinkage;
326     else
327       return GlobalValue::ExternalLinkage;
328
329   case GlobalValue::AppendingLinkage:
330     // It would be incorrect to import an appending linkage variable,
331     // since it would cause global constructors/destructors to be
332     // executed multiple times. This should have already been handled
333     // by linkIfNeeded, and we will assert in shouldLinkFromSource
334     // if we try to import, so we simply return AppendingLinkage here
335     // as this helper is called more widely in getLinkedToGlobal.
336     return GlobalValue::AppendingLinkage;
337
338   case GlobalValue::InternalLinkage:
339   case GlobalValue::PrivateLinkage:
340     // If we are promoting the local to global scope, it is handled
341     // similarly to a normal externally visible global.
342     if (doPromoteLocalToGlobal(SGV)) {
343       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
344         return GlobalValue::AvailableExternallyLinkage;
345       else
346         return GlobalValue::ExternalLinkage;
347     }
348     // A non-promoted imported local definition stays local.
349     // The ThinLTO pass will eventually force-import their definitions.
350     return SGV->getLinkage();
351
352   case GlobalValue::ExternalWeakLinkage:
353     // External weak doesn't apply to definitions, must be a declaration.
354     assert(!doImportAsDefinition(SGV));
355     // Linkage stays external_weak.
356     return SGV->getLinkage();
357
358   case GlobalValue::CommonLinkage:
359     // Linkage stays common on definitions.
360     // The ThinLTO pass will eventually force-import their definitions.
361     return SGV->getLinkage();
362   }
363
364   llvm_unreachable("unknown linkage type");
365 }
366
367 static GlobalValue::VisibilityTypes
368 getMinVisibility(GlobalValue::VisibilityTypes A,
369                  GlobalValue::VisibilityTypes B) {
370   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
371     return GlobalValue::HiddenVisibility;
372   if (A == GlobalValue::ProtectedVisibility ||
373       B == GlobalValue::ProtectedVisibility)
374     return GlobalValue::ProtectedVisibility;
375   return GlobalValue::DefaultVisibility;
376 }
377
378 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
379                                  const GlobalValue *DGV) {
380   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
381   if (DGV)
382     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
383   // For promoted locals, mark them hidden so that they can later be
384   // stripped from the symbol table to reduce bloat.
385   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
386     Visibility = GlobalValue::HiddenVisibility;
387   NewGV->setVisibility(Visibility);
388 }
389
390 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
391                                    const GlobalVariable *&GVar) {
392   const GlobalValue *GVal = M.getNamedValue(ComdatName);
393   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
394     GVal = GA->getBaseObject();
395     if (!GVal)
396       // We cannot resolve the size of the aliasee yet.
397       return emitError("Linking COMDATs named '" + ComdatName +
398                        "': COMDAT key involves incomputable alias size.");
399   }
400
401   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
402   if (!GVar)
403     return emitError(
404         "Linking COMDATs named '" + ComdatName +
405         "': GlobalVariable required for data dependent selection!");
406
407   return false;
408 }
409
410 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
411                                                  Comdat::SelectionKind Src,
412                                                  Comdat::SelectionKind Dst,
413                                                  Comdat::SelectionKind &Result,
414                                                  bool &LinkFromSrc) {
415   Module &DstM = Mover.getModule();
416   // The ability to mix Comdat::SelectionKind::Any with
417   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
418   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
419                          Dst == Comdat::SelectionKind::Largest;
420   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
421                          Src == Comdat::SelectionKind::Largest;
422   if (DstAnyOrLargest && SrcAnyOrLargest) {
423     if (Dst == Comdat::SelectionKind::Largest ||
424         Src == Comdat::SelectionKind::Largest)
425       Result = Comdat::SelectionKind::Largest;
426     else
427       Result = Comdat::SelectionKind::Any;
428   } else if (Src == Dst) {
429     Result = Dst;
430   } else {
431     return emitError("Linking COMDATs named '" + ComdatName +
432                      "': invalid selection kinds!");
433   }
434
435   switch (Result) {
436   case Comdat::SelectionKind::Any:
437     // Go with Dst.
438     LinkFromSrc = false;
439     break;
440   case Comdat::SelectionKind::NoDuplicates:
441     return emitError("Linking COMDATs named '" + ComdatName +
442                      "': noduplicates has been violated!");
443   case Comdat::SelectionKind::ExactMatch:
444   case Comdat::SelectionKind::Largest:
445   case Comdat::SelectionKind::SameSize: {
446     const GlobalVariable *DstGV;
447     const GlobalVariable *SrcGV;
448     if (getComdatLeader(DstM, ComdatName, DstGV) ||
449         getComdatLeader(SrcM, ComdatName, SrcGV))
450       return true;
451
452     const DataLayout &DstDL = DstM.getDataLayout();
453     const DataLayout &SrcDL = SrcM.getDataLayout();
454     uint64_t DstSize =
455         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
456     uint64_t SrcSize =
457         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
458     if (Result == Comdat::SelectionKind::ExactMatch) {
459       if (SrcGV->getInitializer() != DstGV->getInitializer())
460         return emitError("Linking COMDATs named '" + ComdatName +
461                          "': ExactMatch violated!");
462       LinkFromSrc = false;
463     } else if (Result == Comdat::SelectionKind::Largest) {
464       LinkFromSrc = SrcSize > DstSize;
465     } else if (Result == Comdat::SelectionKind::SameSize) {
466       if (SrcSize != DstSize)
467         return emitError("Linking COMDATs named '" + ComdatName +
468                          "': SameSize violated!");
469       LinkFromSrc = false;
470     } else {
471       llvm_unreachable("unknown selection kind");
472     }
473     break;
474   }
475   }
476
477   return false;
478 }
479
480 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
481                                    Comdat::SelectionKind &Result,
482                                    bool &LinkFromSrc) {
483   Module &DstM = Mover.getModule();
484   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
485   StringRef ComdatName = SrcC->getName();
486   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
487   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
488
489   if (DstCI == ComdatSymTab.end()) {
490     // Use the comdat if it is only available in one of the modules.
491     LinkFromSrc = true;
492     Result = SSK;
493     return false;
494   }
495
496   const Comdat *DstC = &DstCI->second;
497   Comdat::SelectionKind DSK = DstC->getSelectionKind();
498   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
499                                        LinkFromSrc);
500 }
501
502 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
503                                         const GlobalValue &Dest,
504                                         const GlobalValue &Src) {
505   // Should we unconditionally use the Src?
506   if (shouldOverrideFromSrc()) {
507     LinkFromSrc = true;
508     return false;
509   }
510
511   // We always have to add Src if it has appending linkage.
512   if (Src.hasAppendingLinkage()) {
513     // Should have prevented importing for appending linkage in linkIfNeeded.
514     assert(!isPerformingImport());
515     LinkFromSrc = true;
516     return false;
517   }
518
519   bool SrcIsDeclaration = Src.isDeclarationForLinker();
520   bool DestIsDeclaration = Dest.isDeclarationForLinker();
521
522   if (isPerformingImport()) {
523     if (isa<Function>(&Src)) {
524       // For functions, LinkFromSrc iff this is the function requested
525       // for importing. For variables, decide below normally.
526       LinkFromSrc = ImportFunction->count(&Src);
527       return false;
528     }
529
530     // Check if this is an alias with an already existing definition
531     // in Dest, which must have come from a prior importing pass from
532     // the same Src module. Unlike imported function and variable
533     // definitions, which are imported as available_externally and are
534     // not definitions for the linker, that is not a valid linkage for
535     // imported aliases which must be definitions. Simply use the existing
536     // Dest copy.
537     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
538       assert(isa<GlobalAlias>(&Dest));
539       LinkFromSrc = false;
540       return false;
541     }
542   }
543
544   if (SrcIsDeclaration) {
545     // If Src is external or if both Src & Dest are external..  Just link the
546     // external globals, we aren't adding anything.
547     if (Src.hasDLLImportStorageClass()) {
548       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
549       LinkFromSrc = DestIsDeclaration;
550       return false;
551     }
552     // If the Dest is weak, use the source linkage.
553     if (Dest.hasExternalWeakLinkage()) {
554       LinkFromSrc = true;
555       return false;
556     }
557     // Link an available_externally over a declaration.
558     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
559     return false;
560   }
561
562   if (DestIsDeclaration) {
563     // If Dest is external but Src is not:
564     LinkFromSrc = true;
565     return false;
566   }
567
568   if (Src.hasCommonLinkage()) {
569     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
570       LinkFromSrc = true;
571       return false;
572     }
573
574     if (!Dest.hasCommonLinkage()) {
575       LinkFromSrc = false;
576       return false;
577     }
578
579     const DataLayout &DL = Dest.getParent()->getDataLayout();
580     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
581     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
582     LinkFromSrc = SrcSize > DestSize;
583     return false;
584   }
585
586   if (Src.isWeakForLinker()) {
587     assert(!Dest.hasExternalWeakLinkage());
588     assert(!Dest.hasAvailableExternallyLinkage());
589
590     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
591       LinkFromSrc = true;
592       return false;
593     }
594
595     LinkFromSrc = false;
596     return false;
597   }
598
599   if (Dest.isWeakForLinker()) {
600     assert(Src.hasExternalLinkage());
601     LinkFromSrc = true;
602     return false;
603   }
604
605   assert(!Src.hasExternalWeakLinkage());
606   assert(!Dest.hasExternalWeakLinkage());
607   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
608          "Unexpected linkage type!");
609   return emitError("Linking globals named '" + Src.getName() +
610                    "': symbol multiply defined!");
611 }
612
613 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
614   GlobalValue *DGV = getLinkedToGlobal(&GV);
615
616   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
617     return false;
618
619   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
620     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
621     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
622     if (DGVar && SGVar) {
623       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
624           (!DGVar->isConstant() || !SGVar->isConstant())) {
625         DGVar->setConstant(false);
626         SGVar->setConstant(false);
627       }
628       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
629         unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
630         SGVar->setAlignment(Align);
631         DGVar->setAlignment(Align);
632       }
633     }
634
635     GlobalValue::VisibilityTypes Visibility =
636         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
637     DGV->setVisibility(Visibility);
638     GV.setVisibility(Visibility);
639
640     bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
641     DGV->setUnnamedAddr(HasUnnamedAddr);
642     GV.setUnnamedAddr(HasUnnamedAddr);
643   }
644
645   // Don't want to append to global_ctors list, for example, when we
646   // are importing for ThinLTO, otherwise the global ctors and dtors
647   // get executed multiple times for local variables (the latter causing
648   // double frees).
649   if (GV.hasAppendingLinkage() && isPerformingImport())
650     return false;
651
652   if (isPerformingImport() && !doImportAsDefinition(&GV))
653     return false;
654
655   if (!DGV && !shouldOverrideFromSrc() &&
656       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
657        GV.hasAvailableExternallyLinkage()))
658     return false;
659
660   if (GV.isDeclaration())
661     return false;
662
663   if (const Comdat *SC = GV.getComdat()) {
664     bool LinkFromSrc;
665     Comdat::SelectionKind SK;
666     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
667     if (LinkFromSrc)
668       ValuesToLink.insert(&GV);
669     return false;
670   }
671
672   bool LinkFromSrc = true;
673   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
674     return true;
675   if (LinkFromSrc)
676     ValuesToLink.insert(&GV);
677   return false;
678 }
679
680 void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
681   // Add these to the internalize list
682   if (!GV.hasLinkOnceLinkage())
683     return;
684
685   if (shouldInternalizeLinkedSymbols())
686     Internalize.insert(GV.getName());
687   Add(GV);
688
689   const Comdat *SC = GV.getComdat();
690   if (!SC)
691     return;
692   for (GlobalValue *GV2 : ComdatMembers[SC]) {
693     if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
694       Internalize.insert(GV2->getName());
695     Add(*GV2);
696   }
697 }
698
699 void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
700   if (GV.hasLocalLinkage() &&
701       (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
702     GV.setName(getName(&GV));
703     GV.setLinkage(getLinkage(&GV));
704     if (!GV.hasLocalLinkage())
705       GV.setVisibility(GlobalValue::HiddenVisibility);
706     if (isModuleExporting())
707       ValuesToLink.insert(&GV);
708     return;
709   }
710   GV.setLinkage(getLinkage(&GV));
711 }
712
713 void ModuleLinker::processGlobalsForThinLTO() {
714   for (GlobalVariable &GV : SrcM.globals())
715     processGlobalForThinLTO(GV);
716   for (Function &SF : SrcM)
717     processGlobalForThinLTO(SF);
718   for (GlobalAlias &GA : SrcM.aliases())
719     processGlobalForThinLTO(GA);
720 }
721
722 bool ModuleLinker::run() {
723   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
724     const Comdat &C = SMEC.getValue();
725     if (ComdatsChosen.count(&C))
726       continue;
727     Comdat::SelectionKind SK;
728     bool LinkFromSrc;
729     if (getComdatResult(&C, SK, LinkFromSrc))
730       return true;
731     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
732   }
733
734   for (GlobalVariable &GV : SrcM.globals())
735     if (const Comdat *SC = GV.getComdat())
736       ComdatMembers[SC].push_back(&GV);
737
738   for (Function &SF : SrcM)
739     if (const Comdat *SC = SF.getComdat())
740       ComdatMembers[SC].push_back(&SF);
741
742   for (GlobalAlias &GA : SrcM.aliases())
743     if (const Comdat *SC = GA.getComdat())
744       ComdatMembers[SC].push_back(&GA);
745
746   // Insert all of the globals in src into the DstM module... without linking
747   // initializers (which could refer to functions not yet mapped over).
748   for (GlobalVariable &GV : SrcM.globals())
749     if (linkIfNeeded(GV))
750       return true;
751
752   for (Function &SF : SrcM)
753     if (linkIfNeeded(SF))
754       return true;
755
756   for (GlobalAlias &GA : SrcM.aliases())
757     if (linkIfNeeded(GA))
758       return true;
759
760   processGlobalsForThinLTO();
761
762   for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
763     GlobalValue *GV = ValuesToLink[I];
764     const Comdat *SC = GV->getComdat();
765     if (!SC)
766       continue;
767     for (GlobalValue *GV2 : ComdatMembers[SC])
768       ValuesToLink.insert(GV2);
769   }
770
771   if (shouldInternalizeLinkedSymbols()) {
772     for (GlobalValue *GV : ValuesToLink)
773       Internalize.insert(GV->getName());
774   }
775
776   if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
777                  [this](GlobalValue &GV, IRMover::ValueAdder Add) {
778                    addLazyFor(GV, Add);
779                  }))
780     return true;
781   Module &DstM = Mover.getModule();
782   for (auto &P : Internalize) {
783     GlobalValue *GV = DstM.getNamedValue(P.first());
784     GV->setLinkage(GlobalValue::InternalLinkage);
785   }
786
787   return false;
788 }
789
790 Linker::Linker(Module &M) : Mover(M) {}
791
792 bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
793                           const FunctionInfoIndex *Index,
794                           DenseSet<const GlobalValue *> *FunctionsToImport) {
795   ModuleLinker TheLinker(Mover, *Src, Flags, Index, FunctionsToImport);
796   return TheLinker.run();
797 }
798
799 bool Linker::linkInModuleForCAPI(Module &Src) {
800   ModuleLinker TheLinker(Mover, Src, 0, nullptr, nullptr);
801   return TheLinker.run();
802 }
803
804 //===----------------------------------------------------------------------===//
805 // LinkModules entrypoint.
806 //===----------------------------------------------------------------------===//
807
808 /// This function links two modules together, with the resulting Dest module
809 /// modified to be the composite of the two input modules. If an error occurs,
810 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
811 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
812 /// relied on to be consistent.
813 bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
814                          unsigned Flags) {
815   Linker L(Dest);
816   return L.linkInModule(std::move(Src), Flags);
817 }
818
819 std::unique_ptr<Module>
820 llvm::renameModuleForThinLTO(std::unique_ptr<Module> M,
821                              const FunctionInfoIndex *Index) {
822   std::unique_ptr<llvm::Module> RenamedModule(
823       new llvm::Module(M->getModuleIdentifier(), M->getContext()));
824   Linker L(*RenamedModule.get());
825   if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
826     return nullptr;
827   return RenamedModule;
828 }
829
830 //===----------------------------------------------------------------------===//
831 // C API.
832 //===----------------------------------------------------------------------===//
833
834 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
835   auto *Message = reinterpret_cast<std::string *>(C);
836   raw_string_ostream Stream(*Message);
837   DiagnosticPrinterRawOStream DP(Stream);
838   DI.print(DP);
839 }
840
841 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
842                          LLVMLinkerMode Unused, char **OutMessages) {
843   Module *D = unwrap(Dest);
844   LLVMContext &Ctx = D->getContext();
845
846   LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
847       Ctx.getDiagnosticHandler();
848   void *OldDiagnosticContext = Ctx.getDiagnosticContext();
849   std::string Message;
850   Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
851
852   Linker L(*D);
853   Module *M = unwrap(Src);
854   LLVMBool Result = L.linkInModuleForCAPI(*M);
855
856   Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
857
858   if (OutMessages && Result)
859     *OutMessages = strdup(Message.c_str());
860   return Result;
861 }
862
863 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
864   Module *D = unwrap(Dest);
865   std::unique_ptr<Module> M(unwrap(Src));
866   return Linker::linkModules(*D, std::move(M));
867 }