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