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