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