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