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