Synchronize the logic for deciding to link a gv.
[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 "llvm-c/Linker.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // TypeMap implementation.
30 //===----------------------------------------------------------------------===//
31
32 namespace {
33 class TypeMapTy : public ValueMapTypeRemapper {
34   /// This is a mapping from a source type to a destination type to use.
35   DenseMap<Type *, Type *> MappedTypes;
36
37   /// When checking to see if two subgraphs are isomorphic, we speculatively
38   /// add types to MappedTypes, but keep track of them here in case we need to
39   /// roll back.
40   SmallVector<Type *, 16> SpeculativeTypes;
41
42   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
43
44   /// This is a list of non-opaque structs in the source module that are mapped
45   /// to an opaque struct in the destination module.
46   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
47
48   /// This is the set of opaque types in the destination modules who are
49   /// getting a body from the source module.
50   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
51
52 public:
53   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
54       : DstStructTypesSet(DstStructTypesSet) {}
55
56   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
57   /// Indicate that the specified type in the destination module is conceptually
58   /// equivalent to the specified type in the source module.
59   void addTypeMapping(Type *DstTy, Type *SrcTy);
60
61   /// Produce a body for an opaque type in the dest module from a type
62   /// definition in the source module.
63   void linkDefinedTypeBodies();
64
65   /// Return the mapped type to use for the specified input type from the
66   /// source module.
67   Type *get(Type *SrcTy);
68   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
69
70   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
71
72   FunctionType *get(FunctionType *T) {
73     return cast<FunctionType>(get((Type *)T));
74   }
75
76   /// Dump out the type map for debugging purposes.
77   void dump() const {
78     for (auto &Pair : MappedTypes) {
79       dbgs() << "TypeMap: ";
80       Pair.first->print(dbgs());
81       dbgs() << " => ";
82       Pair.second->print(dbgs());
83       dbgs() << '\n';
84     }
85   }
86
87 private:
88   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
89
90   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
91 };
92 }
93
94 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
95   assert(SpeculativeTypes.empty());
96   assert(SpeculativeDstOpaqueTypes.empty());
97
98   // Check to see if these types are recursively isomorphic and establish a
99   // mapping between them if so.
100   if (!areTypesIsomorphic(DstTy, SrcTy)) {
101     // Oops, they aren't isomorphic.  Just discard this request by rolling out
102     // any speculative mappings we've established.
103     for (Type *Ty : SpeculativeTypes)
104       MappedTypes.erase(Ty);
105
106     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107                                    SpeculativeDstOpaqueTypes.size());
108     for (StructType *Ty : SpeculativeDstOpaqueTypes)
109       DstResolvedOpaqueTypes.erase(Ty);
110   } else {
111     for (Type *Ty : SpeculativeTypes)
112       if (auto *STy = dyn_cast<StructType>(Ty))
113         if (STy->hasName())
114           STy->setName("");
115   }
116   SpeculativeTypes.clear();
117   SpeculativeDstOpaqueTypes.clear();
118 }
119
120 /// Recursively walk this pair of types, returning true if they are isomorphic,
121 /// false if they are not.
122 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123   // Two types with differing kinds are clearly not isomorphic.
124   if (DstTy->getTypeID() != SrcTy->getTypeID())
125     return false;
126
127   // If we have an entry in the MappedTypes table, then we have our answer.
128   Type *&Entry = MappedTypes[SrcTy];
129   if (Entry)
130     return Entry == DstTy;
131
132   // Two identical types are clearly isomorphic.  Remember this
133   // non-speculatively.
134   if (DstTy == SrcTy) {
135     Entry = DstTy;
136     return true;
137   }
138
139   // Okay, we have two types with identical kinds that we haven't seen before.
140
141   // If this is an opaque struct type, special case it.
142   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143     // Mapping an opaque type to any struct, just keep the dest struct.
144     if (SSTy->isOpaque()) {
145       Entry = DstTy;
146       SpeculativeTypes.push_back(SrcTy);
147       return true;
148     }
149
150     // Mapping a non-opaque source type to an opaque dest.  If this is the first
151     // type that we're mapping onto this destination type then we succeed.  Keep
152     // the dest, but fill it in later. If this is the second (different) type
153     // that we're trying to map onto the same opaque type then we fail.
154     if (cast<StructType>(DstTy)->isOpaque()) {
155       // We can only map one source type onto the opaque destination type.
156       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
157         return false;
158       SrcDefinitionsToResolve.push_back(SSTy);
159       SpeculativeTypes.push_back(SrcTy);
160       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
161       Entry = DstTy;
162       return true;
163     }
164   }
165
166   // If the number of subtypes disagree between the two types, then we fail.
167   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
168     return false;
169
170   // Fail if any of the extra properties (e.g. array size) of the type disagree.
171   if (isa<IntegerType>(DstTy))
172     return false; // bitwidth disagrees.
173   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175       return false;
176
177   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179       return false;
180   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181     StructType *SSTy = cast<StructType>(SrcTy);
182     if (DSTy->isLiteral() != SSTy->isLiteral() ||
183         DSTy->isPacked() != SSTy->isPacked())
184       return false;
185   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187       return false;
188   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
190       return false;
191   }
192
193   // Otherwise, we speculate that these two types will line up and recursively
194   // check the subelements.
195   Entry = DstTy;
196   SpeculativeTypes.push_back(SrcTy);
197
198   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199     if (!areTypesIsomorphic(DstTy->getContainedType(I),
200                             SrcTy->getContainedType(I)))
201       return false;
202
203   // If everything seems to have lined up, then everything is great.
204   return true;
205 }
206
207 void TypeMapTy::linkDefinedTypeBodies() {
208   SmallVector<Type *, 16> Elements;
209   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
210     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211     assert(DstSTy->isOpaque());
212
213     // Map the body of the source type over to a new body for the dest type.
214     Elements.resize(SrcSTy->getNumElements());
215     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
216       Elements[I] = get(SrcSTy->getElementType(I));
217
218     DstSTy->setBody(Elements, SrcSTy->isPacked());
219     DstStructTypesSet.switchToNonOpaque(DstSTy);
220   }
221   SrcDefinitionsToResolve.clear();
222   DstResolvedOpaqueTypes.clear();
223 }
224
225 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
226                            ArrayRef<Type *> ETypes) {
227   DTy->setBody(ETypes, STy->isPacked());
228
229   // Steal STy's name.
230   if (STy->hasName()) {
231     SmallString<16> TmpName = STy->getName();
232     STy->setName("");
233     DTy->setName(TmpName);
234   }
235
236   DstStructTypesSet.addNonOpaque(DTy);
237 }
238
239 Type *TypeMapTy::get(Type *Ty) {
240   SmallPtrSet<StructType *, 8> Visited;
241   return get(Ty, Visited);
242 }
243
244 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245   // If we already have an entry for this type, return it.
246   Type **Entry = &MappedTypes[Ty];
247   if (*Entry)
248     return *Entry;
249
250   // These are types that LLVM itself will unique.
251   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
252
253 #ifndef NDEBUG
254   if (!IsUniqued) {
255     for (auto &Pair : MappedTypes) {
256       assert(!(Pair.first != Ty && Pair.second == Ty) &&
257              "mapping to a source type");
258     }
259   }
260 #endif
261
262   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
263     StructType *DTy = StructType::create(Ty->getContext());
264     return *Entry = DTy;
265   }
266
267   // If this is not a recursive type, then just map all of the elements and
268   // then rebuild the type from inside out.
269   SmallVector<Type *, 4> ElementTypes;
270
271   // If there are no element types to map, then the type is itself.  This is
272   // true for the anonymous {} struct, things like 'float', integers, etc.
273   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
274     return *Entry = Ty;
275
276   // Remap all of the elements, keeping track of whether any of them change.
277   bool AnyChange = false;
278   ElementTypes.resize(Ty->getNumContainedTypes());
279   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
280     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
282   }
283
284   // If we found our type while recursively processing stuff, just use it.
285   Entry = &MappedTypes[Ty];
286   if (*Entry) {
287     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
288       if (DTy->isOpaque()) {
289         auto *STy = cast<StructType>(Ty);
290         finishType(DTy, STy, ElementTypes);
291       }
292     }
293     return *Entry;
294   }
295
296   // If all of the element types mapped directly over and the type is not
297   // a nomed struct, then the type is usable as-is.
298   if (!AnyChange && IsUniqued)
299     return *Entry = Ty;
300
301   // Otherwise, rebuild a modified type.
302   switch (Ty->getTypeID()) {
303   default:
304     llvm_unreachable("unknown derived type to remap");
305   case Type::ArrayTyID:
306     return *Entry = ArrayType::get(ElementTypes[0],
307                                    cast<ArrayType>(Ty)->getNumElements());
308   case Type::VectorTyID:
309     return *Entry = VectorType::get(ElementTypes[0],
310                                     cast<VectorType>(Ty)->getNumElements());
311   case Type::PointerTyID:
312     return *Entry = PointerType::get(ElementTypes[0],
313                                      cast<PointerType>(Ty)->getAddressSpace());
314   case Type::FunctionTyID:
315     return *Entry = FunctionType::get(ElementTypes[0],
316                                       makeArrayRef(ElementTypes).slice(1),
317                                       cast<FunctionType>(Ty)->isVarArg());
318   case Type::StructTyID: {
319     auto *STy = cast<StructType>(Ty);
320     bool IsPacked = STy->isPacked();
321     if (IsUniqued)
322       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
323
324     // If the type is opaque, we can just use it directly.
325     if (STy->isOpaque()) {
326       DstStructTypesSet.addOpaque(STy);
327       return *Entry = Ty;
328     }
329
330     if (StructType *OldT =
331             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
332       STy->setName("");
333       return *Entry = OldT;
334     }
335
336     if (!AnyChange) {
337       DstStructTypesSet.addNonOpaque(STy);
338       return *Entry = Ty;
339     }
340
341     StructType *DTy = StructType::create(Ty->getContext());
342     finishType(DTy, STy, ElementTypes);
343     return *Entry = DTy;
344   }
345   }
346 }
347
348 //===----------------------------------------------------------------------===//
349 // ModuleLinker implementation.
350 //===----------------------------------------------------------------------===//
351
352 namespace {
353 class ModuleLinker;
354
355 /// Creates prototypes for functions that are lazily linked on the fly. This
356 /// speeds up linking for modules with many/ lazily linked functions of which
357 /// few get used.
358 class ValueMaterializerTy final : public ValueMaterializer {
359   ModuleLinker *ModLinker;
360
361 public:
362   ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
363
364   Value *materializeDeclFor(Value *V) override;
365   void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
366 };
367
368 class LinkDiagnosticInfo : public DiagnosticInfo {
369   const Twine &Msg;
370
371 public:
372   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373   void print(DiagnosticPrinter &DP) const override;
374 };
375 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
376                                        const Twine &Msg)
377     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
379
380 /// This is an implementation class for the LinkModules function, which is the
381 /// entrypoint for this file.
382 class ModuleLinker {
383   Module &DstM;
384   Module &SrcM;
385
386   TypeMapTy TypeMap;
387   ValueMaterializerTy ValMaterializer;
388
389   /// Mapping of values from what they used to be in Src, to what they are now
390   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
391   /// due to the use of Value handles which the Linker doesn't actually need,
392   /// but this allows us to reuse the ValueMapper code.
393   ValueToValueMapTy ValueMap;
394
395   SetVector<GlobalValue *> ValuesToLink;
396
397   DiagnosticHandlerFunction DiagnosticHandler;
398
399   /// For symbol clashes, prefer those from Src.
400   unsigned Flags;
401
402   /// Function index passed into ModuleLinker for using in function
403   /// importing/exporting handling.
404   const FunctionInfoIndex *ImportIndex;
405
406   /// Function to import from source module, all other functions are
407   /// imported as declarations instead of definitions.
408   DenseSet<const GlobalValue *> *ImportFunction;
409
410   /// Set to true if the given FunctionInfoIndex contains any functions
411   /// from this source module, in which case we must conservatively assume
412   /// that any of its functions may be imported into another module
413   /// as part of a different backend compilation process.
414   bool HasExportedFunctions = false;
415
416   /// Set to true when all global value body linking is complete (including
417   /// lazy linking). Used to prevent metadata linking from creating new
418   /// references.
419   bool DoneLinkingBodies = false;
420
421   bool HasError = false;
422
423   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
424   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
425   bool shouldInternalizeLinkedSymbols() {
426     return Flags & Linker::InternalizeLinkedSymbols;
427   }
428
429   /// Handles cloning of a global values from the source module into
430   /// the destination module, including setting the attributes and visibility.
431   GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
432
433   /// Check if we should promote the given local value to global scope.
434   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
435
436   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
437                             const GlobalValue &Src);
438
439   /// Helper method for setting a message and returning an error code.
440   bool emitError(const Twine &Message) {
441     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
442     HasError = true;
443     return true;
444   }
445
446   void emitWarning(const Twine &Message) {
447     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
448   }
449
450   bool getComdatLeader(Module &M, StringRef ComdatName,
451                        const GlobalVariable *&GVar);
452   bool computeResultingSelectionKind(StringRef ComdatName,
453                                      Comdat::SelectionKind Src,
454                                      Comdat::SelectionKind Dst,
455                                      Comdat::SelectionKind &Result,
456                                      bool &LinkFromSrc);
457   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
458       ComdatsChosen;
459   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
460                        bool &LinkFromSrc);
461   // Keep track of the global value members of each comdat in source.
462   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
463
464   /// Given a global in the source module, return the global in the
465   /// destination module that is being linked to, if any.
466   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
467     // If the source has no name it can't link.  If it has local linkage,
468     // there is no name match-up going on.
469     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
470       return nullptr;
471
472     // Otherwise see if we have a match in the destination module's symtab.
473     GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
474     if (!DGV)
475       return nullptr;
476
477     // If we found a global with the same name in the dest module, but it has
478     // internal linkage, we are really not doing any linkage here.
479     if (DGV->hasLocalLinkage())
480       return nullptr;
481
482     // Otherwise, we do in fact link to the destination global.
483     return DGV;
484   }
485
486   void computeTypeMapping();
487
488   bool linkIfNeeded(GlobalValue &GV);
489   Constant *linkAppendingVarProto(GlobalVariable *DstGV,
490                                   const GlobalVariable *SrcGV);
491
492   Constant *linkGlobalValueProto(GlobalValue *GV);
493   bool linkModuleFlagsMetadata();
494
495   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496   bool linkFunctionBody(Function &Dst, Function &Src);
497   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498   bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
499
500   /// Functions that take care of cloning a specific global value type
501   /// into the destination module.
502   GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503   Function *copyFunctionProto(const Function *SF);
504   GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
505
506   /// Helper methods to check if we are importing from or potentially
507   /// exporting from the current source module.
508   bool isPerformingImport() { return ImportFunction != nullptr; }
509   bool isModuleExporting() { return HasExportedFunctions; }
510
511   /// If we are importing from the source module, checks if we should
512   /// import SGV as a definition, otherwise import as a declaration.
513   bool doImportAsDefinition(const GlobalValue *SGV);
514
515   /// Get the name for SGV that should be used in the linked destination
516   /// module. Specifically, this handles the case where we need to rename
517   /// a local that is being promoted to global scope.
518   std::string getName(const GlobalValue *SGV);
519
520   /// Get the new linkage for SGV that should be used in the linked destination
521   /// module. Specifically, for ThinLTO importing or exporting it may need
522   /// to be adjusted.
523   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
524
525   /// Copies the necessary global value attributes and name from the source
526   /// to the newly cloned global value.
527   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
528
529   /// Updates the visibility for the new global cloned from the source
530   /// and, if applicable, linked with an existing destination global.
531   /// Handles visibility change required for promoted locals.
532   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
533                      const GlobalValue *DGV = nullptr);
534
535   void linkNamedMDNodes();
536
537 public:
538   ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
539                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
540                const FunctionInfoIndex *Index = nullptr,
541                DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
542       : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
543         DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
544         ImportFunction(FunctionsToImport) {
545     assert((ImportIndex || !ImportFunction) &&
546            "Expect a FunctionInfoIndex when importing");
547     // If we have a FunctionInfoIndex but no function to import,
548     // then this is the primary module being compiled in a ThinLTO
549     // backend compilation, and we need to see if it has functions that
550     // may be exported to another backend compilation.
551     if (ImportIndex && !ImportFunction)
552       HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
553   }
554
555   bool run();
556   Value *materializeDeclFor(Value *V);
557   void materializeInitFor(GlobalValue *New, GlobalValue *Old);
558 };
559 }
560
561 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
562 /// table. This is good for all clients except for us. Go through the trouble
563 /// to force this back.
564 static void forceRenaming(GlobalValue *GV, StringRef Name) {
565   // If the global doesn't force its name or if it already has the right name,
566   // there is nothing for us to do.
567   // Note that any required local to global promotion should already be done,
568   // so promoted locals will not skip this handling as their linkage is no
569   // longer local.
570   if (GV->hasLocalLinkage() || GV->getName() == Name)
571     return;
572
573   Module *M = GV->getParent();
574
575   // If there is a conflict, rename the conflict.
576   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
577     GV->takeName(ConflictGV);
578     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
579     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
580   } else {
581     GV->setName(Name); // Force the name back
582   }
583 }
584
585 /// copy additional attributes (those not needed to construct a GlobalValue)
586 /// from the SrcGV to the DestGV.
587 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
588                                     const GlobalValue *SrcGV) {
589   NewGV->copyAttributesFrom(SrcGV);
590   forceRenaming(NewGV, getName(SrcGV));
591 }
592
593 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
594   if (!isPerformingImport())
595     return false;
596   auto *GA = dyn_cast<GlobalAlias>(SGV);
597   if (GA) {
598     if (GA->hasWeakAnyLinkage())
599       return false;
600     const GlobalObject *GO = GA->getBaseObject();
601     if (!GO->hasLinkOnceODRLinkage())
602       return false;
603     return doImportAsDefinition(GO);
604   }
605   // Always import GlobalVariable definitions, except for the special
606   // case of WeakAny which are imported as ExternalWeak declarations
607   // (see comments in ModuleLinker::getLinkage). The linkage changes
608   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
609   // global variables with external linkage are transformed to
610   // available_externally definitions, which are ultimately turned into
611   // declarations after the EliminateAvailableExternally pass).
612   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
613       !SGV->hasWeakAnyLinkage())
614     return true;
615   // Only import the function requested for importing.
616   auto *SF = dyn_cast<Function>(SGV);
617   if (SF && ImportFunction->count(SF))
618     return true;
619   // Otherwise no.
620   return false;
621 }
622
623 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
624   assert(SGV->hasLocalLinkage());
625   // Both the imported references and the original local variable must
626   // be promoted.
627   if (!isPerformingImport() && !isModuleExporting())
628     return false;
629
630   // Local const variables never need to be promoted unless they are address
631   // taken. The imported uses can simply use the clone created in this module.
632   // For now we are conservative in determining which variables are not
633   // address taken by checking the unnamed addr flag. To be more aggressive,
634   // the address taken information must be checked earlier during parsing
635   // of the module and recorded in the function index for use when importing
636   // from that module.
637   auto *GVar = dyn_cast<GlobalVariable>(SGV);
638   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
639     return false;
640
641   // Eventually we only need to promote functions in the exporting module that
642   // are referenced by a potentially exported function (i.e. one that is in the
643   // function index).
644   return true;
645 }
646
647 std::string ModuleLinker::getName(const GlobalValue *SGV) {
648   // For locals that must be promoted to global scope, ensure that
649   // the promoted name uniquely identifies the copy in the original module,
650   // using the ID assigned during combined index creation. When importing,
651   // we rename all locals (not just those that are promoted) in order to
652   // avoid naming conflicts between locals imported from different modules.
653   if (SGV->hasLocalLinkage() &&
654       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
655     return FunctionInfoIndex::getGlobalNameForLocal(
656         SGV->getName(),
657         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
658   return SGV->getName();
659 }
660
661 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
662   // Any local variable that is referenced by an exported function needs
663   // to be promoted to global scope. Since we don't currently know which
664   // functions reference which local variables/functions, we must treat
665   // all as potentially exported if this module is exporting anything.
666   if (isModuleExporting()) {
667     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
668       return GlobalValue::ExternalLinkage;
669     return SGV->getLinkage();
670   }
671
672   // Otherwise, if we aren't importing, no linkage change is needed.
673   if (!isPerformingImport())
674     return SGV->getLinkage();
675
676   switch (SGV->getLinkage()) {
677   case GlobalValue::ExternalLinkage:
678     // External defnitions are converted to available_externally
679     // definitions upon import, so that they are available for inlining
680     // and/or optimization, but are turned into declarations later
681     // during the EliminateAvailableExternally pass.
682     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
683       return GlobalValue::AvailableExternallyLinkage;
684     // An imported external declaration stays external.
685     return SGV->getLinkage();
686
687   case GlobalValue::AvailableExternallyLinkage:
688     // An imported available_externally definition converts
689     // to external if imported as a declaration.
690     if (!doImportAsDefinition(SGV))
691       return GlobalValue::ExternalLinkage;
692     // An imported available_externally declaration stays that way.
693     return SGV->getLinkage();
694
695   case GlobalValue::LinkOnceAnyLinkage:
696   case GlobalValue::LinkOnceODRLinkage:
697     // These both stay the same when importing the definition.
698     // The ThinLTO pass will eventually force-import their definitions.
699     return SGV->getLinkage();
700
701   case GlobalValue::WeakAnyLinkage:
702     // Can't import weak_any definitions correctly, or we might change the
703     // program semantics, since the linker will pick the first weak_any
704     // definition and importing would change the order they are seen by the
705     // linker. The module linking caller needs to enforce this.
706     assert(!doImportAsDefinition(SGV));
707     // If imported as a declaration, it becomes external_weak.
708     return GlobalValue::ExternalWeakLinkage;
709
710   case GlobalValue::WeakODRLinkage:
711     // For weak_odr linkage, there is a guarantee that all copies will be
712     // equivalent, so the issue described above for weak_any does not exist,
713     // and the definition can be imported. It can be treated similarly
714     // to an imported externally visible global value.
715     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
716       return GlobalValue::AvailableExternallyLinkage;
717     else
718       return GlobalValue::ExternalLinkage;
719
720   case GlobalValue::AppendingLinkage:
721     // It would be incorrect to import an appending linkage variable,
722     // since it would cause global constructors/destructors to be
723     // executed multiple times. This should have already been handled
724     // by linkIfNeeded, and we will assert in shouldLinkFromSource
725     // if we try to import, so we simply return AppendingLinkage here
726     // as this helper is called more widely in getLinkedToGlobal.
727     return GlobalValue::AppendingLinkage;
728
729   case GlobalValue::InternalLinkage:
730   case GlobalValue::PrivateLinkage:
731     // If we are promoting the local to global scope, it is handled
732     // similarly to a normal externally visible global.
733     if (doPromoteLocalToGlobal(SGV)) {
734       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
735         return GlobalValue::AvailableExternallyLinkage;
736       else
737         return GlobalValue::ExternalLinkage;
738     }
739     // A non-promoted imported local definition stays local.
740     // The ThinLTO pass will eventually force-import their definitions.
741     return SGV->getLinkage();
742
743   case GlobalValue::ExternalWeakLinkage:
744     // External weak doesn't apply to definitions, must be a declaration.
745     assert(!doImportAsDefinition(SGV));
746     // Linkage stays external_weak.
747     return SGV->getLinkage();
748
749   case GlobalValue::CommonLinkage:
750     // Linkage stays common on definitions.
751     // The ThinLTO pass will eventually force-import their definitions.
752     return SGV->getLinkage();
753   }
754
755   llvm_unreachable("unknown linkage type");
756 }
757
758 /// Loop through the global variables in the src module and merge them into the
759 /// dest module.
760 GlobalVariable *
761 ModuleLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
762   // No linking to be performed or linking from the source: simply create an
763   // identical version of the symbol over in the dest module... the
764   // initializer will be filled in later by LinkGlobalInits.
765   GlobalVariable *NewDGV =
766       new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
767                          SGVar->isConstant(), GlobalValue::ExternalLinkage,
768                          /*init*/ nullptr, getName(SGVar),
769                          /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
770                          SGVar->getType()->getAddressSpace());
771
772   return NewDGV;
773 }
774
775 /// Link the function in the source module into the destination module if
776 /// needed, setting up mapping information.
777 Function *ModuleLinker::copyFunctionProto(const Function *SF) {
778   // If there is no linkage to be performed or we are linking from the source,
779   // bring SF over.
780   return Function::Create(TypeMap.get(SF->getFunctionType()),
781                           GlobalValue::ExternalLinkage, getName(SF), &DstM);
782 }
783
784 /// Set up prototypes for any aliases that come over from the source module.
785 GlobalValue *ModuleLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
786   // If there is no linkage to be performed or we're linking from the source,
787   // bring over SGA.
788   auto *Ty = TypeMap.get(SGA->getValueType());
789   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
790                              GlobalValue::ExternalLinkage, getName(SGA), &DstM);
791 }
792
793 static GlobalValue::VisibilityTypes
794 getMinVisibility(GlobalValue::VisibilityTypes A,
795                  GlobalValue::VisibilityTypes B) {
796   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
797     return GlobalValue::HiddenVisibility;
798   if (A == GlobalValue::ProtectedVisibility ||
799       B == GlobalValue::ProtectedVisibility)
800     return GlobalValue::ProtectedVisibility;
801   return GlobalValue::DefaultVisibility;
802 }
803
804 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
805                                  const GlobalValue *DGV) {
806   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
807   if (DGV)
808     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
809   // For promoted locals, mark them hidden so that they can later be
810   // stripped from the symbol table to reduce bloat.
811   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
812     Visibility = GlobalValue::HiddenVisibility;
813   NewGV->setVisibility(Visibility);
814 }
815
816 GlobalValue *ModuleLinker::copyGlobalValueProto(const GlobalValue *SGV,
817                                                 bool ForDefinition) {
818   GlobalValue *NewGV;
819   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
820     NewGV = copyGlobalVariableProto(SGVar);
821   } else if (auto *SF = dyn_cast<Function>(SGV)) {
822     NewGV = copyFunctionProto(SF);
823   } else {
824     if (ForDefinition)
825       NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
826     else
827       NewGV = new GlobalVariable(
828           DstM, TypeMap.get(SGV->getType()->getElementType()),
829           /*isConstant*/ false, GlobalValue::ExternalLinkage,
830           /*init*/ nullptr, getName(SGV),
831           /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
832           SGV->getType()->getAddressSpace());
833   }
834
835   if (ForDefinition)
836     NewGV->setLinkage(getLinkage(SGV));
837   else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
838            SGV->hasLinkOnceLinkage())
839     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
840
841   copyGVAttributes(NewGV, SGV);
842   return NewGV;
843 }
844
845 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
846   return ModLinker->materializeDeclFor(V);
847 }
848
849 Value *ModuleLinker::materializeDeclFor(Value *V) {
850   auto *SGV = dyn_cast<GlobalValue>(V);
851   if (!SGV)
852     return nullptr;
853
854   return linkGlobalValueProto(SGV);
855 }
856
857 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
858                                              GlobalValue *Old) {
859   return ModLinker->materializeInitFor(New, Old);
860 }
861
862 static bool shouldLazyLink(const GlobalValue &GV) {
863   return GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
864          GV.hasAvailableExternallyLinkage();
865 }
866
867 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
868   if (auto *F = dyn_cast<Function>(New)) {
869     if (!F->isDeclaration())
870       return;
871   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
872     if (V->hasInitializer())
873       return;
874   } else {
875     auto *A = cast<GlobalAlias>(New);
876     if (A->getAliasee())
877       return;
878   }
879
880   if (Old->isDeclaration())
881     return;
882
883   if (isPerformingImport() && !doImportAsDefinition(Old))
884     return;
885
886   if (!ValuesToLink.count(Old) && !shouldLazyLink(*Old))
887     return;
888
889   linkGlobalValueBody(*New, *Old);
890 }
891
892 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
893                                    const GlobalVariable *&GVar) {
894   const GlobalValue *GVal = M.getNamedValue(ComdatName);
895   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
896     GVal = GA->getBaseObject();
897     if (!GVal)
898       // We cannot resolve the size of the aliasee yet.
899       return emitError("Linking COMDATs named '" + ComdatName +
900                        "': COMDAT key involves incomputable alias size.");
901   }
902
903   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
904   if (!GVar)
905     return emitError(
906         "Linking COMDATs named '" + ComdatName +
907         "': GlobalVariable required for data dependent selection!");
908
909   return false;
910 }
911
912 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
913                                                  Comdat::SelectionKind Src,
914                                                  Comdat::SelectionKind Dst,
915                                                  Comdat::SelectionKind &Result,
916                                                  bool &LinkFromSrc) {
917   // The ability to mix Comdat::SelectionKind::Any with
918   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
919   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
920                          Dst == Comdat::SelectionKind::Largest;
921   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
922                          Src == Comdat::SelectionKind::Largest;
923   if (DstAnyOrLargest && SrcAnyOrLargest) {
924     if (Dst == Comdat::SelectionKind::Largest ||
925         Src == Comdat::SelectionKind::Largest)
926       Result = Comdat::SelectionKind::Largest;
927     else
928       Result = Comdat::SelectionKind::Any;
929   } else if (Src == Dst) {
930     Result = Dst;
931   } else {
932     return emitError("Linking COMDATs named '" + ComdatName +
933                      "': invalid selection kinds!");
934   }
935
936   switch (Result) {
937   case Comdat::SelectionKind::Any:
938     // Go with Dst.
939     LinkFromSrc = false;
940     break;
941   case Comdat::SelectionKind::NoDuplicates:
942     return emitError("Linking COMDATs named '" + ComdatName +
943                      "': noduplicates has been violated!");
944   case Comdat::SelectionKind::ExactMatch:
945   case Comdat::SelectionKind::Largest:
946   case Comdat::SelectionKind::SameSize: {
947     const GlobalVariable *DstGV;
948     const GlobalVariable *SrcGV;
949     if (getComdatLeader(DstM, ComdatName, DstGV) ||
950         getComdatLeader(SrcM, ComdatName, SrcGV))
951       return true;
952
953     const DataLayout &DstDL = DstM.getDataLayout();
954     const DataLayout &SrcDL = SrcM.getDataLayout();
955     uint64_t DstSize =
956         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
957     uint64_t SrcSize =
958         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
959     if (Result == Comdat::SelectionKind::ExactMatch) {
960       if (SrcGV->getInitializer() != DstGV->getInitializer())
961         return emitError("Linking COMDATs named '" + ComdatName +
962                          "': ExactMatch violated!");
963       LinkFromSrc = false;
964     } else if (Result == Comdat::SelectionKind::Largest) {
965       LinkFromSrc = SrcSize > DstSize;
966     } else if (Result == Comdat::SelectionKind::SameSize) {
967       if (SrcSize != DstSize)
968         return emitError("Linking COMDATs named '" + ComdatName +
969                          "': SameSize violated!");
970       LinkFromSrc = false;
971     } else {
972       llvm_unreachable("unknown selection kind");
973     }
974     break;
975   }
976   }
977
978   return false;
979 }
980
981 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
982                                    Comdat::SelectionKind &Result,
983                                    bool &LinkFromSrc) {
984   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
985   StringRef ComdatName = SrcC->getName();
986   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
987   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
988
989   if (DstCI == ComdatSymTab.end()) {
990     // Use the comdat if it is only available in one of the modules.
991     LinkFromSrc = true;
992     Result = SSK;
993     return false;
994   }
995
996   const Comdat *DstC = &DstCI->second;
997   Comdat::SelectionKind DSK = DstC->getSelectionKind();
998   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
999                                        LinkFromSrc);
1000 }
1001
1002 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1003                                         const GlobalValue &Dest,
1004                                         const GlobalValue &Src) {
1005   // Should we unconditionally use the Src?
1006   if (shouldOverrideFromSrc()) {
1007     LinkFromSrc = true;
1008     return false;
1009   }
1010
1011   // We always have to add Src if it has appending linkage.
1012   if (Src.hasAppendingLinkage()) {
1013     // Should have prevented importing for appending linkage in linkIfNeeded.
1014     assert(!isPerformingImport());
1015     LinkFromSrc = true;
1016     return false;
1017   }
1018
1019   bool SrcIsDeclaration = Src.isDeclarationForLinker();
1020   bool DestIsDeclaration = Dest.isDeclarationForLinker();
1021
1022   if (isPerformingImport()) {
1023     if (isa<Function>(&Src)) {
1024       // For functions, LinkFromSrc iff this is the function requested
1025       // for importing. For variables, decide below normally.
1026       LinkFromSrc = ImportFunction->count(&Src);
1027       return false;
1028     }
1029
1030     // Check if this is an alias with an already existing definition
1031     // in Dest, which must have come from a prior importing pass from
1032     // the same Src module. Unlike imported function and variable
1033     // definitions, which are imported as available_externally and are
1034     // not definitions for the linker, that is not a valid linkage for
1035     // imported aliases which must be definitions. Simply use the existing
1036     // Dest copy.
1037     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1038       assert(isa<GlobalAlias>(&Dest));
1039       LinkFromSrc = false;
1040       return false;
1041     }
1042   }
1043
1044   if (SrcIsDeclaration) {
1045     // If Src is external or if both Src & Dest are external..  Just link the
1046     // external globals, we aren't adding anything.
1047     if (Src.hasDLLImportStorageClass()) {
1048       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1049       LinkFromSrc = DestIsDeclaration;
1050       return false;
1051     }
1052     // If the Dest is weak, use the source linkage.
1053     if (Dest.hasExternalWeakLinkage()) {
1054       LinkFromSrc = true;
1055       return false;
1056     }
1057     // Link an available_externally over a declaration.
1058     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
1059     return false;
1060   }
1061
1062   if (DestIsDeclaration) {
1063     // If Dest is external but Src is not:
1064     LinkFromSrc = true;
1065     return false;
1066   }
1067
1068   if (Src.hasCommonLinkage()) {
1069     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1070       LinkFromSrc = true;
1071       return false;
1072     }
1073
1074     if (!Dest.hasCommonLinkage()) {
1075       LinkFromSrc = false;
1076       return false;
1077     }
1078
1079     const DataLayout &DL = Dest.getParent()->getDataLayout();
1080     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1081     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1082     LinkFromSrc = SrcSize > DestSize;
1083     return false;
1084   }
1085
1086   if (Src.isWeakForLinker()) {
1087     assert(!Dest.hasExternalWeakLinkage());
1088     assert(!Dest.hasAvailableExternallyLinkage());
1089
1090     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1091       LinkFromSrc = true;
1092       return false;
1093     }
1094
1095     LinkFromSrc = false;
1096     return false;
1097   }
1098
1099   if (Dest.isWeakForLinker()) {
1100     assert(Src.hasExternalLinkage());
1101     LinkFromSrc = true;
1102     return false;
1103   }
1104
1105   assert(!Src.hasExternalWeakLinkage());
1106   assert(!Dest.hasExternalWeakLinkage());
1107   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1108          "Unexpected linkage type!");
1109   return emitError("Linking globals named '" + Src.getName() +
1110                    "': symbol multiply defined!");
1111 }
1112
1113 /// Loop over all of the linked values to compute type mappings.  For example,
1114 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1115 /// types 'Foo' but one got renamed when the module was loaded into the same
1116 /// LLVMContext.
1117 void ModuleLinker::computeTypeMapping() {
1118   for (GlobalValue &SGV : SrcM.globals()) {
1119     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1120     if (!DGV)
1121       continue;
1122
1123     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1124       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1125       continue;
1126     }
1127
1128     // Unify the element type of appending arrays.
1129     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1130     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1131     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1132   }
1133
1134   for (GlobalValue &SGV : SrcM) {
1135     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1136       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1137   }
1138
1139   for (GlobalValue &SGV : SrcM.aliases()) {
1140     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1141       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1142   }
1143
1144   // Incorporate types by name, scanning all the types in the source module.
1145   // At this point, the destination module may have a type "%foo = { i32 }" for
1146   // example.  When the source module got loaded into the same LLVMContext, if
1147   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1148   std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1149   for (StructType *ST : Types) {
1150     if (!ST->hasName())
1151       continue;
1152
1153     // Check to see if there is a dot in the name followed by a digit.
1154     size_t DotPos = ST->getName().rfind('.');
1155     if (DotPos == 0 || DotPos == StringRef::npos ||
1156         ST->getName().back() == '.' ||
1157         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1158       continue;
1159
1160     // Check to see if the destination module has a struct with the prefix name.
1161     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1162     if (!DST)
1163       continue;
1164
1165     // Don't use it if this actually came from the source module. They're in
1166     // the same LLVMContext after all. Also don't use it unless the type is
1167     // actually used in the destination module. This can happen in situations
1168     // like this:
1169     //
1170     //      Module A                         Module B
1171     //      --------                         --------
1172     //   %Z = type { %A }                %B = type { %C.1 }
1173     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
1174     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
1175     //   %C = type { i8* }               %B.3 = type { %C.1 }
1176     //
1177     // When we link Module B with Module A, the '%B' in Module B is
1178     // used. However, that would then use '%C.1'. But when we process '%C.1',
1179     // we prefer to take the '%C' version. So we are then left with both
1180     // '%C.1' and '%C' being used for the same types. This leads to some
1181     // variables using one type and some using the other.
1182     if (TypeMap.DstStructTypesSet.hasType(DST))
1183       TypeMap.addTypeMapping(DST, ST);
1184   }
1185
1186   // Now that we have discovered all of the type equivalences, get a body for
1187   // any 'opaque' types in the dest module that are now resolved.
1188   TypeMap.linkDefinedTypeBodies();
1189 }
1190
1191 static void getArrayElements(const Constant *C,
1192                              SmallVectorImpl<Constant *> &Dest) {
1193   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1194
1195   for (unsigned i = 0; i != NumElements; ++i)
1196     Dest.push_back(C->getAggregateElement(i));
1197 }
1198
1199 /// If there were any appending global variables, link them together now.
1200 /// Return true on error.
1201 Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1202                                               const GlobalVariable *SrcGV) {
1203   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
1204                     ->getElementType();
1205
1206   StringRef Name = SrcGV->getName();
1207   bool IsNewStructor = false;
1208   bool IsOldStructor = false;
1209   if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
1210     if (cast<StructType>(EltTy)->getNumElements() == 3)
1211       IsNewStructor = true;
1212     else
1213       IsOldStructor = true;
1214   }
1215
1216   PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
1217   if (IsOldStructor) {
1218     auto &ST = *cast<StructType>(EltTy);
1219     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1220     EltTy = StructType::get(SrcGV->getContext(), Tys, false);
1221   }
1222
1223   if (DstGV) {
1224     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1225
1226     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
1227       emitError(
1228           "Linking globals named '" + SrcGV->getName() +
1229           "': can only link appending global with another appending global!");
1230       return nullptr;
1231     }
1232
1233     // Check to see that they two arrays agree on type.
1234     if (EltTy != DstTy->getElementType()) {
1235       emitError("Appending variables with different element types!");
1236       return nullptr;
1237     }
1238     if (DstGV->isConstant() != SrcGV->isConstant()) {
1239       emitError("Appending variables linked with different const'ness!");
1240       return nullptr;
1241     }
1242
1243     if (DstGV->getAlignment() != SrcGV->getAlignment()) {
1244       emitError(
1245           "Appending variables with different alignment need to be linked!");
1246       return nullptr;
1247     }
1248
1249     if (DstGV->getVisibility() != SrcGV->getVisibility()) {
1250       emitError(
1251           "Appending variables with different visibility need to be linked!");
1252       return nullptr;
1253     }
1254
1255     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
1256       emitError(
1257           "Appending variables with different unnamed_addr need to be linked!");
1258       return nullptr;
1259     }
1260
1261     if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
1262       emitError(
1263           "Appending variables with different section name need to be linked!");
1264       return nullptr;
1265     }
1266   }
1267
1268   SmallVector<Constant *, 16> DstElements;
1269   if (DstGV)
1270     getArrayElements(DstGV->getInitializer(), DstElements);
1271
1272   SmallVector<Constant *, 16> SrcElements;
1273   getArrayElements(SrcGV->getInitializer(), SrcElements);
1274
1275   if (IsNewStructor)
1276     SrcElements.erase(
1277         std::remove_if(SrcElements.begin(), SrcElements.end(),
1278                        [this](Constant *E) {
1279                          auto *Key = dyn_cast<GlobalValue>(
1280                              E->getAggregateElement(2)->stripPointerCasts());
1281                          return Key && !ValuesToLink.count(Key) &&
1282                                 !shouldLazyLink(*Key);
1283                        }),
1284         SrcElements.end());
1285   uint64_t NewSize = DstElements.size() + SrcElements.size();
1286   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1287
1288   // Create the new global variable.
1289   GlobalVariable *NG = new GlobalVariable(
1290       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1291       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1292       SrcGV->getType()->getAddressSpace());
1293
1294   // Propagate alignment, visibility and section info.
1295   copyGVAttributes(NG, SrcGV);
1296
1297   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1298
1299   // Stop recursion.
1300   ValueMap[SrcGV] = Ret;
1301
1302   for (auto *V : SrcElements) {
1303     Constant *NewV;
1304     if (IsOldStructor) {
1305       auto *S = cast<ConstantStruct>(V);
1306       auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
1307                           &TypeMap, &ValMaterializer);
1308       auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
1309                           &TypeMap, &ValMaterializer);
1310       Value *Null = Constant::getNullValue(VoidPtrTy);
1311       NewV =
1312           ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1313     } else {
1314       NewV =
1315           MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1316     }
1317     DstElements.push_back(NewV);
1318   }
1319
1320   NG->setInitializer(ConstantArray::get(NewType, DstElements));
1321
1322   // Replace any uses of the two global variables with uses of the new
1323   // global.
1324   if (DstGV) {
1325     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1326     DstGV->eraseFromParent();
1327   }
1328
1329   return Ret;
1330 }
1331
1332 Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1333   GlobalValue *DGV = getLinkedToGlobal(SGV);
1334
1335   // Handle the ultra special appending linkage case first.
1336   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1337   if (SGV->hasAppendingLinkage()) {
1338     // Should have prevented importing for appending linkage in linkIfNeeded.
1339     assert(!isPerformingImport());
1340     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1341                                  cast<GlobalVariable>(SGV));
1342   }
1343
1344   bool LinkFromSrc = true;
1345   Comdat *C = nullptr;
1346   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1347
1348   if (isPerformingImport() && !doImportAsDefinition(SGV)) {
1349     LinkFromSrc = false;
1350   } else if (const Comdat *SC = SGV->getComdat()) {
1351     Comdat::SelectionKind SK;
1352     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1353     C = DstM.getOrInsertComdat(SC->getName());
1354     C->setSelectionKind(SK);
1355     if (SGV->hasLocalLinkage())
1356       LinkFromSrc = true;
1357   } else if (DGV) {
1358     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1359       return nullptr;
1360   }
1361
1362   if (DGV)
1363     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1364
1365   GlobalValue *NewGV;
1366   if (!LinkFromSrc && DGV) {
1367     NewGV = DGV;
1368   } else {
1369     // If we are done linking global value bodies (i.e. we are performing
1370     // metadata linking), don't link in the global value due to this
1371     // reference, simply map it to null.
1372     if (DoneLinkingBodies)
1373       return nullptr;
1374
1375     NewGV = copyGlobalValueProto(SGV, LinkFromSrc);
1376   }
1377
1378   setVisibility(NewGV, SGV, DGV);
1379   NewGV->setUnnamedAddr(HasUnnamedAddr);
1380
1381   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1382     if (C && LinkFromSrc)
1383       NewGO->setComdat(C);
1384
1385     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1386       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1387   }
1388
1389   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1390     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1391     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1392     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1393         (!DGVar->isConstant() || !SGVar->isConstant()))
1394       NewGVar->setConstant(false);
1395   }
1396
1397   if (NewGV != DGV && DGV) {
1398     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1399     DGV->eraseFromParent();
1400   }
1401
1402   return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1403 }
1404
1405 /// Update the initializers in the Dest module now that all globals that may be
1406 /// referenced are in Dest.
1407 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1408   // Figure out what the initializer looks like in the dest module.
1409   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1410                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1411 }
1412
1413 /// Copy the source function over into the dest function and fix up references
1414 /// to values. At this point we know that Dest is an external function, and
1415 /// that Src is not.
1416 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1417   assert(Dst.isDeclaration() && !Src.isDeclaration());
1418
1419   // Materialize if needed.
1420   if (std::error_code EC = Src.materialize())
1421     return emitError(EC.message());
1422
1423   // Link in the prefix data.
1424   if (Src.hasPrefixData())
1425     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1426                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1427
1428   // Link in the prologue data.
1429   if (Src.hasPrologueData())
1430     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1431                                  RF_MoveDistinctMDs, &TypeMap,
1432                                  &ValMaterializer));
1433
1434   // Link in the personality function.
1435   if (Src.hasPersonalityFn())
1436     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1437                                   RF_MoveDistinctMDs, &TypeMap,
1438                                   &ValMaterializer));
1439
1440   // Go through and convert function arguments over, remembering the mapping.
1441   Function::arg_iterator DI = Dst.arg_begin();
1442   for (Argument &Arg : Src.args()) {
1443     DI->setName(Arg.getName()); // Copy the name over.
1444
1445     // Add a mapping to our mapping.
1446     ValueMap[&Arg] = &*DI;
1447     ++DI;
1448   }
1449
1450   // Copy over the metadata attachments.
1451   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1452   Src.getAllMetadata(MDs);
1453   for (const auto &I : MDs)
1454     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1455                                          &TypeMap, &ValMaterializer));
1456
1457   // Splice the body of the source function into the dest function.
1458   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1459
1460   // At this point, all of the instructions and values of the function are now
1461   // copied over.  The only problem is that they are still referencing values in
1462   // the Source function as operands.  Loop through all of the operands of the
1463   // functions and patch them up to point to the local versions.
1464   for (BasicBlock &BB : Dst)
1465     for (Instruction &I : BB)
1466       RemapInstruction(&I, ValueMap,
1467                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1468                        &ValMaterializer);
1469
1470   // There is no need to map the arguments anymore.
1471   for (Argument &Arg : Src.args())
1472     ValueMap.erase(&Arg);
1473
1474   Src.dematerialize();
1475   return false;
1476 }
1477
1478 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1479   Constant *Aliasee = Src.getAliasee();
1480   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1481                            &ValMaterializer);
1482   Dst.setAliasee(Val);
1483 }
1484
1485 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1486   if (const Comdat *SC = Src.getComdat()) {
1487     // To ensure that we don't generate an incomplete comdat group,
1488     // we must materialize and map in any other members that are not
1489     // yet materialized in Dst, which also ensures their definitions
1490     // are linked in. Otherwise, linkonce and other lazy linked GVs will
1491     // not be materialized if they aren't referenced.
1492     for (auto *SGV : ComdatMembers[SC]) {
1493       auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
1494       if (DGV && !DGV->isDeclaration())
1495         continue;
1496       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1497     }
1498   }
1499   if (shouldInternalizeLinkedSymbols())
1500     if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1501       DGV->setLinkage(GlobalValue::InternalLinkage);
1502   if (auto *F = dyn_cast<Function>(&Src))
1503     return linkFunctionBody(cast<Function>(Dst), *F);
1504   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1505     linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1506     return false;
1507   }
1508   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1509   return false;
1510 }
1511
1512 /// Insert all of the named MDNodes in Src into the Dest module.
1513 void ModuleLinker::linkNamedMDNodes() {
1514   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1515   for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1516     // Don't link module flags here. Do them separately.
1517     if (&NMD == SrcModFlags)
1518       continue;
1519     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1520     // Add Src elements into Dest node.
1521     for (const MDNode *op : NMD.operands())
1522       DestNMD->addOperand(MapMetadata(
1523           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1524           &TypeMap, &ValMaterializer));
1525   }
1526 }
1527
1528 /// Merge the linker flags in Src into the Dest module.
1529 bool ModuleLinker::linkModuleFlagsMetadata() {
1530   // If the source module has no module flags, we are done.
1531   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1532   if (!SrcModFlags)
1533     return false;
1534
1535   // If the destination module doesn't have module flags yet, then just copy
1536   // over the source module's flags.
1537   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1538   if (DstModFlags->getNumOperands() == 0) {
1539     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1540       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1541
1542     return false;
1543   }
1544
1545   // First build a map of the existing module flags and requirements.
1546   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1547   SmallSetVector<MDNode *, 16> Requirements;
1548   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1549     MDNode *Op = DstModFlags->getOperand(I);
1550     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1551     MDString *ID = cast<MDString>(Op->getOperand(1));
1552
1553     if (Behavior->getZExtValue() == Module::Require) {
1554       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1555     } else {
1556       Flags[ID] = std::make_pair(Op, I);
1557     }
1558   }
1559
1560   // Merge in the flags from the source module, and also collect its set of
1561   // requirements.
1562   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1563     MDNode *SrcOp = SrcModFlags->getOperand(I);
1564     ConstantInt *SrcBehavior =
1565         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1566     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1567     MDNode *DstOp;
1568     unsigned DstIndex;
1569     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1570     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1571
1572     // If this is a requirement, add it and continue.
1573     if (SrcBehaviorValue == Module::Require) {
1574       // If the destination module does not already have this requirement, add
1575       // it.
1576       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1577         DstModFlags->addOperand(SrcOp);
1578       }
1579       continue;
1580     }
1581
1582     // If there is no existing flag with this ID, just add it.
1583     if (!DstOp) {
1584       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1585       DstModFlags->addOperand(SrcOp);
1586       continue;
1587     }
1588
1589     // Otherwise, perform a merge.
1590     ConstantInt *DstBehavior =
1591         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1592     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1593
1594     // If either flag has override behavior, handle it first.
1595     if (DstBehaviorValue == Module::Override) {
1596       // Diagnose inconsistent flags which both have override behavior.
1597       if (SrcBehaviorValue == Module::Override &&
1598           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1599         emitError("linking module flags '" + ID->getString() +
1600                   "': IDs have conflicting override values");
1601       }
1602       continue;
1603     } else if (SrcBehaviorValue == Module::Override) {
1604       // Update the destination flag to that of the source.
1605       DstModFlags->setOperand(DstIndex, SrcOp);
1606       Flags[ID].first = SrcOp;
1607       continue;
1608     }
1609
1610     // Diagnose inconsistent merge behavior types.
1611     if (SrcBehaviorValue != DstBehaviorValue) {
1612       emitError("linking module flags '" + ID->getString() +
1613                 "': IDs have conflicting behaviors");
1614       continue;
1615     }
1616
1617     auto replaceDstValue = [&](MDNode *New) {
1618       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1619       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1620       DstModFlags->setOperand(DstIndex, Flag);
1621       Flags[ID].first = Flag;
1622     };
1623
1624     // Perform the merge for standard behavior types.
1625     switch (SrcBehaviorValue) {
1626     case Module::Require:
1627     case Module::Override:
1628       llvm_unreachable("not possible");
1629     case Module::Error: {
1630       // Emit an error if the values differ.
1631       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1632         emitError("linking module flags '" + ID->getString() +
1633                   "': IDs have conflicting values");
1634       }
1635       continue;
1636     }
1637     case Module::Warning: {
1638       // Emit a warning if the values differ.
1639       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1640         emitWarning("linking module flags '" + ID->getString() +
1641                     "': IDs have conflicting values");
1642       }
1643       continue;
1644     }
1645     case Module::Append: {
1646       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1647       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1648       SmallVector<Metadata *, 8> MDs;
1649       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1650       MDs.append(DstValue->op_begin(), DstValue->op_end());
1651       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1652
1653       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1654       break;
1655     }
1656     case Module::AppendUnique: {
1657       SmallSetVector<Metadata *, 16> Elts;
1658       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1659       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1660       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1661       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1662
1663       replaceDstValue(MDNode::get(DstM.getContext(),
1664                                   makeArrayRef(Elts.begin(), Elts.end())));
1665       break;
1666     }
1667     }
1668   }
1669
1670   // Check all of the requirements.
1671   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1672     MDNode *Requirement = Requirements[I];
1673     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1674     Metadata *ReqValue = Requirement->getOperand(1);
1675
1676     MDNode *Op = Flags[Flag].first;
1677     if (!Op || Op->getOperand(2) != ReqValue) {
1678       emitError("linking module flags '" + Flag->getString() +
1679                 "': does not have the required value");
1680       continue;
1681     }
1682   }
1683
1684   return HasError;
1685 }
1686
1687 // This function returns true if the triples match.
1688 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1689   // If vendor is apple, ignore the version number.
1690   if (T0.getVendor() == Triple::Apple)
1691     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1692            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1693
1694   return T0 == T1;
1695 }
1696
1697 // This function returns the merged triple.
1698 static std::string mergeTriples(const Triple &SrcTriple,
1699                                 const Triple &DstTriple) {
1700   // If vendor is apple, pick the triple with the larger version number.
1701   if (SrcTriple.getVendor() == Triple::Apple)
1702     if (DstTriple.isOSVersionLT(SrcTriple))
1703       return SrcTriple.str();
1704
1705   return DstTriple.str();
1706 }
1707
1708 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1709   GlobalValue *DGV = getLinkedToGlobal(&GV);
1710
1711   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1712     return false;
1713
1714   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
1715     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1716     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
1717     if (DGVar && SGVar) {
1718       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
1719           (!DGVar->isConstant() || !SGVar->isConstant())) {
1720         DGVar->setConstant(false);
1721         SGVar->setConstant(false);
1722       }
1723       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
1724         unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
1725         SGVar->setAlignment(Align);
1726         DGVar->setAlignment(Align);
1727       }
1728     }
1729
1730     GlobalValue::VisibilityTypes Visibility =
1731         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1732     DGV->setVisibility(Visibility);
1733     GV.setVisibility(Visibility);
1734
1735     bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
1736     DGV->setUnnamedAddr(HasUnnamedAddr);
1737     GV.setUnnamedAddr(HasUnnamedAddr);
1738   }
1739
1740   // Don't want to append to global_ctors list, for example, when we
1741   // are importing for ThinLTO, otherwise the global ctors and dtors
1742   // get executed multiple times for local variables (the latter causing
1743   // double frees).
1744   if (GV.hasAppendingLinkage() && isPerformingImport())
1745     return false;
1746
1747   if (isPerformingImport() && !doImportAsDefinition(&GV))
1748     return false;
1749
1750   if (!DGV && !shouldOverrideFromSrc() &&
1751       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1752        GV.hasAvailableExternallyLinkage()))
1753     return false;
1754
1755   if (GV.isDeclaration())
1756     return false;
1757
1758   if (const Comdat *SC = GV.getComdat()) {
1759     bool LinkFromSrc;
1760     Comdat::SelectionKind SK;
1761     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1762     if (LinkFromSrc)
1763       ValuesToLink.insert(&GV);
1764     return false;
1765   }
1766
1767   bool LinkFromSrc = true;
1768   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
1769     return true;
1770   if (LinkFromSrc)
1771     ValuesToLink.insert(&GV);
1772   return false;
1773 }
1774
1775 bool ModuleLinker::run() {
1776   // Inherit the target data from the source module if the destination module
1777   // doesn't have one already.
1778   if (DstM.getDataLayout().isDefault())
1779     DstM.setDataLayout(SrcM.getDataLayout());
1780
1781   if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1782     emitWarning("Linking two modules of different data layouts: '" +
1783                 SrcM.getModuleIdentifier() + "' is '" +
1784                 SrcM.getDataLayoutStr() + "' whereas '" +
1785                 DstM.getModuleIdentifier() + "' is '" +
1786                 DstM.getDataLayoutStr() + "'\n");
1787   }
1788
1789   // Copy the target triple from the source to dest if the dest's is empty.
1790   if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1791     DstM.setTargetTriple(SrcM.getTargetTriple());
1792
1793   Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1794
1795   if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1796     emitWarning("Linking two modules of different target triples: " +
1797                 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1798                 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1799                 DstM.getTargetTriple() + "'\n");
1800
1801   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1802
1803   // Append the module inline asm string.
1804   if (!SrcM.getModuleInlineAsm().empty()) {
1805     if (DstM.getModuleInlineAsm().empty())
1806       DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1807     else
1808       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1809                               SrcM.getModuleInlineAsm());
1810   }
1811
1812   // Loop over all of the linked values to compute type mappings.
1813   computeTypeMapping();
1814
1815   ComdatsChosen.clear();
1816   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1817     const Comdat &C = SMEC.getValue();
1818     if (ComdatsChosen.count(&C))
1819       continue;
1820     Comdat::SelectionKind SK;
1821     bool LinkFromSrc;
1822     if (getComdatResult(&C, SK, LinkFromSrc))
1823       return true;
1824     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1825   }
1826
1827   for (GlobalVariable &GV : SrcM.globals())
1828     if (const Comdat *SC = GV.getComdat())
1829       ComdatMembers[SC].push_back(&GV);
1830
1831   for (Function &SF : SrcM)
1832     if (const Comdat *SC = SF.getComdat())
1833       ComdatMembers[SC].push_back(&SF);
1834
1835   for (GlobalAlias &GA : SrcM.aliases())
1836     if (const Comdat *SC = GA.getComdat())
1837       ComdatMembers[SC].push_back(&GA);
1838
1839   // Insert all of the globals in src into the DstM module... without linking
1840   // initializers (which could refer to functions not yet mapped over).
1841   for (GlobalVariable &GV : SrcM.globals())
1842     if (linkIfNeeded(GV))
1843       return true;
1844
1845   for (Function &SF : SrcM)
1846     if (linkIfNeeded(SF))
1847       return true;
1848
1849   for (GlobalAlias &GA : SrcM.aliases())
1850     if (linkIfNeeded(GA))
1851       return true;
1852
1853   for (GlobalValue *GV : ValuesToLink) {
1854     MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1855     if (HasError)
1856       return true;
1857   }
1858
1859   // Note that we are done linking global value bodies. This prevents
1860   // metadata linking from creating new references.
1861   DoneLinkingBodies = true;
1862
1863   // Remap all of the named MDNodes in Src into the DstM module. We do this
1864   // after linking GlobalValues so that MDNodes that reference GlobalValues
1865   // are properly remapped.
1866   linkNamedMDNodes();
1867
1868   // Merge the module flags into the DstM module.
1869   if (linkModuleFlagsMetadata())
1870     return true;
1871
1872   return false;
1873 }
1874
1875 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1876     : ETypes(E), IsPacked(P) {}
1877
1878 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1879     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1880
1881 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1882   if (IsPacked != That.IsPacked)
1883     return false;
1884   if (ETypes != That.ETypes)
1885     return false;
1886   return true;
1887 }
1888
1889 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1890   return !this->operator==(That);
1891 }
1892
1893 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1894   return DenseMapInfo<StructType *>::getEmptyKey();
1895 }
1896
1897 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1898   return DenseMapInfo<StructType *>::getTombstoneKey();
1899 }
1900
1901 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1902   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1903                       Key.IsPacked);
1904 }
1905
1906 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1907   return getHashValue(KeyTy(ST));
1908 }
1909
1910 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1911                                         const StructType *RHS) {
1912   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1913     return false;
1914   return LHS == KeyTy(RHS);
1915 }
1916
1917 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1918                                         const StructType *RHS) {
1919   if (RHS == getEmptyKey())
1920     return LHS == getEmptyKey();
1921
1922   if (RHS == getTombstoneKey())
1923     return LHS == getTombstoneKey();
1924
1925   return KeyTy(LHS) == KeyTy(RHS);
1926 }
1927
1928 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1929   assert(!Ty->isOpaque());
1930   NonOpaqueStructTypes.insert(Ty);
1931 }
1932
1933 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1934   assert(!Ty->isOpaque());
1935   NonOpaqueStructTypes.insert(Ty);
1936   bool Removed = OpaqueStructTypes.erase(Ty);
1937   (void)Removed;
1938   assert(Removed);
1939 }
1940
1941 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1942   assert(Ty->isOpaque());
1943   OpaqueStructTypes.insert(Ty);
1944 }
1945
1946 StructType *
1947 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1948                                                bool IsPacked) {
1949   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1950   auto I = NonOpaqueStructTypes.find_as(Key);
1951   if (I == NonOpaqueStructTypes.end())
1952     return nullptr;
1953   return *I;
1954 }
1955
1956 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1957   if (Ty->isOpaque())
1958     return OpaqueStructTypes.count(Ty);
1959   auto I = NonOpaqueStructTypes.find(Ty);
1960   if (I == NonOpaqueStructTypes.end())
1961     return false;
1962   return *I == Ty;
1963 }
1964
1965 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1966     : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1967   TypeFinder StructTypes;
1968   StructTypes.run(M, true);
1969   for (StructType *Ty : StructTypes) {
1970     if (Ty->isOpaque())
1971       IdentifiedStructTypes.addOpaque(Ty);
1972     else
1973       IdentifiedStructTypes.addNonOpaque(Ty);
1974   }
1975 }
1976
1977 bool Linker::linkInModule(Module &Src, unsigned Flags,
1978                           const FunctionInfoIndex *Index,
1979                           DenseSet<const GlobalValue *> *FunctionsToImport) {
1980   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1981                          DiagnosticHandler, Flags, Index, FunctionsToImport);
1982   bool RetCode = TheLinker.run();
1983   Composite.dropTriviallyDeadConstantArrays();
1984   return RetCode;
1985 }
1986
1987 //===----------------------------------------------------------------------===//
1988 // LinkModules entrypoint.
1989 //===----------------------------------------------------------------------===//
1990
1991 /// This function links two modules together, with the resulting Dest module
1992 /// modified to be the composite of the two input modules. If an error occurs,
1993 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1994 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1995 /// relied on to be consistent.
1996 bool Linker::linkModules(Module &Dest, Module &Src,
1997                          DiagnosticHandlerFunction DiagnosticHandler,
1998                          unsigned Flags) {
1999   Linker L(Dest, DiagnosticHandler);
2000   return L.linkInModule(Src, Flags);
2001 }
2002
2003 std::unique_ptr<Module>
2004 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
2005                              const FunctionInfoIndex *Index,
2006                              DiagnosticHandlerFunction DiagnosticHandler) {
2007   std::unique_ptr<llvm::Module> RenamedModule(
2008       new llvm::Module(M->getModuleIdentifier(), M->getContext()));
2009   Linker L(*RenamedModule.get(), DiagnosticHandler);
2010   if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
2011     return nullptr;
2012   return RenamedModule;
2013 }
2014
2015 //===----------------------------------------------------------------------===//
2016 // C API.
2017 //===----------------------------------------------------------------------===//
2018
2019 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2020                          LLVMLinkerMode Unused, char **OutMessages) {
2021   Module *D = unwrap(Dest);
2022   std::string Message;
2023   raw_string_ostream Stream(Message);
2024   DiagnosticPrinterRawOStream DP(Stream);
2025
2026   LLVMBool Result = Linker::linkModules(
2027       *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2028
2029   if (OutMessages && Result) {
2030     Stream.flush();
2031     *OutMessages = strdup(Message.c_str());
2032   }
2033   return Result;
2034 }