[PGO] Rename the profdata filename to avoid the conflict b/w tests.
[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     LinkFromSrc = Dest.hasExternalWeakLinkage();
1054     return false;
1055   }
1056
1057   if (DestIsDeclaration) {
1058     // If Dest is external but Src is not:
1059     LinkFromSrc = true;
1060     return false;
1061   }
1062
1063   if (Src.hasCommonLinkage()) {
1064     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1065       LinkFromSrc = true;
1066       return false;
1067     }
1068
1069     if (!Dest.hasCommonLinkage()) {
1070       LinkFromSrc = false;
1071       return false;
1072     }
1073
1074     const DataLayout &DL = Dest.getParent()->getDataLayout();
1075     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1076     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1077     LinkFromSrc = SrcSize > DestSize;
1078     return false;
1079   }
1080
1081   if (Src.isWeakForLinker()) {
1082     assert(!Dest.hasExternalWeakLinkage());
1083     assert(!Dest.hasAvailableExternallyLinkage());
1084
1085     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1086       LinkFromSrc = true;
1087       return false;
1088     }
1089
1090     LinkFromSrc = false;
1091     return false;
1092   }
1093
1094   if (Dest.isWeakForLinker()) {
1095     assert(Src.hasExternalLinkage());
1096     LinkFromSrc = true;
1097     return false;
1098   }
1099
1100   assert(!Src.hasExternalWeakLinkage());
1101   assert(!Dest.hasExternalWeakLinkage());
1102   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1103          "Unexpected linkage type!");
1104   return emitError("Linking globals named '" + Src.getName() +
1105                    "': symbol multiply defined!");
1106 }
1107
1108 /// Loop over all of the linked values to compute type mappings.  For example,
1109 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1110 /// types 'Foo' but one got renamed when the module was loaded into the same
1111 /// LLVMContext.
1112 void ModuleLinker::computeTypeMapping() {
1113   for (GlobalValue &SGV : SrcM.globals()) {
1114     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1115     if (!DGV)
1116       continue;
1117
1118     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1119       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1120       continue;
1121     }
1122
1123     // Unify the element type of appending arrays.
1124     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1125     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1126     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1127   }
1128
1129   for (GlobalValue &SGV : SrcM) {
1130     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1131       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1132   }
1133
1134   for (GlobalValue &SGV : SrcM.aliases()) {
1135     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1136       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1137   }
1138
1139   // Incorporate types by name, scanning all the types in the source module.
1140   // At this point, the destination module may have a type "%foo = { i32 }" for
1141   // example.  When the source module got loaded into the same LLVMContext, if
1142   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1143   std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1144   for (StructType *ST : Types) {
1145     if (!ST->hasName())
1146       continue;
1147
1148     // Check to see if there is a dot in the name followed by a digit.
1149     size_t DotPos = ST->getName().rfind('.');
1150     if (DotPos == 0 || DotPos == StringRef::npos ||
1151         ST->getName().back() == '.' ||
1152         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1153       continue;
1154
1155     // Check to see if the destination module has a struct with the prefix name.
1156     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1157     if (!DST)
1158       continue;
1159
1160     // Don't use it if this actually came from the source module. They're in
1161     // the same LLVMContext after all. Also don't use it unless the type is
1162     // actually used in the destination module. This can happen in situations
1163     // like this:
1164     //
1165     //      Module A                         Module B
1166     //      --------                         --------
1167     //   %Z = type { %A }                %B = type { %C.1 }
1168     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
1169     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
1170     //   %C = type { i8* }               %B.3 = type { %C.1 }
1171     //
1172     // When we link Module B with Module A, the '%B' in Module B is
1173     // used. However, that would then use '%C.1'. But when we process '%C.1',
1174     // we prefer to take the '%C' version. So we are then left with both
1175     // '%C.1' and '%C' being used for the same types. This leads to some
1176     // variables using one type and some using the other.
1177     if (TypeMap.DstStructTypesSet.hasType(DST))
1178       TypeMap.addTypeMapping(DST, ST);
1179   }
1180
1181   // Now that we have discovered all of the type equivalences, get a body for
1182   // any 'opaque' types in the dest module that are now resolved.
1183   TypeMap.linkDefinedTypeBodies();
1184 }
1185
1186 static void getArrayElements(const Constant *C,
1187                              SmallVectorImpl<Constant *> &Dest) {
1188   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1189
1190   for (unsigned i = 0; i != NumElements; ++i)
1191     Dest.push_back(C->getAggregateElement(i));
1192 }
1193
1194 /// If there were any appending global variables, link them together now.
1195 /// Return true on error.
1196 Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1197                                               const GlobalVariable *SrcGV) {
1198   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
1199                     ->getElementType();
1200
1201   StringRef Name = SrcGV->getName();
1202   bool IsNewStructor = false;
1203   bool IsOldStructor = false;
1204   if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
1205     if (cast<StructType>(EltTy)->getNumElements() == 3)
1206       IsNewStructor = true;
1207     else
1208       IsOldStructor = true;
1209   }
1210
1211   PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
1212   if (IsOldStructor) {
1213     auto &ST = *cast<StructType>(EltTy);
1214     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1215     EltTy = StructType::get(SrcGV->getContext(), Tys, false);
1216   }
1217
1218   if (DstGV) {
1219     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1220
1221     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
1222       emitError(
1223           "Linking globals named '" + SrcGV->getName() +
1224           "': can only link appending global with another appending global!");
1225       return nullptr;
1226     }
1227
1228     // Check to see that they two arrays agree on type.
1229     if (EltTy != DstTy->getElementType()) {
1230       emitError("Appending variables with different element types!");
1231       return nullptr;
1232     }
1233     if (DstGV->isConstant() != SrcGV->isConstant()) {
1234       emitError("Appending variables linked with different const'ness!");
1235       return nullptr;
1236     }
1237
1238     if (DstGV->getAlignment() != SrcGV->getAlignment()) {
1239       emitError(
1240           "Appending variables with different alignment need to be linked!");
1241       return nullptr;
1242     }
1243
1244     if (DstGV->getVisibility() != SrcGV->getVisibility()) {
1245       emitError(
1246           "Appending variables with different visibility need to be linked!");
1247       return nullptr;
1248     }
1249
1250     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
1251       emitError(
1252           "Appending variables with different unnamed_addr need to be linked!");
1253       return nullptr;
1254     }
1255
1256     if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
1257       emitError(
1258           "Appending variables with different section name need to be linked!");
1259       return nullptr;
1260     }
1261   }
1262
1263   SmallVector<Constant *, 16> DstElements;
1264   if (DstGV)
1265     getArrayElements(DstGV->getInitializer(), DstElements);
1266
1267   SmallVector<Constant *, 16> SrcElements;
1268   getArrayElements(SrcGV->getInitializer(), SrcElements);
1269
1270   if (IsNewStructor)
1271     SrcElements.erase(
1272         std::remove_if(SrcElements.begin(), SrcElements.end(),
1273                        [this](Constant *E) {
1274                          auto *Key = dyn_cast<GlobalValue>(
1275                              E->getAggregateElement(2)->stripPointerCasts());
1276                          return Key && !ValuesToLink.count(Key) &&
1277                                 !shouldLazyLink(*Key);
1278                        }),
1279         SrcElements.end());
1280   uint64_t NewSize = DstElements.size() + SrcElements.size();
1281   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1282
1283   // Create the new global variable.
1284   GlobalVariable *NG = new GlobalVariable(
1285       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1286       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1287       SrcGV->getType()->getAddressSpace());
1288
1289   // Propagate alignment, visibility and section info.
1290   copyGVAttributes(NG, SrcGV);
1291
1292   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1293
1294   // Stop recursion.
1295   ValueMap[SrcGV] = Ret;
1296
1297   for (auto *V : SrcElements) {
1298     Constant *NewV;
1299     if (IsOldStructor) {
1300       auto *S = cast<ConstantStruct>(V);
1301       auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
1302                           &TypeMap, &ValMaterializer);
1303       auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
1304                           &TypeMap, &ValMaterializer);
1305       Value *Null = Constant::getNullValue(VoidPtrTy);
1306       NewV =
1307           ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1308     } else {
1309       NewV =
1310           MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1311     }
1312     DstElements.push_back(NewV);
1313   }
1314
1315   NG->setInitializer(ConstantArray::get(NewType, DstElements));
1316
1317   // Replace any uses of the two global variables with uses of the new
1318   // global.
1319   if (DstGV) {
1320     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1321     DstGV->eraseFromParent();
1322   }
1323
1324   return Ret;
1325 }
1326
1327 Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1328   GlobalValue *DGV = getLinkedToGlobal(SGV);
1329
1330   // Handle the ultra special appending linkage case first.
1331   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1332   if (SGV->hasAppendingLinkage()) {
1333     // Should have prevented importing for appending linkage in linkIfNeeded.
1334     assert(!isPerformingImport());
1335     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1336                                  cast<GlobalVariable>(SGV));
1337   }
1338
1339   bool LinkFromSrc = true;
1340   Comdat *C = nullptr;
1341   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1342
1343   if (isPerformingImport() && !doImportAsDefinition(SGV)) {
1344     LinkFromSrc = false;
1345   } else if (const Comdat *SC = SGV->getComdat()) {
1346     Comdat::SelectionKind SK;
1347     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1348     C = DstM.getOrInsertComdat(SC->getName());
1349     C->setSelectionKind(SK);
1350     if (SGV->hasLocalLinkage())
1351       LinkFromSrc = true;
1352   } else if (DGV) {
1353     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1354       return nullptr;
1355   }
1356
1357   if (DGV)
1358     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1359
1360   GlobalValue *NewGV;
1361   if (!LinkFromSrc && DGV) {
1362     NewGV = DGV;
1363   } else {
1364     // If we are done linking global value bodies (i.e. we are performing
1365     // metadata linking), don't link in the global value due to this
1366     // reference, simply map it to null.
1367     if (DoneLinkingBodies)
1368       return nullptr;
1369
1370     NewGV = copyGlobalValueProto(SGV, LinkFromSrc);
1371   }
1372
1373   setVisibility(NewGV, SGV, DGV);
1374   NewGV->setUnnamedAddr(HasUnnamedAddr);
1375
1376   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1377     if (C && LinkFromSrc)
1378       NewGO->setComdat(C);
1379
1380     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1381       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1382   }
1383
1384   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1385     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1386     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1387     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1388         (!DGVar->isConstant() || !SGVar->isConstant()))
1389       NewGVar->setConstant(false);
1390   }
1391
1392   if (NewGV != DGV && DGV) {
1393     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1394     DGV->eraseFromParent();
1395   }
1396
1397   return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1398 }
1399
1400 /// Update the initializers in the Dest module now that all globals that may be
1401 /// referenced are in Dest.
1402 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1403   // Figure out what the initializer looks like in the dest module.
1404   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1405                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1406 }
1407
1408 /// Copy the source function over into the dest function and fix up references
1409 /// to values. At this point we know that Dest is an external function, and
1410 /// that Src is not.
1411 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1412   assert(Dst.isDeclaration() && !Src.isDeclaration());
1413
1414   // Materialize if needed.
1415   if (std::error_code EC = Src.materialize())
1416     return emitError(EC.message());
1417
1418   // Link in the prefix data.
1419   if (Src.hasPrefixData())
1420     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1421                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1422
1423   // Link in the prologue data.
1424   if (Src.hasPrologueData())
1425     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1426                                  RF_MoveDistinctMDs, &TypeMap,
1427                                  &ValMaterializer));
1428
1429   // Link in the personality function.
1430   if (Src.hasPersonalityFn())
1431     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1432                                   RF_MoveDistinctMDs, &TypeMap,
1433                                   &ValMaterializer));
1434
1435   // Go through and convert function arguments over, remembering the mapping.
1436   Function::arg_iterator DI = Dst.arg_begin();
1437   for (Argument &Arg : Src.args()) {
1438     DI->setName(Arg.getName()); // Copy the name over.
1439
1440     // Add a mapping to our mapping.
1441     ValueMap[&Arg] = &*DI;
1442     ++DI;
1443   }
1444
1445   // Copy over the metadata attachments.
1446   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1447   Src.getAllMetadata(MDs);
1448   for (const auto &I : MDs)
1449     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1450                                          &TypeMap, &ValMaterializer));
1451
1452   // Splice the body of the source function into the dest function.
1453   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1454
1455   // At this point, all of the instructions and values of the function are now
1456   // copied over.  The only problem is that they are still referencing values in
1457   // the Source function as operands.  Loop through all of the operands of the
1458   // functions and patch them up to point to the local versions.
1459   for (BasicBlock &BB : Dst)
1460     for (Instruction &I : BB)
1461       RemapInstruction(&I, ValueMap,
1462                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1463                        &ValMaterializer);
1464
1465   // There is no need to map the arguments anymore.
1466   for (Argument &Arg : Src.args())
1467     ValueMap.erase(&Arg);
1468
1469   Src.dematerialize();
1470   return false;
1471 }
1472
1473 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1474   Constant *Aliasee = Src.getAliasee();
1475   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1476                            &ValMaterializer);
1477   Dst.setAliasee(Val);
1478 }
1479
1480 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1481   if (const Comdat *SC = Src.getComdat()) {
1482     // To ensure that we don't generate an incomplete comdat group,
1483     // we must materialize and map in any other members that are not
1484     // yet materialized in Dst, which also ensures their definitions
1485     // are linked in. Otherwise, linkonce and other lazy linked GVs will
1486     // not be materialized if they aren't referenced.
1487     for (auto *SGV : ComdatMembers[SC]) {
1488       auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
1489       if (DGV && !DGV->isDeclaration())
1490         continue;
1491       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1492     }
1493   }
1494   if (shouldInternalizeLinkedSymbols())
1495     if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1496       DGV->setLinkage(GlobalValue::InternalLinkage);
1497   if (auto *F = dyn_cast<Function>(&Src))
1498     return linkFunctionBody(cast<Function>(Dst), *F);
1499   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1500     linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1501     return false;
1502   }
1503   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1504   return false;
1505 }
1506
1507 /// Insert all of the named MDNodes in Src into the Dest module.
1508 void ModuleLinker::linkNamedMDNodes() {
1509   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1510   for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1511     // Don't link module flags here. Do them separately.
1512     if (&NMD == SrcModFlags)
1513       continue;
1514     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1515     // Add Src elements into Dest node.
1516     for (const MDNode *op : NMD.operands())
1517       DestNMD->addOperand(MapMetadata(
1518           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1519           &TypeMap, &ValMaterializer));
1520   }
1521 }
1522
1523 /// Merge the linker flags in Src into the Dest module.
1524 bool ModuleLinker::linkModuleFlagsMetadata() {
1525   // If the source module has no module flags, we are done.
1526   const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1527   if (!SrcModFlags)
1528     return false;
1529
1530   // If the destination module doesn't have module flags yet, then just copy
1531   // over the source module's flags.
1532   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1533   if (DstModFlags->getNumOperands() == 0) {
1534     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1535       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1536
1537     return false;
1538   }
1539
1540   // First build a map of the existing module flags and requirements.
1541   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1542   SmallSetVector<MDNode *, 16> Requirements;
1543   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1544     MDNode *Op = DstModFlags->getOperand(I);
1545     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1546     MDString *ID = cast<MDString>(Op->getOperand(1));
1547
1548     if (Behavior->getZExtValue() == Module::Require) {
1549       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1550     } else {
1551       Flags[ID] = std::make_pair(Op, I);
1552     }
1553   }
1554
1555   // Merge in the flags from the source module, and also collect its set of
1556   // requirements.
1557   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1558     MDNode *SrcOp = SrcModFlags->getOperand(I);
1559     ConstantInt *SrcBehavior =
1560         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1561     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1562     MDNode *DstOp;
1563     unsigned DstIndex;
1564     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1565     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1566
1567     // If this is a requirement, add it and continue.
1568     if (SrcBehaviorValue == Module::Require) {
1569       // If the destination module does not already have this requirement, add
1570       // it.
1571       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1572         DstModFlags->addOperand(SrcOp);
1573       }
1574       continue;
1575     }
1576
1577     // If there is no existing flag with this ID, just add it.
1578     if (!DstOp) {
1579       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1580       DstModFlags->addOperand(SrcOp);
1581       continue;
1582     }
1583
1584     // Otherwise, perform a merge.
1585     ConstantInt *DstBehavior =
1586         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1587     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1588
1589     // If either flag has override behavior, handle it first.
1590     if (DstBehaviorValue == Module::Override) {
1591       // Diagnose inconsistent flags which both have override behavior.
1592       if (SrcBehaviorValue == Module::Override &&
1593           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1594         emitError("linking module flags '" + ID->getString() +
1595                   "': IDs have conflicting override values");
1596       }
1597       continue;
1598     } else if (SrcBehaviorValue == Module::Override) {
1599       // Update the destination flag to that of the source.
1600       DstModFlags->setOperand(DstIndex, SrcOp);
1601       Flags[ID].first = SrcOp;
1602       continue;
1603     }
1604
1605     // Diagnose inconsistent merge behavior types.
1606     if (SrcBehaviorValue != DstBehaviorValue) {
1607       emitError("linking module flags '" + ID->getString() +
1608                 "': IDs have conflicting behaviors");
1609       continue;
1610     }
1611
1612     auto replaceDstValue = [&](MDNode *New) {
1613       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1614       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1615       DstModFlags->setOperand(DstIndex, Flag);
1616       Flags[ID].first = Flag;
1617     };
1618
1619     // Perform the merge for standard behavior types.
1620     switch (SrcBehaviorValue) {
1621     case Module::Require:
1622     case Module::Override:
1623       llvm_unreachable("not possible");
1624     case Module::Error: {
1625       // Emit an error if the values differ.
1626       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1627         emitError("linking module flags '" + ID->getString() +
1628                   "': IDs have conflicting values");
1629       }
1630       continue;
1631     }
1632     case Module::Warning: {
1633       // Emit a warning if the values differ.
1634       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1635         emitWarning("linking module flags '" + ID->getString() +
1636                     "': IDs have conflicting values");
1637       }
1638       continue;
1639     }
1640     case Module::Append: {
1641       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1642       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1643       SmallVector<Metadata *, 8> MDs;
1644       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1645       MDs.append(DstValue->op_begin(), DstValue->op_end());
1646       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1647
1648       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1649       break;
1650     }
1651     case Module::AppendUnique: {
1652       SmallSetVector<Metadata *, 16> Elts;
1653       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1654       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1655       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1656       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1657
1658       replaceDstValue(MDNode::get(DstM.getContext(),
1659                                   makeArrayRef(Elts.begin(), Elts.end())));
1660       break;
1661     }
1662     }
1663   }
1664
1665   // Check all of the requirements.
1666   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1667     MDNode *Requirement = Requirements[I];
1668     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1669     Metadata *ReqValue = Requirement->getOperand(1);
1670
1671     MDNode *Op = Flags[Flag].first;
1672     if (!Op || Op->getOperand(2) != ReqValue) {
1673       emitError("linking module flags '" + Flag->getString() +
1674                 "': does not have the required value");
1675       continue;
1676     }
1677   }
1678
1679   return HasError;
1680 }
1681
1682 // This function returns true if the triples match.
1683 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1684   // If vendor is apple, ignore the version number.
1685   if (T0.getVendor() == Triple::Apple)
1686     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1687            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1688
1689   return T0 == T1;
1690 }
1691
1692 // This function returns the merged triple.
1693 static std::string mergeTriples(const Triple &SrcTriple,
1694                                 const Triple &DstTriple) {
1695   // If vendor is apple, pick the triple with the larger version number.
1696   if (SrcTriple.getVendor() == Triple::Apple)
1697     if (DstTriple.isOSVersionLT(SrcTriple))
1698       return SrcTriple.str();
1699
1700   return DstTriple.str();
1701 }
1702
1703 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1704   GlobalValue *DGV = getLinkedToGlobal(&GV);
1705
1706   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1707     return false;
1708
1709   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
1710     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1711     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
1712     if (DGVar && SGVar) {
1713       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
1714           (!DGVar->isConstant() || !SGVar->isConstant())) {
1715         DGVar->setConstant(false);
1716         SGVar->setConstant(false);
1717       }
1718       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
1719         unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
1720         SGVar->setAlignment(Align);
1721         DGVar->setAlignment(Align);
1722       }
1723     }
1724
1725     GlobalValue::VisibilityTypes Visibility =
1726         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1727     DGV->setVisibility(Visibility);
1728     GV.setVisibility(Visibility);
1729
1730     bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
1731     DGV->setUnnamedAddr(HasUnnamedAddr);
1732     GV.setUnnamedAddr(HasUnnamedAddr);
1733   }
1734
1735   // Don't want to append to global_ctors list, for example, when we
1736   // are importing for ThinLTO, otherwise the global ctors and dtors
1737   // get executed multiple times for local variables (the latter causing
1738   // double frees).
1739   if (GV.hasAppendingLinkage() && isPerformingImport())
1740     return false;
1741
1742   if (isPerformingImport() && !doImportAsDefinition(&GV))
1743     return false;
1744
1745   if (!DGV && !shouldOverrideFromSrc() &&
1746       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1747        GV.hasAvailableExternallyLinkage()))
1748     return false;
1749
1750   if (GV.isDeclaration())
1751     return false;
1752
1753   if (const Comdat *SC = GV.getComdat()) {
1754     bool LinkFromSrc;
1755     Comdat::SelectionKind SK;
1756     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1757     if (LinkFromSrc)
1758       ValuesToLink.insert(&GV);
1759     return false;
1760   }
1761
1762   bool LinkFromSrc = true;
1763   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
1764     return true;
1765   if (LinkFromSrc)
1766     ValuesToLink.insert(&GV);
1767   return false;
1768 }
1769
1770 bool ModuleLinker::run() {
1771   // Inherit the target data from the source module if the destination module
1772   // doesn't have one already.
1773   if (DstM.getDataLayout().isDefault())
1774     DstM.setDataLayout(SrcM.getDataLayout());
1775
1776   if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1777     emitWarning("Linking two modules of different data layouts: '" +
1778                 SrcM.getModuleIdentifier() + "' is '" +
1779                 SrcM.getDataLayoutStr() + "' whereas '" +
1780                 DstM.getModuleIdentifier() + "' is '" +
1781                 DstM.getDataLayoutStr() + "'\n");
1782   }
1783
1784   // Copy the target triple from the source to dest if the dest's is empty.
1785   if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1786     DstM.setTargetTriple(SrcM.getTargetTriple());
1787
1788   Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1789
1790   if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1791     emitWarning("Linking two modules of different target triples: " +
1792                 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1793                 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1794                 DstM.getTargetTriple() + "'\n");
1795
1796   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1797
1798   // Append the module inline asm string.
1799   if (!SrcM.getModuleInlineAsm().empty()) {
1800     if (DstM.getModuleInlineAsm().empty())
1801       DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1802     else
1803       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1804                               SrcM.getModuleInlineAsm());
1805   }
1806
1807   // Loop over all of the linked values to compute type mappings.
1808   computeTypeMapping();
1809
1810   ComdatsChosen.clear();
1811   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1812     const Comdat &C = SMEC.getValue();
1813     if (ComdatsChosen.count(&C))
1814       continue;
1815     Comdat::SelectionKind SK;
1816     bool LinkFromSrc;
1817     if (getComdatResult(&C, SK, LinkFromSrc))
1818       return true;
1819     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1820   }
1821
1822   for (GlobalVariable &GV : SrcM.globals())
1823     if (const Comdat *SC = GV.getComdat())
1824       ComdatMembers[SC].push_back(&GV);
1825
1826   for (Function &SF : SrcM)
1827     if (const Comdat *SC = SF.getComdat())
1828       ComdatMembers[SC].push_back(&SF);
1829
1830   for (GlobalAlias &GA : SrcM.aliases())
1831     if (const Comdat *SC = GA.getComdat())
1832       ComdatMembers[SC].push_back(&GA);
1833
1834   // Insert all of the globals in src into the DstM module... without linking
1835   // initializers (which could refer to functions not yet mapped over).
1836   for (GlobalVariable &GV : SrcM.globals())
1837     if (linkIfNeeded(GV))
1838       return true;
1839
1840   for (Function &SF : SrcM)
1841     if (linkIfNeeded(SF))
1842       return true;
1843
1844   for (GlobalAlias &GA : SrcM.aliases())
1845     if (linkIfNeeded(GA))
1846       return true;
1847
1848   for (GlobalValue *GV : ValuesToLink) {
1849     MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1850     if (HasError)
1851       return true;
1852   }
1853
1854   // Note that we are done linking global value bodies. This prevents
1855   // metadata linking from creating new references.
1856   DoneLinkingBodies = true;
1857
1858   // Remap all of the named MDNodes in Src into the DstM module. We do this
1859   // after linking GlobalValues so that MDNodes that reference GlobalValues
1860   // are properly remapped.
1861   linkNamedMDNodes();
1862
1863   // Merge the module flags into the DstM module.
1864   if (linkModuleFlagsMetadata())
1865     return true;
1866
1867   return false;
1868 }
1869
1870 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1871     : ETypes(E), IsPacked(P) {}
1872
1873 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1874     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1875
1876 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1877   if (IsPacked != That.IsPacked)
1878     return false;
1879   if (ETypes != That.ETypes)
1880     return false;
1881   return true;
1882 }
1883
1884 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1885   return !this->operator==(That);
1886 }
1887
1888 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1889   return DenseMapInfo<StructType *>::getEmptyKey();
1890 }
1891
1892 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1893   return DenseMapInfo<StructType *>::getTombstoneKey();
1894 }
1895
1896 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1897   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1898                       Key.IsPacked);
1899 }
1900
1901 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1902   return getHashValue(KeyTy(ST));
1903 }
1904
1905 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1906                                         const StructType *RHS) {
1907   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1908     return false;
1909   return LHS == KeyTy(RHS);
1910 }
1911
1912 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1913                                         const StructType *RHS) {
1914   if (RHS == getEmptyKey())
1915     return LHS == getEmptyKey();
1916
1917   if (RHS == getTombstoneKey())
1918     return LHS == getTombstoneKey();
1919
1920   return KeyTy(LHS) == KeyTy(RHS);
1921 }
1922
1923 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1924   assert(!Ty->isOpaque());
1925   NonOpaqueStructTypes.insert(Ty);
1926 }
1927
1928 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1929   assert(!Ty->isOpaque());
1930   NonOpaqueStructTypes.insert(Ty);
1931   bool Removed = OpaqueStructTypes.erase(Ty);
1932   (void)Removed;
1933   assert(Removed);
1934 }
1935
1936 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1937   assert(Ty->isOpaque());
1938   OpaqueStructTypes.insert(Ty);
1939 }
1940
1941 StructType *
1942 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1943                                                bool IsPacked) {
1944   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1945   auto I = NonOpaqueStructTypes.find_as(Key);
1946   if (I == NonOpaqueStructTypes.end())
1947     return nullptr;
1948   return *I;
1949 }
1950
1951 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1952   if (Ty->isOpaque())
1953     return OpaqueStructTypes.count(Ty);
1954   auto I = NonOpaqueStructTypes.find(Ty);
1955   if (I == NonOpaqueStructTypes.end())
1956     return false;
1957   return *I == Ty;
1958 }
1959
1960 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1961     : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1962   TypeFinder StructTypes;
1963   StructTypes.run(M, true);
1964   for (StructType *Ty : StructTypes) {
1965     if (Ty->isOpaque())
1966       IdentifiedStructTypes.addOpaque(Ty);
1967     else
1968       IdentifiedStructTypes.addNonOpaque(Ty);
1969   }
1970 }
1971
1972 bool Linker::linkInModule(Module &Src, unsigned Flags,
1973                           const FunctionInfoIndex *Index,
1974                           DenseSet<const GlobalValue *> *FunctionsToImport) {
1975   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1976                          DiagnosticHandler, Flags, Index, FunctionsToImport);
1977   bool RetCode = TheLinker.run();
1978   Composite.dropTriviallyDeadConstantArrays();
1979   return RetCode;
1980 }
1981
1982 //===----------------------------------------------------------------------===//
1983 // LinkModules entrypoint.
1984 //===----------------------------------------------------------------------===//
1985
1986 /// This function links two modules together, with the resulting Dest module
1987 /// modified to be the composite of the two input modules. If an error occurs,
1988 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1989 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1990 /// relied on to be consistent.
1991 bool Linker::linkModules(Module &Dest, Module &Src,
1992                          DiagnosticHandlerFunction DiagnosticHandler,
1993                          unsigned Flags) {
1994   Linker L(Dest, DiagnosticHandler);
1995   return L.linkInModule(Src, Flags);
1996 }
1997
1998 std::unique_ptr<Module>
1999 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
2000                              const FunctionInfoIndex *Index,
2001                              DiagnosticHandlerFunction DiagnosticHandler) {
2002   std::unique_ptr<llvm::Module> RenamedModule(
2003       new llvm::Module(M->getModuleIdentifier(), M->getContext()));
2004   Linker L(*RenamedModule.get(), DiagnosticHandler);
2005   if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
2006     return nullptr;
2007   return RenamedModule;
2008 }
2009
2010 //===----------------------------------------------------------------------===//
2011 // C API.
2012 //===----------------------------------------------------------------------===//
2013
2014 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2015                          LLVMLinkerMode Unused, char **OutMessages) {
2016   Module *D = unwrap(Dest);
2017   std::string Message;
2018   raw_string_ostream Stream(Message);
2019   DiagnosticPrinterRawOStream DP(Stream);
2020
2021   LLVMBool Result = Linker::linkModules(
2022       *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2023
2024   if (OutMessages && Result) {
2025     Stream.flush();
2026     *OutMessages = strdup(Message.c_str());
2027   }
2028   return Result;
2029 }