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