Link the type of aliases.
[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/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.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/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include <cctype>
30 #include <tuple>
31 using namespace llvm;
32
33
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
37
38 namespace {
39 typedef SmallPtrSet<StructType *, 32> TypeSet;
40
41 class TypeMapTy : public ValueMapTypeRemapper {
42   /// This is a mapping from a source type to a destination type to use.
43   DenseMap<Type*, Type*> MappedTypes;
44
45   /// When checking to see if two subgraphs are isomorphic, we speculatively
46   /// add types to MappedTypes, but keep track of them here in case we need to
47   /// roll back.
48   SmallVector<Type*, 16> SpeculativeTypes;
49
50   /// This is a list of non-opaque structs in the source module that are mapped
51   /// to an opaque struct in the destination module.
52   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
53
54   /// This is the set of opaque types in the destination modules who are
55   /// getting a body from the source module.
56   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
57
58 public:
59   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
60
61   TypeSet &DstStructTypesSet;
62   /// Indicate that the specified type in the destination module is conceptually
63   /// equivalent to the specified type in the source module.
64   void addTypeMapping(Type *DstTy, Type *SrcTy);
65
66   /// Produce a body for an opaque type in the dest module from a type
67   /// definition in the source module.
68   void linkDefinedTypeBodies();
69
70   /// Return the mapped type to use for the specified input type from the
71   /// source module.
72   Type *get(Type *SrcTy);
73
74   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75
76   /// Dump out the type map for debugging purposes.
77   void dump() const {
78     for (DenseMap<Type*, Type*>::const_iterator
79            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80       dbgs() << "TypeMap: ";
81       I->first->print(dbgs());
82       dbgs() << " => ";
83       I->second->print(dbgs());
84       dbgs() << '\n';
85     }
86   }
87
88 private:
89   Type *getImpl(Type *T);
90   /// Implement the ValueMapTypeRemapper interface.
91   Type *remapType(Type *SrcTy) override {
92     return get(SrcTy);
93   }
94
95   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 };
97 }
98
99 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100   Type *&Entry = MappedTypes[SrcTy];
101   if (Entry) return;
102
103   if (DstTy == SrcTy) {
104     Entry = DstTy;
105     return;
106   }
107
108   // Check to see if these types are recursively isomorphic and establish a
109   // mapping between them if so.
110   if (!areTypesIsomorphic(DstTy, SrcTy)) {
111     // Oops, they aren't isomorphic.  Just discard this request by rolling out
112     // any speculative mappings we've established.
113     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114       MappedTypes.erase(SpeculativeTypes[i]);
115   }
116   SpeculativeTypes.clear();
117 }
118
119 /// Recursively walk this pair of types, returning true if they are isomorphic,
120 /// false if they are not.
121 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122   // Two types with differing kinds are clearly not isomorphic.
123   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
124
125   // If we have an entry in the MappedTypes table, then we have our answer.
126   Type *&Entry = MappedTypes[SrcTy];
127   if (Entry)
128     return Entry == DstTy;
129
130   // Two identical types are clearly isomorphic.  Remember this
131   // non-speculatively.
132   if (DstTy == SrcTy) {
133     Entry = DstTy;
134     return true;
135   }
136
137   // Okay, we have two types with identical kinds that we haven't seen before.
138
139   // If this is an opaque struct type, special case it.
140   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141     // Mapping an opaque type to any struct, just keep the dest struct.
142     if (SSTy->isOpaque()) {
143       Entry = DstTy;
144       SpeculativeTypes.push_back(SrcTy);
145       return true;
146     }
147
148     // Mapping a non-opaque source type to an opaque dest.  If this is the first
149     // type that we're mapping onto this destination type then we succeed.  Keep
150     // the dest, but fill it in later.  This doesn't need to be speculative.  If
151     // this is the second (different) type that we're trying to map onto the
152     // same opaque type then we fail.
153     if (cast<StructType>(DstTy)->isOpaque()) {
154       // We can only map one source type onto the opaque destination type.
155       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
156         return false;
157       SrcDefinitionsToResolve.push_back(SSTy);
158       Entry = DstTy;
159       return true;
160     }
161   }
162
163   // If the number of subtypes disagree between the two types, then we fail.
164   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
165     return false;
166
167   // Fail if any of the extra properties (e.g. array size) of the type disagree.
168   if (isa<IntegerType>(DstTy))
169     return false;  // bitwidth disagrees.
170   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
172       return false;
173
174   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176       return false;
177   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178     StructType *SSTy = cast<StructType>(SrcTy);
179     if (DSTy->isLiteral() != SSTy->isLiteral() ||
180         DSTy->isPacked() != SSTy->isPacked())
181       return false;
182   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184       return false;
185   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
186     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
187       return false;
188   }
189
190   // Otherwise, we speculate that these two types will line up and recursively
191   // check the subelements.
192   Entry = DstTy;
193   SpeculativeTypes.push_back(SrcTy);
194
195   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196     if (!areTypesIsomorphic(DstTy->getContainedType(i),
197                             SrcTy->getContainedType(i)))
198       return false;
199
200   // If everything seems to have lined up, then everything is great.
201   return true;
202 }
203
204 void TypeMapTy::linkDefinedTypeBodies() {
205   SmallVector<Type*, 16> Elements;
206   SmallString<16> TmpName;
207
208   // Note that processing entries in this loop (calling 'get') can add new
209   // entries to the SrcDefinitionsToResolve vector.
210   while (!SrcDefinitionsToResolve.empty()) {
211     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
212     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
213
214     // TypeMap is a many-to-one mapping, if there were multiple types that
215     // provide a body for DstSTy then previous iterations of this loop may have
216     // already handled it.  Just ignore this case.
217     if (!DstSTy->isOpaque()) continue;
218     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
219
220     // Map the body of the source type over to a new body for the dest type.
221     Elements.resize(SrcSTy->getNumElements());
222     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
223       Elements[i] = getImpl(SrcSTy->getElementType(i));
224
225     DstSTy->setBody(Elements, SrcSTy->isPacked());
226
227     // If DstSTy has no name or has a longer name than STy, then viciously steal
228     // STy's name.
229     if (!SrcSTy->hasName()) continue;
230     StringRef SrcName = SrcSTy->getName();
231
232     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
233       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
234       SrcSTy->setName("");
235       DstSTy->setName(TmpName.str());
236       TmpName.clear();
237     }
238   }
239
240   DstResolvedOpaqueTypes.clear();
241 }
242
243 Type *TypeMapTy::get(Type *Ty) {
244   Type *Result = getImpl(Ty);
245
246   // If this caused a reference to any struct type, resolve it before returning.
247   if (!SrcDefinitionsToResolve.empty())
248     linkDefinedTypeBodies();
249   return Result;
250 }
251
252 /// This is the recursive version of get().
253 Type *TypeMapTy::getImpl(Type *Ty) {
254   // If we already have an entry for this type, return it.
255   Type **Entry = &MappedTypes[Ty];
256   if (*Entry) return *Entry;
257
258   // If this is not a named struct type, then just map all of the elements and
259   // then rebuild the type from inside out.
260   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
261     // If there are no element types to map, then the type is itself.  This is
262     // true for the anonymous {} struct, things like 'float', integers, etc.
263     if (Ty->getNumContainedTypes() == 0)
264       return *Entry = Ty;
265
266     // Remap all of the elements, keeping track of whether any of them change.
267     bool AnyChange = false;
268     SmallVector<Type*, 4> ElementTypes;
269     ElementTypes.resize(Ty->getNumContainedTypes());
270     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
271       ElementTypes[i] = getImpl(Ty->getContainedType(i));
272       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
273     }
274
275     // If we found our type while recursively processing stuff, just use it.
276     Entry = &MappedTypes[Ty];
277     if (*Entry) return *Entry;
278
279     // If all of the element types mapped directly over, then the type is usable
280     // as-is.
281     if (!AnyChange)
282       return *Entry = Ty;
283
284     // Otherwise, rebuild a modified type.
285     switch (Ty->getTypeID()) {
286     default: llvm_unreachable("unknown derived type to remap");
287     case Type::ArrayTyID:
288       return *Entry = ArrayType::get(ElementTypes[0],
289                                      cast<ArrayType>(Ty)->getNumElements());
290     case Type::VectorTyID:
291       return *Entry = VectorType::get(ElementTypes[0],
292                                       cast<VectorType>(Ty)->getNumElements());
293     case Type::PointerTyID:
294       return *Entry = PointerType::get(ElementTypes[0],
295                                       cast<PointerType>(Ty)->getAddressSpace());
296     case Type::FunctionTyID:
297       return *Entry = FunctionType::get(ElementTypes[0],
298                                         makeArrayRef(ElementTypes).slice(1),
299                                         cast<FunctionType>(Ty)->isVarArg());
300     case Type::StructTyID:
301       // Note that this is only reached for anonymous structs.
302       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
303                                       cast<StructType>(Ty)->isPacked());
304     }
305   }
306
307   // Otherwise, this is an unmapped named struct.  If the struct can be directly
308   // mapped over, just use it as-is.  This happens in a case when the linked-in
309   // module has something like:
310   //   %T = type {%T*, i32}
311   //   @GV = global %T* null
312   // where T does not exist at all in the destination module.
313   //
314   // The other case we watch for is when the type is not in the destination
315   // module, but that it has to be rebuilt because it refers to something that
316   // is already mapped.  For example, if the destination module has:
317   //  %A = type { i32 }
318   // and the source module has something like
319   //  %A' = type { i32 }
320   //  %B = type { %A'* }
321   //  @GV = global %B* null
322   // then we want to create a new type: "%B = type { %A*}" and have it take the
323   // pristine "%B" name from the source module.
324   //
325   // To determine which case this is, we have to recursively walk the type graph
326   // speculating that we'll be able to reuse it unmodified.  Only if this is
327   // safe would we map the entire thing over.  Because this is an optimization,
328   // and is not required for the prettiness of the linked module, we just skip
329   // it and always rebuild a type here.
330   StructType *STy = cast<StructType>(Ty);
331
332   // If the type is opaque, we can just use it directly.
333   if (STy->isOpaque()) {
334     // A named structure type from src module is used. Add it to the Set of
335     // identified structs in the destination module.
336     DstStructTypesSet.insert(STy);
337     return *Entry = STy;
338   }
339
340   // Otherwise we create a new type and resolve its body later.  This will be
341   // resolved by the top level of get().
342   SrcDefinitionsToResolve.push_back(STy);
343   StructType *DTy = StructType::create(STy->getContext());
344   // A new identified structure type was created. Add it to the set of
345   // identified structs in the destination module.
346   DstStructTypesSet.insert(DTy);
347   DstResolvedOpaqueTypes.insert(DTy);
348   return *Entry = DTy;
349 }
350
351 //===----------------------------------------------------------------------===//
352 // ModuleLinker implementation.
353 //===----------------------------------------------------------------------===//
354
355 namespace {
356   class ModuleLinker;
357
358   /// Creates prototypes for functions that are lazily linked on the fly. This
359   /// speeds up linking for modules with many/ lazily linked functions of which
360   /// few get used.
361   class ValueMaterializerTy : public ValueMaterializer {
362     TypeMapTy &TypeMap;
363     Module *DstM;
364     std::vector<Function*> &LazilyLinkFunctions;
365   public:
366     ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
367                         std::vector<Function*> &LazilyLinkFunctions) :
368       ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
369       LazilyLinkFunctions(LazilyLinkFunctions) {
370     }
371
372     Value *materializeValueFor(Value *V) override;
373   };
374
375   namespace {
376   class LinkDiagnosticInfo : public DiagnosticInfo {
377     const Twine &Msg;
378
379   public:
380     LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
381     void print(DiagnosticPrinter &DP) const override;
382   };
383   LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
384                                          const Twine &Msg)
385       : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
386   void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
387   }
388
389   /// This is an implementation class for the LinkModules function, which is the
390   /// entrypoint for this file.
391   class ModuleLinker {
392     Module *DstM, *SrcM;
393
394     TypeMapTy TypeMap;
395     ValueMaterializerTy ValMaterializer;
396
397     /// Mapping of values from what they used to be in Src, to what they are now
398     /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
399     /// due to the use of Value handles which the Linker doesn't actually need,
400     /// but this allows us to reuse the ValueMapper code.
401     ValueToValueMapTy ValueMap;
402
403     struct AppendingVarInfo {
404       GlobalVariable *NewGV;   // New aggregate global in dest module.
405       const Constant *DstInit; // Old initializer from dest module.
406       const Constant *SrcInit; // Old initializer from src module.
407     };
408
409     std::vector<AppendingVarInfo> AppendingVars;
410
411     // Set of items not to link in from source.
412     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
413
414     // Vector of functions to lazily link in.
415     std::vector<Function*> LazilyLinkFunctions;
416
417     Linker::DiagnosticHandlerFunction DiagnosticHandler;
418
419   public:
420     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
421                  Linker::DiagnosticHandlerFunction DiagnosticHandler)
422         : DstM(dstM), SrcM(srcM), TypeMap(Set),
423           ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
424           DiagnosticHandler(DiagnosticHandler) {}
425
426     bool run();
427
428   private:
429     bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
430                               const GlobalValue &Src);
431
432     /// Helper method for setting a message and returning an error code.
433     bool emitError(const Twine &Message) {
434       DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
435       return true;
436     }
437
438     void emitWarning(const Twine &Message) {
439       DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
440     }
441
442     bool getComdatLeader(Module *M, StringRef ComdatName,
443                          const GlobalVariable *&GVar);
444     bool computeResultingSelectionKind(StringRef ComdatName,
445                                        Comdat::SelectionKind Src,
446                                        Comdat::SelectionKind Dst,
447                                        Comdat::SelectionKind &Result,
448                                        bool &LinkFromSrc);
449     std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
450         ComdatsChosen;
451     bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
452                          bool &LinkFromSrc);
453
454     /// Given a global in the source module, return the global in the
455     /// destination module that is being linked to, if any.
456     GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
457       // If the source has no name it can't link.  If it has local linkage,
458       // there is no name match-up going on.
459       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
460         return nullptr;
461
462       // Otherwise see if we have a match in the destination module's symtab.
463       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
464       if (!DGV) return nullptr;
465
466       // If we found a global with the same name in the dest module, but it has
467       // internal linkage, we are really not doing any linkage here.
468       if (DGV->hasLocalLinkage())
469         return nullptr;
470
471       // Otherwise, we do in fact link to the destination global.
472       return DGV;
473     }
474
475     void computeTypeMapping();
476
477     void upgradeMismatchedGlobalArray(StringRef Name);
478     void upgradeMismatchedGlobals();
479
480     bool linkAppendingVarProto(GlobalVariable *DstGV,
481                                const GlobalVariable *SrcGV);
482
483     bool linkGlobalValueProto(GlobalValue *GV);
484     GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
485                                          GlobalValue *DGV, bool LinkFromSrc);
486     GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
487                                    bool LinkFromSrc);
488     GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
489                                       bool LinkFromSrc);
490
491     bool linkModuleFlagsMetadata();
492
493     void linkAppendingVarInit(const AppendingVarInfo &AVI);
494     void linkGlobalInits();
495     void linkFunctionBody(Function *Dst, Function *Src);
496     void linkAliasBodies();
497     void linkNamedMDNodes();
498   };
499 }
500
501 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
502 /// table. This is good for all clients except for us. Go through the trouble
503 /// to force this back.
504 static void forceRenaming(GlobalValue *GV, StringRef Name) {
505   // If the global doesn't force its name or if it already has the right name,
506   // there is nothing for us to do.
507   if (GV->hasLocalLinkage() || GV->getName() == Name)
508     return;
509
510   Module *M = GV->getParent();
511
512   // If there is a conflict, rename the conflict.
513   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
514     GV->takeName(ConflictGV);
515     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
516     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
517   } else {
518     GV->setName(Name);              // Force the name back
519   }
520 }
521
522 /// copy additional attributes (those not needed to construct a GlobalValue)
523 /// from the SrcGV to the DestGV.
524 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
525   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
526   auto *DestGO = dyn_cast<GlobalObject>(DestGV);
527   unsigned Alignment;
528   if (DestGO)
529     Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
530
531   DestGV->copyAttributesFrom(SrcGV);
532
533   if (DestGO)
534     DestGO->setAlignment(Alignment);
535
536   forceRenaming(DestGV, SrcGV->getName());
537 }
538
539 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
540                                GlobalValue::VisibilityTypes b) {
541   if (a == GlobalValue::HiddenVisibility)
542     return false;
543   if (b == GlobalValue::HiddenVisibility)
544     return true;
545   if (a == GlobalValue::ProtectedVisibility)
546     return false;
547   if (b == GlobalValue::ProtectedVisibility)
548     return true;
549   return false;
550 }
551
552 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
553   Function *SF = dyn_cast<Function>(V);
554   if (!SF)
555     return nullptr;
556
557   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
558                                   SF->getLinkage(), SF->getName(), DstM);
559   copyGVAttributes(DF, SF);
560
561   if (Comdat *SC = SF->getComdat()) {
562     Comdat *DC = DstM->getOrInsertComdat(SC->getName());
563     DF->setComdat(DC);
564   }
565
566   LazilyLinkFunctions.push_back(SF);
567   return DF;
568 }
569
570 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
571                                    const GlobalVariable *&GVar) {
572   const GlobalValue *GVal = M->getNamedValue(ComdatName);
573   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
574     GVal = GA->getBaseObject();
575     if (!GVal)
576       // We cannot resolve the size of the aliasee yet.
577       return emitError("Linking COMDATs named '" + ComdatName +
578                        "': COMDAT key involves incomputable alias size.");
579   }
580
581   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
582   if (!GVar)
583     return emitError(
584         "Linking COMDATs named '" + ComdatName +
585         "': GlobalVariable required for data dependent selection!");
586
587   return false;
588 }
589
590 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
591                                                  Comdat::SelectionKind Src,
592                                                  Comdat::SelectionKind Dst,
593                                                  Comdat::SelectionKind &Result,
594                                                  bool &LinkFromSrc) {
595   // The ability to mix Comdat::SelectionKind::Any with
596   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
597   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
598                          Dst == Comdat::SelectionKind::Largest;
599   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
600                          Src == Comdat::SelectionKind::Largest;
601   if (DstAnyOrLargest && SrcAnyOrLargest) {
602     if (Dst == Comdat::SelectionKind::Largest ||
603         Src == Comdat::SelectionKind::Largest)
604       Result = Comdat::SelectionKind::Largest;
605     else
606       Result = Comdat::SelectionKind::Any;
607   } else if (Src == Dst) {
608     Result = Dst;
609   } else {
610     return emitError("Linking COMDATs named '" + ComdatName +
611                      "': invalid selection kinds!");
612   }
613
614   switch (Result) {
615   case Comdat::SelectionKind::Any:
616     // Go with Dst.
617     LinkFromSrc = false;
618     break;
619   case Comdat::SelectionKind::NoDuplicates:
620     return emitError("Linking COMDATs named '" + ComdatName +
621                      "': noduplicates has been violated!");
622   case Comdat::SelectionKind::ExactMatch:
623   case Comdat::SelectionKind::Largest:
624   case Comdat::SelectionKind::SameSize: {
625     const GlobalVariable *DstGV;
626     const GlobalVariable *SrcGV;
627     if (getComdatLeader(DstM, ComdatName, DstGV) ||
628         getComdatLeader(SrcM, ComdatName, SrcGV))
629       return true;
630
631     const DataLayout *DstDL = DstM->getDataLayout();
632     const DataLayout *SrcDL = SrcM->getDataLayout();
633     if (!DstDL || !SrcDL) {
634       return emitError(
635           "Linking COMDATs named '" + ComdatName +
636           "': can't do size dependent selection without DataLayout!");
637     }
638     uint64_t DstSize =
639         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
640     uint64_t SrcSize =
641         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
642     if (Result == Comdat::SelectionKind::ExactMatch) {
643       if (SrcGV->getInitializer() != DstGV->getInitializer())
644         return emitError("Linking COMDATs named '" + ComdatName +
645                          "': ExactMatch violated!");
646       LinkFromSrc = false;
647     } else if (Result == Comdat::SelectionKind::Largest) {
648       LinkFromSrc = SrcSize > DstSize;
649     } else if (Result == Comdat::SelectionKind::SameSize) {
650       if (SrcSize != DstSize)
651         return emitError("Linking COMDATs named '" + ComdatName +
652                          "': SameSize violated!");
653       LinkFromSrc = false;
654     } else {
655       llvm_unreachable("unknown selection kind");
656     }
657     break;
658   }
659   }
660
661   return false;
662 }
663
664 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
665                                    Comdat::SelectionKind &Result,
666                                    bool &LinkFromSrc) {
667   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
668   StringRef ComdatName = SrcC->getName();
669   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
670   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
671
672   if (DstCI == ComdatSymTab.end()) {
673     // Use the comdat if it is only available in one of the modules.
674     LinkFromSrc = true;
675     Result = SSK;
676     return false;
677   }
678
679   const Comdat *DstC = &DstCI->second;
680   Comdat::SelectionKind DSK = DstC->getSelectionKind();
681   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
682                                        LinkFromSrc);
683 }
684
685 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
686                                         const GlobalValue &Dest,
687                                         const GlobalValue &Src) {
688   // We always have to add Src if it has appending linkage.
689   if (Src.hasAppendingLinkage()) {
690     LinkFromSrc = true;
691     return false;
692   }
693
694   bool SrcIsDeclaration = Src.isDeclarationForLinker();
695   bool DestIsDeclaration = Dest.isDeclarationForLinker();
696
697   if (SrcIsDeclaration) {
698     // If Src is external or if both Src & Dest are external..  Just link the
699     // external globals, we aren't adding anything.
700     if (Src.hasDLLImportStorageClass()) {
701       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
702       LinkFromSrc = DestIsDeclaration;
703       return false;
704     }
705     // If the Dest is weak, use the source linkage.
706     LinkFromSrc = Dest.hasExternalWeakLinkage();
707     return false;
708   }
709
710   if (DestIsDeclaration) {
711     // If Dest is external but Src is not:
712     LinkFromSrc = true;
713     return false;
714   }
715
716   if (Src.hasCommonLinkage()) {
717     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
718       LinkFromSrc = true;
719       return false;
720     }
721
722     if (!Dest.hasCommonLinkage()) {
723       LinkFromSrc = false;
724       return false;
725     }
726
727     // FIXME: Make datalayout mandatory and just use getDataLayout().
728     DataLayout DL(Dest.getParent());
729
730     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
731     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
732     LinkFromSrc = SrcSize > DestSize;
733     return false;
734   }
735
736   if (Src.isWeakForLinker()) {
737     assert(!Dest.hasExternalWeakLinkage());
738     assert(!Dest.hasAvailableExternallyLinkage());
739
740     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
741       LinkFromSrc = true;
742       return false;
743     }
744
745     LinkFromSrc = false;
746     return false;
747   }
748
749   if (Dest.isWeakForLinker()) {
750     assert(Src.hasExternalLinkage());
751     LinkFromSrc = true;
752     return false;
753   }
754
755   assert(!Src.hasExternalWeakLinkage());
756   assert(!Dest.hasExternalWeakLinkage());
757   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
758          "Unexpected linkage type!");
759   return emitError("Linking globals named '" + Src.getName() +
760                    "': symbol multiply defined!");
761 }
762
763 /// Loop over all of the linked values to compute type mappings.  For example,
764 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
765 /// types 'Foo' but one got renamed when the module was loaded into the same
766 /// LLVMContext.
767 void ModuleLinker::computeTypeMapping() {
768   for (GlobalValue &SGV : SrcM->globals()) {
769     GlobalValue *DGV = getLinkedToGlobal(&SGV);
770     if (!DGV)
771       continue;
772
773     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
774       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
775       continue;
776     }
777
778     // Unify the element type of appending arrays.
779     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
780     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
781     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
782   }
783
784   for (GlobalValue &SGV : *SrcM) {
785     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
786       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
787   }
788
789   for (GlobalValue &SGV : SrcM->aliases()) {
790     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
791       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
792   }
793
794   // Incorporate types by name, scanning all the types in the source module.
795   // At this point, the destination module may have a type "%foo = { i32 }" for
796   // example.  When the source module got loaded into the same LLVMContext, if
797   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
798   TypeFinder SrcStructTypes;
799   SrcStructTypes.run(*SrcM, true);
800   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
801                                                  SrcStructTypes.end());
802
803   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
804     StructType *ST = SrcStructTypes[i];
805     if (!ST->hasName()) continue;
806
807     // Check to see if there is a dot in the name followed by a digit.
808     size_t DotPos = ST->getName().rfind('.');
809     if (DotPos == 0 || DotPos == StringRef::npos ||
810         ST->getName().back() == '.' ||
811         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
812       continue;
813
814     // Check to see if the destination module has a struct with the prefix name.
815     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
816       // Don't use it if this actually came from the source module. They're in
817       // the same LLVMContext after all. Also don't use it unless the type is
818       // actually used in the destination module. This can happen in situations
819       // like this:
820       //
821       //      Module A                         Module B
822       //      --------                         --------
823       //   %Z = type { %A }                %B = type { %C.1 }
824       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
825       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
826       //   %C = type { i8* }               %B.3 = type { %C.1 }
827       //
828       // When we link Module B with Module A, the '%B' in Module B is
829       // used. However, that would then use '%C.1'. But when we process '%C.1',
830       // we prefer to take the '%C' version. So we are then left with both
831       // '%C.1' and '%C' being used for the same types. This leads to some
832       // variables using one type and some using the other.
833       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
834         TypeMap.addTypeMapping(DST, ST);
835   }
836
837   // Now that we have discovered all of the type equivalences, get a body for
838   // any 'opaque' types in the dest module that are now resolved.
839   TypeMap.linkDefinedTypeBodies();
840 }
841
842 static void upgradeGlobalArray(GlobalVariable *GV) {
843   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
844   StructType *OldTy = cast<StructType>(ATy->getElementType());
845   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
846
847   // Get the upgraded 3 element type.
848   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
849   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
850                   VoidPtrTy};
851   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
852
853   // Build new constants with a null third field filled in.
854   Constant *OldInitC = GV->getInitializer();
855   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
856   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
857     // Invalid initializer; give up.
858     return;
859   std::vector<Constant *> Initializers;
860   if (OldInit && OldInit->getNumOperands()) {
861     Value *Null = Constant::getNullValue(VoidPtrTy);
862     for (Use &U : OldInit->operands()) {
863       ConstantStruct *Init = cast<ConstantStruct>(U.get());
864       Initializers.push_back(ConstantStruct::get(
865           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
866     }
867   }
868   assert(Initializers.size() == ATy->getNumElements() &&
869          "Failed to copy all array elements");
870
871   // Replace the old GV with a new one.
872   ATy = ArrayType::get(NewTy, Initializers.size());
873   Constant *NewInit = ConstantArray::get(ATy, Initializers);
874   GlobalVariable *NewGV = new GlobalVariable(
875       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
876       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
877       GV->isExternallyInitialized());
878   NewGV->copyAttributesFrom(GV);
879   NewGV->takeName(GV);
880   assert(GV->use_empty() && "program cannot use initializer list");
881   GV->eraseFromParent();
882 }
883
884 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
885   // Look for the global arrays.
886   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
887   if (!DstGV)
888     return;
889   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
890   if (!SrcGV)
891     return;
892
893   // Check if the types already match.
894   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
895   auto *SrcTy =
896       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
897   if (DstTy == SrcTy)
898     return;
899
900   // Grab the element types.  We can only upgrade an array of a two-field
901   // struct.  Only bother if the other one has three-fields.
902   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
903   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
904   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
905     upgradeGlobalArray(DstGV);
906     return;
907   }
908   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
909     upgradeGlobalArray(SrcGV);
910
911   // We can't upgrade any other differences.
912 }
913
914 void ModuleLinker::upgradeMismatchedGlobals() {
915   upgradeMismatchedGlobalArray("llvm.global_ctors");
916   upgradeMismatchedGlobalArray("llvm.global_dtors");
917 }
918
919 /// If there were any appending global variables, link them together now.
920 /// Return true on error.
921 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
922                                          const GlobalVariable *SrcGV) {
923
924   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925     return emitError("Linking globals named '" + SrcGV->getName() +
926            "': can only link appending global with another appending global!");
927
928   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
929   ArrayType *SrcTy =
930     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931   Type *EltTy = DstTy->getElementType();
932
933   // Check to see that they two arrays agree on type.
934   if (EltTy != SrcTy->getElementType())
935     return emitError("Appending variables with different element types!");
936   if (DstGV->isConstant() != SrcGV->isConstant())
937     return emitError("Appending variables linked with different const'ness!");
938
939   if (DstGV->getAlignment() != SrcGV->getAlignment())
940     return emitError(
941              "Appending variables with different alignment need to be linked!");
942
943   if (DstGV->getVisibility() != SrcGV->getVisibility())
944     return emitError(
945             "Appending variables with different visibility need to be linked!");
946
947   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
948     return emitError(
949         "Appending variables with different unnamed_addr need to be linked!");
950
951   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
952     return emitError(
953           "Appending variables with different section name need to be linked!");
954
955   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
957
958   // Create the new global variable.
959   GlobalVariable *NG =
960     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
961                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
962                        DstGV->getThreadLocalMode(),
963                        DstGV->getType()->getAddressSpace());
964
965   // Propagate alignment, visibility and section info.
966   copyGVAttributes(NG, DstGV);
967
968   AppendingVarInfo AVI;
969   AVI.NewGV = NG;
970   AVI.DstInit = DstGV->getInitializer();
971   AVI.SrcInit = SrcGV->getInitializer();
972   AppendingVars.push_back(AVI);
973
974   // Replace any uses of the two global variables with uses of the new
975   // global.
976   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
977
978   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979   DstGV->eraseFromParent();
980
981   // Track the source variable so we don't try to link it.
982   DoNotLinkFromSource.insert(SrcGV);
983
984   return false;
985 }
986
987 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
988   GlobalValue *DGV = getLinkedToGlobal(SGV);
989
990   // Handle the ultra special appending linkage case first.
991   if (DGV && DGV->hasAppendingLinkage())
992     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
993                                  cast<GlobalVariable>(SGV));
994
995   bool LinkFromSrc = true;
996   Comdat *C = nullptr;
997   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
998   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
999
1000   if (const Comdat *SC = SGV->getComdat()) {
1001     Comdat::SelectionKind SK;
1002     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1003     C = DstM->getOrInsertComdat(SC->getName());
1004     C->setSelectionKind(SK);
1005   } else if (DGV) {
1006     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1007       return true;
1008   }
1009
1010   if (!LinkFromSrc) {
1011     // Track the source global so that we don't attempt to copy it over when
1012     // processing global initializers.
1013     DoNotLinkFromSource.insert(SGV);
1014
1015     if (DGV)
1016       // Make sure to remember this mapping.
1017       ValueMap[SGV] =
1018           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1019   }
1020
1021   if (DGV) {
1022     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1023                      ? DGV->getVisibility()
1024                      : Visibility;
1025     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1026   }
1027
1028   if (!LinkFromSrc && !DGV)
1029     return false;
1030
1031   GlobalValue *NewGV;
1032   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1033     NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1034     if (!NewGV)
1035       return true;
1036   } else if (auto *SF = dyn_cast<Function>(SGV)) {
1037     NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1038   } else {
1039     NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1040   }
1041
1042   if (NewGV) {
1043     if (NewGV != DGV)
1044       copyGVAttributes(NewGV, SGV);
1045
1046     NewGV->setUnnamedAddr(HasUnnamedAddr);
1047     NewGV->setVisibility(Visibility);
1048
1049     if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1050       if (C)
1051         NewGO->setComdat(C);
1052     }
1053
1054     // Make sure to remember this mapping.
1055     if (NewGV != DGV) {
1056       if (DGV) {
1057         DGV->replaceAllUsesWith(
1058             ConstantExpr::getBitCast(NewGV, DGV->getType()));
1059         DGV->eraseFromParent();
1060       }
1061       ValueMap[SGV] = NewGV;
1062     }
1063   }
1064
1065   return false;
1066 }
1067
1068 /// Loop through the global variables in the src module and merge them into the
1069 /// dest module.
1070 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1071                                                    GlobalValue *DGV,
1072                                                    bool LinkFromSrc) {
1073   unsigned Alignment = 0;
1074   bool ClearConstant = false;
1075
1076   if (DGV) {
1077     if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1078       Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1079
1080     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1081     if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1082       ClearConstant = true;
1083   }
1084
1085   if (!LinkFromSrc) {
1086     if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1087       if (Alignment)
1088         NewGVar->setAlignment(Alignment);
1089       if (NewGVar->isDeclaration() && ClearConstant)
1090         NewGVar->setConstant(false);
1091     }
1092     return DGV;
1093   }
1094
1095   // No linking to be performed or linking from the source: simply create an
1096   // identical version of the symbol over in the dest module... the
1097   // initializer will be filled in later by LinkGlobalInits.
1098   GlobalVariable *NewDGV = new GlobalVariable(
1099       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1100       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1101       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1102       SGVar->getType()->getAddressSpace());
1103
1104   if (Alignment)
1105     NewDGV->setAlignment(Alignment);
1106
1107   return NewDGV;
1108 }
1109
1110 /// Link the function in the source module into the destination module if
1111 /// needed, setting up mapping information.
1112 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1113                                              GlobalValue *DGV,
1114                                              bool LinkFromSrc) {
1115   if (!LinkFromSrc)
1116     return DGV;
1117
1118   // If the function is to be lazily linked, don't create it just yet.
1119   // The ValueMaterializerTy will deal with creating it if it's used.
1120   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1121                SF->hasAvailableExternallyLinkage())) {
1122     DoNotLinkFromSource.insert(SF);
1123     return nullptr;
1124   }
1125
1126   // If there is no linkage to be performed or we are linking from the source,
1127   // bring SF over.
1128   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1129                           SF->getName(), DstM);
1130 }
1131
1132 /// Set up prototypes for any aliases that come over from the source module.
1133 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1134                                                 GlobalValue *DGV,
1135                                                 bool LinkFromSrc) {
1136   if (!LinkFromSrc)
1137     return DGV;
1138
1139   // If there is no linkage to be performed or we're linking from the source,
1140   // bring over SGA.
1141   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1142   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1143                              SGA->getLinkage(), SGA->getName(), DstM);
1144 }
1145
1146 static void getArrayElements(const Constant *C,
1147                              SmallVectorImpl<Constant *> &Dest) {
1148   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1149
1150   for (unsigned i = 0; i != NumElements; ++i)
1151     Dest.push_back(C->getAggregateElement(i));
1152 }
1153
1154 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1155   // Merge the initializer.
1156   SmallVector<Constant *, 16> DstElements;
1157   getArrayElements(AVI.DstInit, DstElements);
1158
1159   SmallVector<Constant *, 16> SrcElements;
1160   getArrayElements(AVI.SrcInit, SrcElements);
1161
1162   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1163
1164   StringRef Name = AVI.NewGV->getName();
1165   bool IsNewStructor =
1166       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1167       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1168
1169   for (auto *V : SrcElements) {
1170     if (IsNewStructor) {
1171       Constant *Key = V->getAggregateElement(2);
1172       if (DoNotLinkFromSource.count(Key))
1173         continue;
1174     }
1175     DstElements.push_back(
1176         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1177   }
1178   if (IsNewStructor) {
1179     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1180     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1181   }
1182
1183   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1184 }
1185
1186 /// Update the initializers in the Dest module now that all globals that may be
1187 /// referenced are in Dest.
1188 void ModuleLinker::linkGlobalInits() {
1189   // Loop over all of the globals in the src module, mapping them over as we go
1190   for (Module::const_global_iterator I = SrcM->global_begin(),
1191        E = SrcM->global_end(); I != E; ++I) {
1192
1193     // Only process initialized GV's or ones not already in dest.
1194     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1195
1196     // Grab destination global variable.
1197     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1198     // Figure out what the initializer looks like in the dest module.
1199     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1200                                  RF_None, &TypeMap, &ValMaterializer));
1201   }
1202 }
1203
1204 /// Copy the source function over into the dest function and fix up references
1205 /// to values. At this point we know that Dest is an external function, and
1206 /// that Src is not.
1207 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1208   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1209
1210   // Go through and convert function arguments over, remembering the mapping.
1211   Function::arg_iterator DI = Dst->arg_begin();
1212   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1213        I != E; ++I, ++DI) {
1214     DI->setName(I->getName());  // Copy the name over.
1215
1216     // Add a mapping to our mapping.
1217     ValueMap[I] = DI;
1218   }
1219
1220   // Splice the body of the source function into the dest function.
1221   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1222
1223   // At this point, all of the instructions and values of the function are now
1224   // copied over.  The only problem is that they are still referencing values in
1225   // the Source function as operands.  Loop through all of the operands of the
1226   // functions and patch them up to point to the local versions.
1227   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1228     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1229       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1230                        &ValMaterializer);
1231
1232   // There is no need to map the arguments anymore.
1233   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1234        I != E; ++I)
1235     ValueMap.erase(I);
1236
1237 }
1238
1239 /// Insert all of the aliases in Src into the Dest module.
1240 void ModuleLinker::linkAliasBodies() {
1241   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1242        I != E; ++I) {
1243     if (DoNotLinkFromSource.count(I))
1244       continue;
1245     if (Constant *Aliasee = I->getAliasee()) {
1246       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1247       Constant *Val =
1248           MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1249       DA->setAliasee(Val);
1250     }
1251   }
1252 }
1253
1254 /// Insert all of the named MDNodes in Src into the Dest module.
1255 void ModuleLinker::linkNamedMDNodes() {
1256   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1257   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1258        E = SrcM->named_metadata_end(); I != E; ++I) {
1259     // Don't link module flags here. Do them separately.
1260     if (&*I == SrcModFlags) continue;
1261     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1262     // Add Src elements into Dest node.
1263     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1264       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1265                                    RF_None, &TypeMap, &ValMaterializer));
1266   }
1267 }
1268
1269 /// Merge the linker flags in Src into the Dest module.
1270 bool ModuleLinker::linkModuleFlagsMetadata() {
1271   // If the source module has no module flags, we are done.
1272   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1273   if (!SrcModFlags) return false;
1274
1275   // If the destination module doesn't have module flags yet, then just copy
1276   // over the source module's flags.
1277   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1278   if (DstModFlags->getNumOperands() == 0) {
1279     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1280       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1281
1282     return false;
1283   }
1284
1285   // First build a map of the existing module flags and requirements.
1286   DenseMap<MDString*, MDNode*> Flags;
1287   SmallSetVector<MDNode*, 16> Requirements;
1288   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1289     MDNode *Op = DstModFlags->getOperand(I);
1290     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1291     MDString *ID = cast<MDString>(Op->getOperand(1));
1292
1293     if (Behavior->getZExtValue() == Module::Require) {
1294       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1295     } else {
1296       Flags[ID] = Op;
1297     }
1298   }
1299
1300   // Merge in the flags from the source module, and also collect its set of
1301   // requirements.
1302   bool HasErr = false;
1303   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1304     MDNode *SrcOp = SrcModFlags->getOperand(I);
1305     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1306     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1307     MDNode *DstOp = Flags.lookup(ID);
1308     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1309
1310     // If this is a requirement, add it and continue.
1311     if (SrcBehaviorValue == Module::Require) {
1312       // If the destination module does not already have this requirement, add
1313       // it.
1314       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1315         DstModFlags->addOperand(SrcOp);
1316       }
1317       continue;
1318     }
1319
1320     // If there is no existing flag with this ID, just add it.
1321     if (!DstOp) {
1322       Flags[ID] = SrcOp;
1323       DstModFlags->addOperand(SrcOp);
1324       continue;
1325     }
1326
1327     // Otherwise, perform a merge.
1328     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1329     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1330
1331     // If either flag has override behavior, handle it first.
1332     if (DstBehaviorValue == Module::Override) {
1333       // Diagnose inconsistent flags which both have override behavior.
1334       if (SrcBehaviorValue == Module::Override &&
1335           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1336         HasErr |= emitError("linking module flags '" + ID->getString() +
1337                             "': IDs have conflicting override values");
1338       }
1339       continue;
1340     } else if (SrcBehaviorValue == Module::Override) {
1341       // Update the destination flag to that of the source.
1342       DstOp->replaceOperandWith(0, SrcBehavior);
1343       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1344       continue;
1345     }
1346
1347     // Diagnose inconsistent merge behavior types.
1348     if (SrcBehaviorValue != DstBehaviorValue) {
1349       HasErr |= emitError("linking module flags '" + ID->getString() +
1350                           "': IDs have conflicting behaviors");
1351       continue;
1352     }
1353
1354     // Perform the merge for standard behavior types.
1355     switch (SrcBehaviorValue) {
1356     case Module::Require:
1357     case Module::Override: llvm_unreachable("not possible");
1358     case Module::Error: {
1359       // Emit an error if the values differ.
1360       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1361         HasErr |= emitError("linking module flags '" + ID->getString() +
1362                             "': IDs have conflicting values");
1363       }
1364       continue;
1365     }
1366     case Module::Warning: {
1367       // Emit a warning if the values differ.
1368       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1369         emitWarning("linking module flags '" + ID->getString() +
1370                     "': IDs have conflicting values");
1371       }
1372       continue;
1373     }
1374     case Module::Append: {
1375       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1376       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1377       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1378       Value **VP, **Values = VP = new Value*[NumOps];
1379       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1380         *VP = DstValue->getOperand(i);
1381       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1382         *VP = SrcValue->getOperand(i);
1383       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384                                                ArrayRef<Value*>(Values,
1385                                                                 NumOps)));
1386       delete[] Values;
1387       break;
1388     }
1389     case Module::AppendUnique: {
1390       SmallSetVector<Value*, 16> Elts;
1391       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1392       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1393       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1394         Elts.insert(DstValue->getOperand(i));
1395       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1396         Elts.insert(SrcValue->getOperand(i));
1397       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1398                                                ArrayRef<Value*>(Elts.begin(),
1399                                                                 Elts.end())));
1400       break;
1401     }
1402     }
1403   }
1404
1405   // Check all of the requirements.
1406   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1407     MDNode *Requirement = Requirements[I];
1408     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1409     Value *ReqValue = Requirement->getOperand(1);
1410
1411     MDNode *Op = Flags[Flag];
1412     if (!Op || Op->getOperand(2) != ReqValue) {
1413       HasErr |= emitError("linking module flags '" + Flag->getString() +
1414                           "': does not have the required value");
1415       continue;
1416     }
1417   }
1418
1419   return HasErr;
1420 }
1421
1422 bool ModuleLinker::run() {
1423   assert(DstM && "Null destination module");
1424   assert(SrcM && "Null source module");
1425
1426   // Inherit the target data from the source module if the destination module
1427   // doesn't have one already.
1428   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1429     DstM->setDataLayout(SrcM->getDataLayout());
1430
1431   // Copy the target triple from the source to dest if the dest's is empty.
1432   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1433     DstM->setTargetTriple(SrcM->getTargetTriple());
1434
1435   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1436       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1437     emitWarning("Linking two modules of different data layouts: '" +
1438                 SrcM->getModuleIdentifier() + "' is '" +
1439                 SrcM->getDataLayoutStr() + "' whereas '" +
1440                 DstM->getModuleIdentifier() + "' is '" +
1441                 DstM->getDataLayoutStr() + "'\n");
1442   }
1443   if (!SrcM->getTargetTriple().empty() &&
1444       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1445     emitWarning("Linking two modules of different target triples: " +
1446                 SrcM->getModuleIdentifier() + "' is '" +
1447                 SrcM->getTargetTriple() + "' whereas '" +
1448                 DstM->getModuleIdentifier() + "' is '" +
1449                 DstM->getTargetTriple() + "'\n");
1450   }
1451
1452   // Append the module inline asm string.
1453   if (!SrcM->getModuleInlineAsm().empty()) {
1454     if (DstM->getModuleInlineAsm().empty())
1455       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1456     else
1457       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1458                                SrcM->getModuleInlineAsm());
1459   }
1460
1461   // Loop over all of the linked values to compute type mappings.
1462   computeTypeMapping();
1463
1464   ComdatsChosen.clear();
1465   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1466     const Comdat &C = SMEC.getValue();
1467     if (ComdatsChosen.count(&C))
1468       continue;
1469     Comdat::SelectionKind SK;
1470     bool LinkFromSrc;
1471     if (getComdatResult(&C, SK, LinkFromSrc))
1472       return true;
1473     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1474   }
1475
1476   // Upgrade mismatched global arrays.
1477   upgradeMismatchedGlobals();
1478
1479   // Insert all of the globals in src into the DstM module... without linking
1480   // initializers (which could refer to functions not yet mapped over).
1481   for (Module::global_iterator I = SrcM->global_begin(),
1482        E = SrcM->global_end(); I != E; ++I)
1483     if (linkGlobalValueProto(I))
1484       return true;
1485
1486   // Link the functions together between the two modules, without doing function
1487   // bodies... this just adds external function prototypes to the DstM
1488   // function...  We do this so that when we begin processing function bodies,
1489   // all of the global values that may be referenced are available in our
1490   // ValueMap.
1491   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1492     if (linkGlobalValueProto(I))
1493       return true;
1494
1495   // If there were any aliases, link them now.
1496   for (Module::alias_iterator I = SrcM->alias_begin(),
1497        E = SrcM->alias_end(); I != E; ++I)
1498     if (linkGlobalValueProto(I))
1499       return true;
1500
1501   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1502     linkAppendingVarInit(AppendingVars[i]);
1503
1504   // Link in the function bodies that are defined in the source module into
1505   // DstM.
1506   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1507     // Skip if not linking from source.
1508     if (DoNotLinkFromSource.count(SF)) continue;
1509
1510     Function *DF = cast<Function>(ValueMap[SF]);
1511     if (SF->hasPrefixData()) {
1512       // Link in the prefix data.
1513       DF->setPrefixData(MapValue(
1514           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1515     }
1516
1517     // Materialize if needed.
1518     if (std::error_code EC = SF->materialize())
1519       return emitError(EC.message());
1520
1521     // Skip if no body (function is external).
1522     if (SF->isDeclaration())
1523       continue;
1524
1525     linkFunctionBody(DF, SF);
1526     SF->Dematerialize();
1527   }
1528
1529   // Resolve all uses of aliases with aliasees.
1530   linkAliasBodies();
1531
1532   // Remap all of the named MDNodes in Src into the DstM module. We do this
1533   // after linking GlobalValues so that MDNodes that reference GlobalValues
1534   // are properly remapped.
1535   linkNamedMDNodes();
1536
1537   // Merge the module flags into the DstM module.
1538   if (linkModuleFlagsMetadata())
1539     return true;
1540
1541   // Update the initializers in the DstM module now that all globals that may
1542   // be referenced are in DstM.
1543   linkGlobalInits();
1544
1545   // Process vector of lazily linked in functions.
1546   bool LinkedInAnyFunctions;
1547   do {
1548     LinkedInAnyFunctions = false;
1549
1550     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1551         E = LazilyLinkFunctions.end(); I != E; ++I) {
1552       Function *SF = *I;
1553       if (!SF)
1554         continue;
1555
1556       Function *DF = cast<Function>(ValueMap[SF]);
1557       if (SF->hasPrefixData()) {
1558         // Link in the prefix data.
1559         DF->setPrefixData(MapValue(SF->getPrefixData(),
1560                                    ValueMap,
1561                                    RF_None,
1562                                    &TypeMap,
1563                                    &ValMaterializer));
1564       }
1565
1566       // Materialize if needed.
1567       if (std::error_code EC = SF->materialize())
1568         return emitError(EC.message());
1569
1570       // Skip if no body (function is external).
1571       if (SF->isDeclaration())
1572         continue;
1573
1574       // Erase from vector *before* the function body is linked - linkFunctionBody could
1575       // invalidate I.
1576       LazilyLinkFunctions.erase(I);
1577
1578       // Link in function body.
1579       linkFunctionBody(DF, SF);
1580       SF->Dematerialize();
1581
1582       // Set flag to indicate we may have more functions to lazily link in
1583       // since we linked in a function.
1584       LinkedInAnyFunctions = true;
1585       break;
1586     }
1587   } while (LinkedInAnyFunctions);
1588
1589   // Now that all of the types from the source are used, resolve any structs
1590   // copied over to the dest that didn't exist there.
1591   TypeMap.linkDefinedTypeBodies();
1592
1593   return false;
1594 }
1595
1596 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1597   this->Composite = M;
1598   this->DiagnosticHandler = DiagnosticHandler;
1599
1600   TypeFinder StructTypes;
1601   StructTypes.run(*M, true);
1602   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1603 }
1604
1605 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1606   init(M, DiagnosticHandler);
1607 }
1608
1609 Linker::Linker(Module *M) {
1610   init(M, [this](const DiagnosticInfo &DI) {
1611     Composite->getContext().diagnose(DI);
1612   });
1613 }
1614
1615 Linker::~Linker() {
1616 }
1617
1618 void Linker::deleteModule() {
1619   delete Composite;
1620   Composite = nullptr;
1621 }
1622
1623 bool Linker::linkInModule(Module *Src) {
1624   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1625                          DiagnosticHandler);
1626   return TheLinker.run();
1627 }
1628
1629 //===----------------------------------------------------------------------===//
1630 // LinkModules entrypoint.
1631 //===----------------------------------------------------------------------===//
1632
1633 /// This function links two modules together, with the resulting Dest module
1634 /// modified to be the composite of the two input modules. If an error occurs,
1635 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1636 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1637 /// relied on to be consistent.
1638 bool Linker::LinkModules(Module *Dest, Module *Src,
1639                          DiagnosticHandlerFunction DiagnosticHandler) {
1640   Linker L(Dest, DiagnosticHandler);
1641   return L.linkInModule(Src);
1642 }
1643
1644 bool Linker::LinkModules(Module *Dest, Module *Src) {
1645   Linker L(Dest);
1646   return L.linkInModule(Src);
1647 }
1648
1649 //===----------------------------------------------------------------------===//
1650 // C API.
1651 //===----------------------------------------------------------------------===//
1652
1653 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1654                          LLVMLinkerMode Mode, char **OutMessages) {
1655   Module *D = unwrap(Dest);
1656   std::string Message;
1657   raw_string_ostream Stream(Message);
1658   DiagnosticPrinterRawOStream DP(Stream);
1659
1660   LLVMBool Result = Linker::LinkModules(
1661       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1662
1663   if (OutMessages && Result)
1664     *OutMessages = strdup(Message.c_str());
1665   return Result;
1666 }