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