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