]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/lib/Linker/LinkModules.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / 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   bool SrcIsDeclaration = Src->isDeclaration();
441   bool DestIsDeclaration = Dest->isDeclaration();
442   
443   if (SrcIsDeclaration) {
444     // If Src is external or if both Src & Dest are external..  Just link the
445     // external globals, we aren't adding anything.
446     if (Src->hasDLLImportLinkage()) {
447       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
448       if (DestIsDeclaration) {
449         LinkFromSrc = true;
450         LT = Src->getLinkage();
451       }
452     } else if (Dest->hasExternalWeakLinkage()) {
453       // If the Dest is weak, use the source linkage.
454       LinkFromSrc = true;
455       LT = Src->getLinkage();
456     } else {
457       LinkFromSrc = false;
458       LT = Dest->getLinkage();
459     }
460   } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
461     // If Dest is external but Src is not:
462     LinkFromSrc = true;
463     LT = Src->getLinkage();
464   } else if (Src->isWeakForLinker()) {
465     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
466     // or DLL* linkage.
467     if (Dest->hasExternalWeakLinkage() ||
468         Dest->hasAvailableExternallyLinkage() ||
469         (Dest->hasLinkOnceLinkage() &&
470          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
471       LinkFromSrc = true;
472       LT = Src->getLinkage();
473     } else {
474       LinkFromSrc = false;
475       LT = Dest->getLinkage();
476     }
477   } else if (Dest->isWeakForLinker()) {
478     // At this point we know that Src has External* or DLL* linkage.
479     if (Src->hasExternalWeakLinkage()) {
480       LinkFromSrc = false;
481       LT = Dest->getLinkage();
482     } else {
483       LinkFromSrc = true;
484       LT = GlobalValue::ExternalLinkage;
485     }
486   } else {
487     assert((Dest->hasExternalLinkage()  || Dest->hasDLLImportLinkage() ||
488             Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
489            (Src->hasExternalLinkage()   || Src->hasDLLImportLinkage() ||
490             Src->hasDLLExportLinkage()  || Src->hasExternalWeakLinkage()) &&
491            "Unexpected linkage type!");
492     return emitError("Linking globals named '" + Src->getName() +
493                  "': symbol multiply defined!");
494   }
495
496   // Check visibility
497   if (Src->getVisibility() != Dest->getVisibility() &&
498       !SrcIsDeclaration && !DestIsDeclaration &&
499       !Src->hasAvailableExternallyLinkage() &&
500       !Dest->hasAvailableExternallyLinkage())
501     return emitError("Linking globals named '" + Src->getName() +
502                    "': symbols have different visibilities!");
503   return false;
504 }
505
506 /// computeTypeMapping - Loop over all of the linked values to compute type
507 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
508 /// we have two struct types 'Foo' but one got renamed when the module was
509 /// loaded into the same LLVMContext.
510 void ModuleLinker::computeTypeMapping() {
511   // Incorporate globals.
512   for (Module::global_iterator I = SrcM->global_begin(),
513        E = SrcM->global_end(); I != E; ++I) {
514     GlobalValue *DGV = getLinkedToGlobal(I);
515     if (DGV == 0) continue;
516     
517     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
518       TypeMap.addTypeMapping(DGV->getType(), I->getType());
519       continue;      
520     }
521     
522     // Unify the element type of appending arrays.
523     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
524     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
525     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
526   }
527   
528   // Incorporate functions.
529   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
530     if (GlobalValue *DGV = getLinkedToGlobal(I))
531       TypeMap.addTypeMapping(DGV->getType(), I->getType());
532   }
533   
534   // Don't bother incorporating aliases, they aren't generally typed well.
535   
536   // Now that we have discovered all of the type equivalences, get a body for
537   // any 'opaque' types in the dest module that are now resolved. 
538   TypeMap.linkDefinedTypeBodies();
539 }
540
541 /// linkAppendingVarProto - If there were any appending global variables, link
542 /// them together now.  Return true on error.
543 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
544                                          GlobalVariable *SrcGV) {
545  
546   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
547     return emitError("Linking globals named '" + SrcGV->getName() +
548            "': can only link appending global with another appending global!");
549   
550   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
551   ArrayType *SrcTy =
552     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
553   Type *EltTy = DstTy->getElementType();
554   
555   // Check to see that they two arrays agree on type.
556   if (EltTy != SrcTy->getElementType())
557     return emitError("Appending variables with different element types!");
558   if (DstGV->isConstant() != SrcGV->isConstant())
559     return emitError("Appending variables linked with different const'ness!");
560   
561   if (DstGV->getAlignment() != SrcGV->getAlignment())
562     return emitError(
563              "Appending variables with different alignment need to be linked!");
564   
565   if (DstGV->getVisibility() != SrcGV->getVisibility())
566     return emitError(
567             "Appending variables with different visibility need to be linked!");
568   
569   if (DstGV->getSection() != SrcGV->getSection())
570     return emitError(
571           "Appending variables with different section name need to be linked!");
572   
573   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
574   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
575   
576   // Create the new global variable.
577   GlobalVariable *NG =
578     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
579                        DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
580                        DstGV->isThreadLocal(),
581                        DstGV->getType()->getAddressSpace());
582   
583   // Propagate alignment, visibility and section info.
584   CopyGVAttributes(NG, DstGV);
585   
586   AppendingVarInfo AVI;
587   AVI.NewGV = NG;
588   AVI.DstInit = DstGV->getInitializer();
589   AVI.SrcInit = SrcGV->getInitializer();
590   AppendingVars.push_back(AVI);
591
592   // Replace any uses of the two global variables with uses of the new
593   // global.
594   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
595
596   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
597   DstGV->eraseFromParent();
598   
599   // Zap the initializer in the source variable so we don't try to link it.
600   SrcGV->setInitializer(0);
601   SrcGV->setLinkage(GlobalValue::ExternalLinkage);
602   return false;
603 }
604
605 /// linkGlobalProto - Loop through the global variables in the src module and
606 /// merge them into the dest module.
607 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
608   GlobalValue *DGV = getLinkedToGlobal(SGV);
609
610   if (DGV) {
611     // Concatenation of appending linkage variables is magic and handled later.
612     if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
613       return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
614     
615     // Determine whether linkage of these two globals follows the source
616     // module's definition or the destination module's definition.
617     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
618     bool LinkFromSrc = false;
619     if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
620       return true;
621
622     // If we're not linking from the source, then keep the definition that we
623     // have.
624     if (!LinkFromSrc) {
625       // Special case for const propagation.
626       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
627         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
628           DGVar->setConstant(true);
629       
630       // Set calculated linkage.
631       DGV->setLinkage(NewLinkage);
632       
633       // Make sure to remember this mapping.
634       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
635       
636       // Destroy the source global's initializer (and convert it to a prototype)
637       // so that we don't attempt to copy it over when processing global
638       // initializers.
639       SGV->setInitializer(0);
640       SGV->setLinkage(GlobalValue::ExternalLinkage);
641       return false;
642     }
643   }
644   
645   // No linking to be performed or linking from the source: simply create an
646   // identical version of the symbol over in the dest module... the
647   // initializer will be filled in later by LinkGlobalInits.
648   GlobalVariable *NewDGV =
649     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
650                        SGV->isConstant(), SGV->getLinkage(), /*init*/0,
651                        SGV->getName(), /*insertbefore*/0,
652                        SGV->isThreadLocal(),
653                        SGV->getType()->getAddressSpace());
654   // Propagate alignment, visibility and section info.
655   CopyGVAttributes(NewDGV, SGV);
656
657   if (DGV) {
658     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
659     DGV->eraseFromParent();
660   }
661   
662   // Make sure to remember this mapping.
663   ValueMap[SGV] = NewDGV;
664   return false;
665 }
666
667 /// linkFunctionProto - Link the function in the source module into the
668 /// destination module if needed, setting up mapping information.
669 bool ModuleLinker::linkFunctionProto(Function *SF) {
670   GlobalValue *DGV = getLinkedToGlobal(SF);
671
672   if (DGV) {
673     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
674     bool LinkFromSrc = false;
675     if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
676       return true;
677     
678     if (!LinkFromSrc) {
679       // Set calculated linkage
680       DGV->setLinkage(NewLinkage);
681       
682       // Make sure to remember this mapping.
683       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
684       
685       // Remove the body from the source module so we don't attempt to remap it.
686       SF->deleteBody();
687       return false;
688     }
689   }
690   
691   // If there is no linkage to be performed or we are linking from the source,
692   // bring SF over.
693   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
694                                      SF->getLinkage(), SF->getName(), DstM);
695   CopyGVAttributes(NewDF, SF);
696
697   if (DGV) {
698     // Any uses of DF need to change to NewDF, with cast.
699     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
700     DGV->eraseFromParent();
701   }
702   
703   ValueMap[SF] = NewDF;
704   return false;
705 }
706
707 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
708 /// source module.
709 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
710   GlobalValue *DGV = getLinkedToGlobal(SGA);
711   
712   if (DGV) {
713     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
714     bool LinkFromSrc = false;
715     if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
716       return true;
717     
718     if (!LinkFromSrc) {
719       // Set calculated linkage.
720       DGV->setLinkage(NewLinkage);
721       
722       // Make sure to remember this mapping.
723       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
724       
725       // Remove the body from the source module so we don't attempt to remap it.
726       SGA->setAliasee(0);
727       return false;
728     }
729   }
730   
731   // If there is no linkage to be performed or we're linking from the source,
732   // bring over SGA.
733   GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
734                                        SGA->getLinkage(), SGA->getName(),
735                                        /*aliasee*/0, DstM);
736   CopyGVAttributes(NewDA, SGA);
737
738   if (DGV) {
739     // Any uses of DGV need to change to NewDA, with cast.
740     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
741     DGV->eraseFromParent();
742   }
743   
744   ValueMap[SGA] = NewDA;
745   return false;
746 }
747
748 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
749   // Merge the initializer.
750   SmallVector<Constant*, 16> Elements;
751   if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
752     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
753       Elements.push_back(I->getOperand(i));
754   } else {
755     assert(isa<ConstantAggregateZero>(AVI.DstInit));
756     ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
757     Type *EltTy = DstAT->getElementType();
758     Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
759   }
760   
761   Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
762   if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
763     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
764       Elements.push_back(I->getOperand(i));
765   } else {
766     assert(isa<ConstantAggregateZero>(SrcInit));
767     ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
768     Type *EltTy = SrcAT->getElementType();
769     Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
770   }
771   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
772   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
773 }
774
775
776 // linkGlobalInits - Update the initializers in the Dest module now that all
777 // globals that may be referenced are in Dest.
778 void ModuleLinker::linkGlobalInits() {
779   // Loop over all of the globals in the src module, mapping them over as we go
780   for (Module::const_global_iterator I = SrcM->global_begin(),
781        E = SrcM->global_end(); I != E; ++I) {
782     if (!I->hasInitializer()) continue;      // Only process initialized GV's.
783     
784     // Grab destination global variable.
785     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
786     // Figure out what the initializer looks like in the dest module.
787     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
788                                  RF_None, &TypeMap));
789   }
790 }
791
792 // linkFunctionBody - Copy the source function over into the dest function and
793 // fix up references to values.  At this point we know that Dest is an external
794 // function, and that Src is not.
795 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
796   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
797
798   // Go through and convert function arguments over, remembering the mapping.
799   Function::arg_iterator DI = Dst->arg_begin();
800   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
801        I != E; ++I, ++DI) {
802     DI->setName(I->getName());  // Copy the name over.
803
804     // Add a mapping to our mapping.
805     ValueMap[I] = DI;
806   }
807
808   // Splice the body of the source function into the dest function.
809   Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
810
811   // At this point, all of the instructions and values of the function are now
812   // copied over.  The only problem is that they are still referencing values in
813   // the Source function as operands.  Loop through all of the operands of the
814   // functions and patch them up to point to the local versions.
815   for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
816     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
817       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
818
819   // There is no need to map the arguments anymore.
820   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
821        I != E; ++I)
822     ValueMap.erase(I);
823 }
824
825
826 void ModuleLinker::linkAliasBodies() {
827   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
828        I != E; ++I)
829     if (Constant *Aliasee = I->getAliasee()) {
830       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
831       DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
832     }
833 }
834
835 /// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
836 /// module.
837 void ModuleLinker::linkNamedMDNodes() {
838   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
839        E = SrcM->named_metadata_end(); I != E; ++I) {
840     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
841     // Add Src elements into Dest node.
842     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
843       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
844                                    RF_None, &TypeMap));
845   }
846 }
847   
848 bool ModuleLinker::run() {
849   assert(DstM && "Null Destination module");
850   assert(SrcM && "Null Source Module");
851
852   // Inherit the target data from the source module if the destination module
853   // doesn't have one already.
854   if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
855     DstM->setDataLayout(SrcM->getDataLayout());
856
857   // Copy the target triple from the source to dest if the dest's is empty.
858   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
859     DstM->setTargetTriple(SrcM->getTargetTriple());
860
861   if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
862       SrcM->getDataLayout() != DstM->getDataLayout())
863     errs() << "WARNING: Linking two modules of different data layouts!\n";
864   if (!SrcM->getTargetTriple().empty() &&
865       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
866     errs() << "WARNING: Linking two modules of different target triples: ";
867     if (!SrcM->getModuleIdentifier().empty())
868       errs() << SrcM->getModuleIdentifier() << ": ";
869     errs() << "'" << SrcM->getTargetTriple() << "' and '" 
870            << DstM->getTargetTriple() << "'\n";
871   }
872
873   // Append the module inline asm string.
874   if (!SrcM->getModuleInlineAsm().empty()) {
875     if (DstM->getModuleInlineAsm().empty())
876       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
877     else
878       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
879                                SrcM->getModuleInlineAsm());
880   }
881
882   // Update the destination module's dependent libraries list with the libraries
883   // from the source module. There's no opportunity for duplicates here as the
884   // Module ensures that duplicate insertions are discarded.
885   for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
886        SI != SE; ++SI)
887     DstM->addLibrary(*SI);
888   
889   // If the source library's module id is in the dependent library list of the
890   // destination library, remove it since that module is now linked in.
891   StringRef ModuleId = SrcM->getModuleIdentifier();
892   if (!ModuleId.empty())
893     DstM->removeLibrary(sys::path::stem(ModuleId));
894
895   
896   // Loop over all of the linked values to compute type mappings.
897   computeTypeMapping();
898
899   // Remap all of the named mdnoes in Src into the DstM module. We do this
900   // after linking GlobalValues so that MDNodes that reference GlobalValues
901   // are properly remapped.
902   linkNamedMDNodes();
903
904   // Insert all of the globals in src into the DstM module... without linking
905   // initializers (which could refer to functions not yet mapped over).
906   for (Module::global_iterator I = SrcM->global_begin(),
907        E = SrcM->global_end(); I != E; ++I)
908     if (linkGlobalProto(I))
909       return true;
910
911   // Link the functions together between the two modules, without doing function
912   // bodies... this just adds external function prototypes to the DstM
913   // function...  We do this so that when we begin processing function bodies,
914   // all of the global values that may be referenced are available in our
915   // ValueMap.
916   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
917     if (linkFunctionProto(I))
918       return true;
919
920   // If there were any aliases, link them now.
921   for (Module::alias_iterator I = SrcM->alias_begin(),
922        E = SrcM->alias_end(); I != E; ++I)
923     if (linkAliasProto(I))
924       return true;
925
926   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
927     linkAppendingVarInit(AppendingVars[i]);
928   
929   // Update the initializers in the DstM module now that all globals that may
930   // be referenced are in DstM.
931   linkGlobalInits();
932
933   // Link in the function bodies that are defined in the source module into
934   // DstM.
935   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
936     if (SF->isDeclaration()) continue;      // No body if function is external.
937     
938     linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
939   }
940
941   // Resolve all uses of aliases with aliasees.
942   linkAliasBodies();
943
944   // Now that all of the types from the source are used, resolve any structs
945   // copied over to the dest that didn't exist there.
946   TypeMap.linkDefinedTypeBodies();
947   
948   return false;
949 }
950
951 //===----------------------------------------------------------------------===//
952 // LinkModules entrypoint.
953 //===----------------------------------------------------------------------===//
954
955 // LinkModules - This function links two modules together, with the resulting
956 // left module modified to be the composite of the two input modules.  If an
957 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
958 // the problem.  Upon failure, the Dest module could be in a modified state, and
959 // shouldn't be relied on to be consistent.
960 bool Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
961   ModuleLinker TheLinker(Dest, Src);
962   if (TheLinker.run()) {
963     if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
964     return true;
965   }
966   
967   return false;
968 }