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