de443910a95ae21589115135898dfb8fbe396d87
[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 // Specifically, this:
13 //  * Merges global variables between the two modules
14 //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15 //  * Merges functions between two modules
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/ValueSymbolTable.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Transforms/Utils/ValueMapper.h"
32 using namespace llvm;
33
34 // Error - Simple wrapper function to conditionally assign to E and return true.
35 // This just makes error return conditions a little bit simpler...
36 static inline bool Error(std::string *E, const Twine &Message) {
37   if (E) *E = Message.str();
38   return true;
39 }
40
41 // Function: ResolveTypes()
42 //
43 // Description:
44 //  Attempt to link the two specified types together.
45 //
46 // Inputs:
47 //  DestTy - The type to which we wish to resolve.
48 //  SrcTy  - The original type which we want to resolve.
49 //
50 // Outputs:
51 //  DestST - The symbol table in which the new type should be placed.
52 //
53 // Return value:
54 //  true  - There is an error and the types cannot yet be linked.
55 //  false - No errors.
56 //
57 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
58   if (DestTy == SrcTy) return false;       // If already equal, noop
59   assert(DestTy && SrcTy && "Can't handle null types");
60
61   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
62     // Type _is_ in module, just opaque...
63     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
64   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
65     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
66   } else {
67     return true;  // Cannot link types... not-equal and neither is opaque.
68   }
69   return false;
70 }
71
72 /// LinkerTypeMap - This implements a map of types that is stable
73 /// even if types are resolved/refined to other types.  This is not a general
74 /// purpose map, it is specific to the linker's use.
75 namespace {
76 class LinkerTypeMap : public AbstractTypeUser {
77   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
78   TheMapTy TheMap;
79
80   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
82 public:
83   LinkerTypeMap() {}
84   ~LinkerTypeMap() {
85     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
86          E = TheMap.end(); I != E; ++I)
87       I->first->removeAbstractTypeUser(this);
88   }
89
90   /// lookup - Return the value for the specified type or null if it doesn't
91   /// exist.
92   const Type *lookup(const Type *Ty) const {
93     TheMapTy::const_iterator I = TheMap.find(Ty);
94     if (I != TheMap.end()) return I->second;
95     return 0;
96   }
97
98   /// insert - This returns true if the pointer was new to the set, false if it
99   /// was already in the set.
100   bool insert(const Type *Src, const Type *Dst) {
101     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
102       return false;  // Already in map.
103     if (Src->isAbstract())
104       Src->addAbstractTypeUser(this);
105     return true;
106   }
107
108 protected:
109   /// refineAbstractType - The callback method invoked when an abstract type is
110   /// resolved to another type.  An object must override this method to update
111   /// its internal state to reference NewType instead of OldType.
112   ///
113   virtual void refineAbstractType(const DerivedType *OldTy,
114                                   const Type *NewTy) {
115     TheMapTy::iterator I = TheMap.find(OldTy);
116     const Type *DstTy = I->second;
117
118     TheMap.erase(I);
119     if (OldTy->isAbstract())
120       OldTy->removeAbstractTypeUser(this);
121
122     // Don't reinsert into the map if the key is concrete now.
123     if (NewTy->isAbstract())
124       insert(NewTy, DstTy);
125   }
126
127   /// The other case which AbstractTypeUsers must be aware of is when a type
128   /// makes the transition from being abstract (where it has clients on it's
129   /// AbstractTypeUsers list) to concrete (where it does not).  This method
130   /// notifies ATU's when this occurs for a type.
131   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
132     TheMap.erase(AbsTy);
133     AbsTy->removeAbstractTypeUser(this);
134   }
135
136   // for debugging...
137   virtual void dump() const {
138     dbgs() << "AbstractTypeSet!\n";
139   }
140 };
141 }
142
143
144 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
145 // recurses down into derived types, merging the used types if the parent types
146 // are compatible.
147 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
148                                    LinkerTypeMap &Pointers) {
149   if (DstTy == SrcTy) return false;       // If already equal, noop
150
151   // If we found our opaque type, resolve it now!
152   if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
153     return ResolveTypes(DstTy, SrcTy);
154
155   // Two types cannot be resolved together if they are of different primitive
156   // type.  For example, we cannot resolve an int to a float.
157   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
158
159   // If neither type is abstract, then they really are just different types.
160   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
161     return true;
162
163   // Otherwise, resolve the used type used by this derived type...
164   switch (DstTy->getTypeID()) {
165   default:
166     return true;
167   case Type::FunctionTyID: {
168     const FunctionType *DstFT = cast<FunctionType>(DstTy);
169     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
170     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
171         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
172       return true;
173
174     // Use TypeHolder's so recursive resolution won't break us.
175     PATypeHolder ST(SrcFT), DT(DstFT);
176     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
177       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
178       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
179         return true;
180     }
181     return false;
182   }
183   case Type::StructTyID: {
184     const StructType *DstST = cast<StructType>(DstTy);
185     const StructType *SrcST = cast<StructType>(SrcTy);
186     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
187       return true;
188
189     PATypeHolder ST(SrcST), DT(DstST);
190     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
191       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
192       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
193         return true;
194     }
195     return false;
196   }
197   case Type::ArrayTyID: {
198     const ArrayType *DAT = cast<ArrayType>(DstTy);
199     const ArrayType *SAT = cast<ArrayType>(SrcTy);
200     if (DAT->getNumElements() != SAT->getNumElements()) return true;
201     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
202                                   Pointers);
203   }
204   case Type::VectorTyID: {
205     const VectorType *DVT = cast<VectorType>(DstTy);
206     const VectorType *SVT = cast<VectorType>(SrcTy);
207     if (DVT->getNumElements() != SVT->getNumElements()) return true;
208     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
209                                   Pointers);
210   }
211   case Type::PointerTyID: {
212     const PointerType *DstPT = cast<PointerType>(DstTy);
213     const PointerType *SrcPT = cast<PointerType>(SrcTy);
214
215     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
216       return true;
217
218     // If this is a pointer type, check to see if we have already seen it.  If
219     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
220     // an associative container for this search, because the type pointers (keys
221     // in the container) change whenever types get resolved.
222     if (SrcPT->isAbstract())
223       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
224         return ExistingDestTy != DstPT;
225
226     if (DstPT->isAbstract())
227       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
228         return ExistingSrcTy != SrcPT;
229     // Otherwise, add the current pointers to the vector to stop recursion on
230     // this pair.
231     if (DstPT->isAbstract())
232       Pointers.insert(DstPT, SrcPT);
233     if (SrcPT->isAbstract())
234       Pointers.insert(SrcPT, DstPT);
235
236     return RecursiveResolveTypesI(DstPT->getElementType(),
237                                   SrcPT->getElementType(), Pointers);
238   }
239   }
240 }
241
242 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
243   LinkerTypeMap PointerTypes;
244   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
245 }
246
247
248 // LinkTypes - Go through the symbol table of the Src module and see if any
249 // types are named in the src module that are not named in the Dst module.
250 // Make sure there are no type name conflicts.
251 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
252         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
253   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
254
255   // Look for a type plane for Type's...
256   TypeSymbolTable::const_iterator TI = SrcST->begin();
257   TypeSymbolTable::const_iterator TE = SrcST->end();
258   if (TI == TE) return false;  // No named types, do nothing.
259
260   // Some types cannot be resolved immediately because they depend on other
261   // types being resolved to each other first.  This contains a list of types we
262   // are waiting to recheck.
263   std::vector<std::string> DelayedTypesToResolve;
264
265   for ( ; TI != TE; ++TI ) {
266     const std::string &Name = TI->first;
267     const Type *RHS = TI->second;
268
269     // Check to see if this type name is already in the dest module.
270     Type *Entry = DestST->lookup(Name);
271
272     // If the name is just in the source module, bring it over to the dest.
273     if (Entry == 0) {
274       if (!Name.empty())
275         DestST->insert(Name, const_cast<Type*>(RHS));
276     } else if (ResolveTypes(Entry, RHS)) {
277       // They look different, save the types 'till later to resolve.
278       DelayedTypesToResolve.push_back(Name);
279     }
280   }
281
282   // Iteratively resolve types while we can...
283   while (!DelayedTypesToResolve.empty()) {
284     // Loop over all of the types, attempting to resolve them if possible...
285     unsigned OldSize = DelayedTypesToResolve.size();
286
287     // Try direct resolution by name...
288     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
289       const std::string &Name = DelayedTypesToResolve[i];
290       Type *T1 = SrcST->lookup(Name);
291       Type *T2 = DestST->lookup(Name);
292       if (!ResolveTypes(T2, T1)) {
293         // We are making progress!
294         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
295         --i;
296       }
297     }
298
299     // Did we not eliminate any types?
300     if (DelayedTypesToResolve.size() == OldSize) {
301       // Attempt to resolve subelements of types.  This allows us to merge these
302       // two types: { int* } and { opaque* }
303       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
304         const std::string &Name = DelayedTypesToResolve[i];
305         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
306           // We are making progress!
307           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
308
309           // Go back to the main loop, perhaps we can resolve directly by name
310           // now...
311           break;
312         }
313       }
314
315       // If we STILL cannot resolve the types, then there is something wrong.
316       if (DelayedTypesToResolve.size() == OldSize) {
317         // Remove the symbol name from the destination.
318         DelayedTypesToResolve.pop_back();
319       }
320     }
321   }
322
323
324   return false;
325 }
326
327 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
328 /// in the symbol table.  This is good for all clients except for us.  Go
329 /// through the trouble to force this back.
330 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
331   assert(GV->getName() != Name && "Can't force rename to self");
332   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
333
334   // If there is a conflict, rename the conflict.
335   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
336     assert(ConflictGV->hasLocalLinkage() &&
337            "Not conflicting with a static global, should link instead!");
338     GV->takeName(ConflictGV);
339     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
340     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
341   } else {
342     GV->setName(Name);              // Force the name back
343   }
344 }
345
346 /// CopyGVAttributes - copy additional attributes (those not needed to construct
347 /// a GlobalValue) from the SrcGV to the DestGV.
348 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
349   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
350   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
351   DestGV->copyAttributesFrom(SrcGV);
352   DestGV->setAlignment(Alignment);
353 }
354
355 /// GetLinkageResult - This analyzes the two global values and determines what
356 /// the result will look like in the destination module.  In particular, it
357 /// computes the resultant linkage type, computes whether the global in the
358 /// source should be copied over to the destination (replacing the existing
359 /// one), and computes whether this linkage is an error or not. It also performs
360 /// visibility checks: we cannot link together two symbols with different
361 /// visibilities.
362 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
363                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
364                              std::string *Err) {
365   assert((!Dest || !Src->hasLocalLinkage()) &&
366          "If Src has internal linkage, Dest shouldn't be set!");
367   if (!Dest) {
368     // Linking something to nothing.
369     LinkFromSrc = true;
370     LT = Src->getLinkage();
371   } else if (Src->isDeclaration()) {
372     // If Src is external or if both Src & Dest are external..  Just link the
373     // external globals, we aren't adding anything.
374     if (Src->hasDLLImportLinkage()) {
375       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
376       if (Dest->isDeclaration()) {
377         LinkFromSrc = true;
378         LT = Src->getLinkage();
379       }
380     } else if (Dest->hasExternalWeakLinkage()) {
381       // If the Dest is weak, use the source linkage.
382       LinkFromSrc = true;
383       LT = Src->getLinkage();
384     } else {
385       LinkFromSrc = false;
386       LT = Dest->getLinkage();
387     }
388   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
389     // If Dest is external but Src is not:
390     LinkFromSrc = true;
391     LT = Src->getLinkage();
392   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
393     if (Src->getLinkage() != Dest->getLinkage())
394       return Error(Err, "Linking globals named '" + Src->getName() +
395             "': can only link appending global with another appending global!");
396     LinkFromSrc = true; // Special cased.
397     LT = Src->getLinkage();
398   } else if (Src->isWeakForLinker()) {
399     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
400     // or DLL* linkage.
401     if (Dest->hasExternalWeakLinkage() ||
402         Dest->hasAvailableExternallyLinkage() ||
403         (Dest->hasLinkOnceLinkage() &&
404          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
405       LinkFromSrc = true;
406       LT = Src->getLinkage();
407     } else {
408       LinkFromSrc = false;
409       LT = Dest->getLinkage();
410     }
411   } else if (Dest->isWeakForLinker()) {
412     // At this point we know that Src has External* or DLL* linkage.
413     if (Src->hasExternalWeakLinkage()) {
414       LinkFromSrc = false;
415       LT = Dest->getLinkage();
416     } else {
417       LinkFromSrc = true;
418       LT = GlobalValue::ExternalLinkage;
419     }
420   } else {
421     assert((Dest->hasExternalLinkage() ||
422             Dest->hasDLLImportLinkage() ||
423             Dest->hasDLLExportLinkage() ||
424             Dest->hasExternalWeakLinkage()) &&
425            (Src->hasExternalLinkage() ||
426             Src->hasDLLImportLinkage() ||
427             Src->hasDLLExportLinkage() ||
428             Src->hasExternalWeakLinkage()) &&
429            "Unexpected linkage type!");
430     return Error(Err, "Linking globals named '" + Src->getName() +
431                  "': symbol multiply defined!");
432   }
433
434   // Check visibility
435   if (Dest && Src->getVisibility() != Dest->getVisibility())
436     if (!Src->isDeclaration() && !Dest->isDeclaration())
437       return Error(Err, "Linking globals named '" + Src->getName() +
438                    "': symbols have different visibilities!");
439   return false;
440 }
441
442 // Insert all of the named mdnoes in Src into the Dest module.
443 static void LinkNamedMDNodes(Module *Dest, Module *Src,
444                              ValueToValueMapTy &ValueMap) {
445   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
446          E = Src->named_metadata_end(); I != E; ++I) {
447     const NamedMDNode *SrcNMD = I;
448     NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
449     // Add Src elements into Dest node.
450     for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i) 
451       DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
452                                                 ValueMap,
453                                                 true)));
454   }
455 }
456
457 // RequiresUnique - Returns true if the global variable needs to be
458 // unique. I.e., there shouldn't be a new global variable created in the
459 // destination Module, rather the source variable's initializer needs to be
460 // identical to the destination variable's initializer.
461 static bool RequiresUnique(const GlobalVariable *SGV,
462                            const GlobalVariable *DGV) {
463   const StringRef SrcSec(SGV->getSection());
464   const StringRef DstSec(DGV->getSection());
465
466   // The Objective-C __image_info section should be unique.
467   if (SrcSec == DstSec &&
468       (SrcSec.find("__objc_imageinfo") != StringRef::npos ||
469        SrcSec.find("__image_info") != StringRef::npos))
470     return true;
471
472   return false;
473 }
474
475 // LinkGlobals - Loop through the global variables in the src module and merge
476 // them into the dest module.
477 static bool LinkGlobals(Module *Dest, const Module *Src,
478                         ValueToValueMapTy &ValueMap,
479                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
480                         std::string *Err) {
481   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
482
483   // Loop over all of the globals in the src module, mapping them over as we go
484   for (Module::const_global_iterator I = Src->global_begin(),
485        E = Src->global_end(); I != E; ++I) {
486     const GlobalVariable *SGV = I;
487     GlobalValue *DGV = 0;
488
489     GlobalValue *SymTabGV =
490       cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
491
492     // Check to see if the symbol exists in the destination module and needs to
493     // be merged instead of replaced.
494     if (SymTabGV) {
495       const GlobalVariable *GV = dyn_cast<GlobalVariable>(SymTabGV);
496       if (GV && RequiresUnique(SGV, GV)) {
497         // Make sure to remember this mapping.
498         ValueMap[SGV] = SymTabGV;
499         continue;
500       }
501     }
502
503     // Check to see if we may have to link the global with a global, alias, or
504     // function.
505     if (SGV->hasName() && !SGV->hasLocalLinkage())
506       DGV = SymTabGV;
507
508     // If we found a global with the same name in the dest module, but it has
509     // internal linkage, we are really not doing any linkage here.
510     if (DGV && DGV->hasLocalLinkage())
511       DGV = 0;
512
513     // If types don't agree due to opaque types, try to resolve them.
514     if (DGV && DGV->getType() != SGV->getType())
515       RecursiveResolveTypes(SGV->getType(), DGV->getType());
516
517     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
518             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
519            "Global must either be external or have an initializer!");
520
521     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
522     bool LinkFromSrc = false;
523     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
524       return true;
525
526     if (DGV == 0) {
527       // No linking to be performed, simply create an identical version of the
528       // symbol over in the dest module... the initializer will be filled in
529       // later by LinkGlobalInits.
530       GlobalVariable *NewDGV =
531         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
532                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
533                            SGV->getName(), 0, false,
534                            SGV->getType()->getAddressSpace());
535       // Propagate alignment, visibility and section info.
536       CopyGVAttributes(NewDGV, SGV);
537
538       // If the LLVM runtime renamed the global, but it is an externally visible
539       // symbol, DGV must be an existing global with internal linkage.  Rename
540       // it.
541       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
542         ForceRenaming(NewDGV, SGV->getName());
543
544       // Make sure to remember this mapping.
545       ValueMap[SGV] = NewDGV;
546
547       // Keep track that this is an appending variable.
548       if (SGV->hasAppendingLinkage())
549         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
550       continue;
551     }
552
553     // If the visibilities of the symbols disagree and the destination is a
554     // prototype, take the visibility of its input.
555     if (DGV->isDeclaration())
556       DGV->setVisibility(SGV->getVisibility());
557
558     if (DGV->hasAppendingLinkage()) {
559       // No linking is performed yet.  Just insert a new copy of the global, and
560       // keep track of the fact that it is an appending variable in the
561       // AppendingVars map.  The name is cleared out so that no linkage is
562       // performed.
563       GlobalVariable *NewDGV =
564         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
565                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
566                            "", 0, false,
567                            SGV->getType()->getAddressSpace());
568
569       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
570       NewDGV->setAlignment(DGV->getAlignment());
571       // Propagate alignment, section and visibility info.
572       CopyGVAttributes(NewDGV, SGV);
573
574       // Make sure to remember this mapping...
575       ValueMap[SGV] = NewDGV;
576
577       // Keep track that this is an appending variable...
578       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
579       continue;
580     }
581
582     if (LinkFromSrc) {
583       if (isa<GlobalAlias>(DGV))
584         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
585                      "': symbol multiple defined");
586
587       // If the types don't match, and if we are to link from the source, nuke
588       // DGV and create a new one of the appropriate type.  Note that the thing
589       // we are replacing may be a function (if a prototype, weak, etc) or a
590       // global variable.
591       GlobalVariable *NewDGV =
592         new GlobalVariable(*Dest, SGV->getType()->getElementType(), 
593                            SGV->isConstant(), NewLinkage, /*init*/0, 
594                            DGV->getName(), 0, false,
595                            SGV->getType()->getAddressSpace());
596
597       // Propagate alignment, section, and visibility info.
598       CopyGVAttributes(NewDGV, SGV);
599       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 
600                                                               DGV->getType()));
601
602       // DGV will conflict with NewDGV because they both had the same
603       // name. We must erase this now so ForceRenaming doesn't assert
604       // because DGV might not have internal linkage.
605       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
606         Var->eraseFromParent();
607       else
608         cast<Function>(DGV)->eraseFromParent();
609
610       // If the symbol table renamed the global, but it is an externally visible
611       // symbol, DGV must be an existing global with internal linkage.  Rename.
612       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
613         ForceRenaming(NewDGV, SGV->getName());
614
615       // Inherit const as appropriate.
616       NewDGV->setConstant(SGV->isConstant());
617
618       // Make sure to remember this mapping.
619       ValueMap[SGV] = NewDGV;
620       continue;
621     }
622
623     // Not "link from source", keep the one in the DestModule and remap the
624     // input onto it.
625
626     // Special case for const propagation.
627     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
628       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
629         DGVar->setConstant(true);
630
631     // SGV is global, but DGV is alias.
632     if (isa<GlobalAlias>(DGV)) {
633       // The only valid mappings are:
634       // - SGV is external declaration, which is effectively a no-op.
635       // - SGV is weak, when we just need to throw SGV out.
636       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
637         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
638                      "': symbol multiple defined");
639     }
640
641     // Set calculated linkage
642     DGV->setLinkage(NewLinkage);
643
644     // Make sure to remember this mapping...
645     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
646   }
647   return false;
648 }
649
650 static GlobalValue::LinkageTypes
651 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
652   GlobalValue::LinkageTypes SL = SGV->getLinkage();
653   GlobalValue::LinkageTypes DL = DGV->getLinkage();
654   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
655     return GlobalValue::ExternalLinkage;
656   else if (SL == GlobalValue::WeakAnyLinkage ||
657            DL == GlobalValue::WeakAnyLinkage)
658     return GlobalValue::WeakAnyLinkage;
659   else if (SL == GlobalValue::WeakODRLinkage ||
660            DL == GlobalValue::WeakODRLinkage)
661     return GlobalValue::WeakODRLinkage;
662   else if (SL == GlobalValue::InternalLinkage &&
663            DL == GlobalValue::InternalLinkage)
664     return GlobalValue::InternalLinkage;
665   else if (SL == GlobalValue::LinkerPrivateLinkage &&
666            DL == GlobalValue::LinkerPrivateLinkage)
667     return GlobalValue::LinkerPrivateLinkage;
668   else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
669            DL == GlobalValue::LinkerPrivateWeakLinkage)
670     return GlobalValue::LinkerPrivateWeakLinkage;
671   else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
672            DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
673     return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
674   else {
675     assert (SL == GlobalValue::PrivateLinkage &&
676             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
677     return GlobalValue::PrivateLinkage;
678   }
679 }
680
681 // LinkAlias - Loop through the alias in the src module and link them into the
682 // dest module. We're assuming, that all functions/global variables were already
683 // linked in.
684 static bool LinkAlias(Module *Dest, const Module *Src,
685                       ValueToValueMapTy &ValueMap,
686                       std::string *Err) {
687   // Loop over all alias in the src module
688   for (Module::const_alias_iterator I = Src->alias_begin(),
689          E = Src->alias_end(); I != E; ++I) {
690     const GlobalAlias *SGA = I;
691     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
692     GlobalAlias *NewGA = NULL;
693
694     // Globals were already linked, thus we can just query ValueMap for variant
695     // of SAliasee in Dest.
696     ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
697     assert(VMI != ValueMap.end() && "Aliasee not linked");
698     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
699     GlobalValue* DGV = NULL;
700
701     // Try to find something 'similar' to SGA in destination module.
702     if (!DGV && !SGA->hasLocalLinkage()) {
703       DGV = Dest->getNamedAlias(SGA->getName());
704
705       // If types don't agree due to opaque types, try to resolve them.
706       if (DGV && DGV->getType() != SGA->getType())
707         RecursiveResolveTypes(SGA->getType(), DGV->getType());
708     }
709
710     if (!DGV && !SGA->hasLocalLinkage()) {
711       DGV = Dest->getGlobalVariable(SGA->getName());
712
713       // If types don't agree due to opaque types, try to resolve them.
714       if (DGV && DGV->getType() != SGA->getType())
715         RecursiveResolveTypes(SGA->getType(), DGV->getType());
716     }
717
718     if (!DGV && !SGA->hasLocalLinkage()) {
719       DGV = Dest->getFunction(SGA->getName());
720
721       // If types don't agree due to opaque types, try to resolve them.
722       if (DGV && DGV->getType() != SGA->getType())
723         RecursiveResolveTypes(SGA->getType(), DGV->getType());
724     }
725
726     // No linking to be performed on internal stuff.
727     if (DGV && DGV->hasLocalLinkage())
728       DGV = NULL;
729
730     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
731       // Types are known to be the same, check whether aliasees equal. As
732       // globals are already linked we just need query ValueMap to find the
733       // mapping.
734       if (DAliasee == DGA->getAliasedGlobal()) {
735         // This is just two copies of the same alias. Propagate linkage, if
736         // necessary.
737         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
738
739         NewGA = DGA;
740         // Proceed to 'common' steps
741       } else
742         return Error(Err, "Alias Collision on '"  + SGA->getName()+
743                      "': aliases have different aliasees");
744     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
745       // The only allowed way is to link alias with external declaration or weak
746       // symbol..
747       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
748         // But only if aliasee is global too...
749         if (!isa<GlobalVariable>(DAliasee))
750           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
751                        "': aliasee is not global variable");
752
753         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
754                                 SGA->getName(), DAliasee, Dest);
755         CopyGVAttributes(NewGA, SGA);
756
757         // Any uses of DGV need to change to NewGA, with cast, if needed.
758         if (SGA->getType() != DGVar->getType())
759           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
760                                                              DGVar->getType()));
761         else
762           DGVar->replaceAllUsesWith(NewGA);
763
764         // DGVar will conflict with NewGA because they both had the same
765         // name. We must erase this now so ForceRenaming doesn't assert
766         // because DGV might not have internal linkage.
767         DGVar->eraseFromParent();
768
769         // Proceed to 'common' steps
770       } else
771         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
772                      "': symbol multiple defined");
773     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
774       // The only allowed way is to link alias with external declaration or weak
775       // symbol...
776       if (DF->isDeclaration() || DF->isWeakForLinker()) {
777         // But only if aliasee is function too...
778         if (!isa<Function>(DAliasee))
779           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
780                        "': aliasee is not function");
781
782         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
783                                 SGA->getName(), DAliasee, Dest);
784         CopyGVAttributes(NewGA, SGA);
785
786         // Any uses of DF need to change to NewGA, with cast, if needed.
787         if (SGA->getType() != DF->getType())
788           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
789                                                           DF->getType()));
790         else
791           DF->replaceAllUsesWith(NewGA);
792
793         // DF will conflict with NewGA because they both had the same
794         // name. We must erase this now so ForceRenaming doesn't assert
795         // because DF might not have internal linkage.
796         DF->eraseFromParent();
797
798         // Proceed to 'common' steps
799       } else
800         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
801                      "': symbol multiple defined");
802     } else {
803       // No linking to be performed, simply create an identical version of the
804       // alias over in the dest module...
805       Constant *Aliasee = DAliasee;
806       // Fixup aliases to bitcasts.  Note that aliases to GEPs are still broken
807       // by this, but aliases to GEPs are broken to a lot of other things, so
808       // it's less important.
809       if (SGA->getType() != DAliasee->getType())
810         Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
811       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
812                               SGA->getName(), Aliasee, Dest);
813       CopyGVAttributes(NewGA, SGA);
814
815       // Proceed to 'common' steps
816     }
817
818     assert(NewGA && "No alias was created in destination module!");
819
820     // If the symbol table renamed the alias, but it is an externally visible
821     // symbol, DGA must be an global value with internal linkage. Rename it.
822     if (NewGA->getName() != SGA->getName() &&
823         !NewGA->hasLocalLinkage())
824       ForceRenaming(NewGA, SGA->getName());
825
826     // Remember this mapping so uses in the source module get remapped
827     // later by MapValue.
828     ValueMap[SGA] = NewGA;
829   }
830
831   return false;
832 }
833
834
835 // LinkGlobalInits - Update the initializers in the Dest module now that all
836 // globals that may be referenced are in Dest.
837 static bool LinkGlobalInits(Module *Dest, const Module *Src,
838                             ValueToValueMapTy &ValueMap,
839                             std::string *Err) {
840   // Loop over all of the globals in the src module, mapping them over as we go
841   for (Module::const_global_iterator I = Src->global_begin(),
842        E = Src->global_end(); I != E; ++I) {
843     const GlobalVariable *SGV = I;
844
845     if (SGV->hasInitializer()) {      // Only process initialized GV's
846       // Figure out what the initializer looks like in the dest module...
847       Constant *SInit =
848         cast<Constant>(MapValue(SGV->getInitializer(), ValueMap, true));
849       // Grab destination global variable or alias.
850       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
851
852       // If dest is a global variable, check that initializers match.
853       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
854         if (DGVar->hasInitializer()) {
855           if (SGV->hasExternalLinkage() || RequiresUnique(SGV, DGVar)) {
856             if (DGVar->getInitializer() != SInit)
857               return Error(Err, "Global Variable Collision on '" +
858                            SGV->getName() +
859                            "': global variables have different initializers");
860           } else if (DGVar->isWeakForLinker()) {
861             // Nothing is required, mapped values will take the new global
862             // automatically.
863           } else if (SGV->isWeakForLinker()) {
864             // Nothing is required, mapped values will take the new global
865             // automatically.
866           } else if (DGVar->hasAppendingLinkage()) {
867             llvm_unreachable("Appending linkage unimplemented!");
868           } else {
869             llvm_unreachable("Unknown linkage!");
870           }
871         } else {
872           // Copy the initializer over now...
873           DGVar->setInitializer(SInit);
874         }
875       } else {
876         // Destination is alias, the only valid situation is when source is
877         // weak. Also, note, that we already checked linkage in LinkGlobals(),
878         // thus we assert here.
879         // FIXME: Should we weaken this assumption, 'dereference' alias and
880         // check for initializer of aliasee?
881         assert(SGV->isWeakForLinker());
882       }
883     }
884   }
885   return false;
886 }
887
888 // LinkFunctionProtos - Link the functions together between the two modules,
889 // without doing function bodies... this just adds external function prototypes
890 // to the Dest function...
891 //
892 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
893                                ValueToValueMapTy &ValueMap,
894                                std::string *Err) {
895   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
896
897   // Loop over all of the functions in the src module, mapping them over
898   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
899     const Function *SF = I;   // SrcFunction
900     GlobalValue *DGV = 0;
901
902     // Check to see if may have to link the function with the global, alias or
903     // function.
904     if (SF->hasName() && !SF->hasLocalLinkage())
905       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
906
907     // If we found a global with the same name in the dest module, but it has
908     // internal linkage, we are really not doing any linkage here.
909     if (DGV && DGV->hasLocalLinkage())
910       DGV = 0;
911
912     // If types don't agree due to opaque types, try to resolve them.
913     if (DGV && DGV->getType() != SF->getType())
914       RecursiveResolveTypes(SF->getType(), DGV->getType());
915
916     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
917     bool LinkFromSrc = false;
918     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
919       return true;
920
921     // If there is no linkage to be performed, just bring over SF without
922     // modifying it.
923     if (DGV == 0) {
924       // Function does not already exist, simply insert an function signature
925       // identical to SF into the dest module.
926       Function *NewDF = Function::Create(SF->getFunctionType(),
927                                          SF->getLinkage(),
928                                          SF->getName(), Dest);
929       CopyGVAttributes(NewDF, SF);
930
931       // If the LLVM runtime renamed the function, but it is an externally
932       // visible symbol, DF must be an existing function with internal linkage.
933       // Rename it.
934       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
935         ForceRenaming(NewDF, SF->getName());
936
937       // ... and remember this mapping...
938       ValueMap[SF] = NewDF;
939       continue;
940     }
941
942     // If the visibilities of the symbols disagree and the destination is a
943     // prototype, take the visibility of its input.
944     if (DGV->isDeclaration())
945       DGV->setVisibility(SF->getVisibility());
946
947     if (LinkFromSrc) {
948       if (isa<GlobalAlias>(DGV))
949         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
950                      "': symbol multiple defined");
951
952       // We have a definition of the same name but different type in the
953       // source module. Copy the prototype to the destination and replace
954       // uses of the destination's prototype with the new prototype.
955       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
956                                          SF->getName(), Dest);
957       CopyGVAttributes(NewDF, SF);
958
959       // Any uses of DF need to change to NewDF, with cast
960       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, 
961                                                               DGV->getType()));
962
963       // DF will conflict with NewDF because they both had the same. We must
964       // erase this now so ForceRenaming doesn't assert because DF might
965       // not have internal linkage.
966       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
967         Var->eraseFromParent();
968       else
969         cast<Function>(DGV)->eraseFromParent();
970
971       // If the symbol table renamed the function, but it is an externally
972       // visible symbol, DF must be an existing function with internal
973       // linkage.  Rename it.
974       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
975         ForceRenaming(NewDF, SF->getName());
976
977       // Remember this mapping so uses in the source module get remapped
978       // later by MapValue.
979       ValueMap[SF] = NewDF;
980       continue;
981     }
982
983     // Not "link from source", keep the one in the DestModule and remap the
984     // input onto it.
985
986     if (isa<GlobalAlias>(DGV)) {
987       // The only valid mappings are:
988       // - SF is external declaration, which is effectively a no-op.
989       // - SF is weak, when we just need to throw SF out.
990       if (!SF->isDeclaration() && !SF->isWeakForLinker())
991         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
992                      "': symbol multiple defined");
993     }
994
995     // Set calculated linkage
996     DGV->setLinkage(NewLinkage);
997
998     // Make sure to remember this mapping.
999     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1000   }
1001   return false;
1002 }
1003
1004 // LinkFunctionBody - Copy the source function over into the dest function and
1005 // fix up references to values.  At this point we know that Dest is an external
1006 // function, and that Src is not.
1007 static bool LinkFunctionBody(Function *Dest, Function *Src,
1008                              ValueToValueMapTy &ValueMap,
1009                              std::string *Err) {
1010   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1011
1012   // Go through and convert function arguments over, remembering the mapping.
1013   Function::arg_iterator DI = Dest->arg_begin();
1014   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1015        I != E; ++I, ++DI) {
1016     DI->setName(I->getName());  // Copy the name information over...
1017
1018     // Add a mapping to our local map
1019     ValueMap[I] = DI;
1020   }
1021
1022   // Splice the body of the source function into the dest function.
1023   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1024
1025   // At this point, all of the instructions and values of the function are now
1026   // copied over.  The only problem is that they are still referencing values in
1027   // the Source function as operands.  Loop through all of the operands of the
1028   // functions and patch them up to point to the local versions...
1029   //
1030   // This is the same as RemapInstruction, except that it avoids remapping
1031   // instruction and basic block operands.
1032   //
1033   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1034     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1035       // Remap operands.
1036       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1037            OI != OE; ++OI)
1038         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1039           *OI = MapValue(*OI, ValueMap, true);
1040
1041       // Remap attached metadata.
1042       SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1043       I->getAllMetadata(MDs);
1044       for (SmallVectorImpl<std::pair<unsigned, MDNode *> >::iterator
1045            MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI) {
1046         Value *Old = MI->second;
1047         if (!isa<Instruction>(Old) && !isa<BasicBlock>(Old)) {
1048           Value *New = MapValue(Old, ValueMap, true);
1049           if (New != Old) 
1050             I->setMetadata(MI->first, cast<MDNode>(New));
1051         }
1052       }
1053     }
1054
1055   // There is no need to map the arguments anymore.
1056   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1057        I != E; ++I)
1058     ValueMap.erase(I);
1059
1060   return false;
1061 }
1062
1063
1064 // LinkFunctionBodies - Link in the function bodies that are defined in the
1065 // source module into the DestModule.  This consists basically of copying the
1066 // function over and fixing up references to values.
1067 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1068                                ValueToValueMapTy &ValueMap,
1069                                std::string *Err) {
1070
1071   // Loop over all of the functions in the src module, mapping them over as we
1072   // go
1073   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1074     if (!SF->isDeclaration()) {               // No body if function is external
1075       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1076
1077       // DF not external SF external?
1078       if (DF && DF->isDeclaration())
1079         // Only provide the function body if there isn't one already.
1080         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1081           return true;
1082     }
1083   }
1084   return false;
1085 }
1086
1087 // LinkAppendingVars - If there were any appending global variables, link them
1088 // together now.  Return true on error.
1089 static bool LinkAppendingVars(Module *M,
1090                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1091                               std::string *ErrorMsg) {
1092   if (AppendingVars.empty()) return false; // Nothing to do.
1093
1094   // Loop over the multimap of appending vars, processing any variables with the
1095   // same name, forming a new appending global variable with both of the
1096   // initializers merged together, then rewrite references to the old variables
1097   // and delete them.
1098   std::vector<Constant*> Inits;
1099   while (AppendingVars.size() > 1) {
1100     // Get the first two elements in the map...
1101     std::multimap<std::string,
1102       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1103
1104     // If the first two elements are for different names, there is no pair...
1105     // Otherwise there is a pair, so link them together...
1106     if (First->first == Second->first) {
1107       GlobalVariable *G1 = First->second, *G2 = Second->second;
1108       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1109       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1110
1111       // Check to see that they two arrays agree on type...
1112       if (T1->getElementType() != T2->getElementType())
1113         return Error(ErrorMsg,
1114          "Appending variables with different element types need to be linked!");
1115       if (G1->isConstant() != G2->isConstant())
1116         return Error(ErrorMsg,
1117                      "Appending variables linked with different const'ness!");
1118
1119       if (G1->getAlignment() != G2->getAlignment())
1120         return Error(ErrorMsg,
1121          "Appending variables with different alignment need to be linked!");
1122
1123       if (G1->getVisibility() != G2->getVisibility())
1124         return Error(ErrorMsg,
1125          "Appending variables with different visibility need to be linked!");
1126
1127       if (G1->getSection() != G2->getSection())
1128         return Error(ErrorMsg,
1129          "Appending variables with different section name need to be linked!");
1130
1131       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1132       ArrayType *NewType = ArrayType::get(T1->getElementType(), 
1133                                                          NewSize);
1134
1135       G1->setName("");   // Clear G1's name in case of a conflict!
1136
1137       // Create the new global variable...
1138       GlobalVariable *NG =
1139         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1140                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1141                            G1->getType()->getAddressSpace());
1142
1143       // Propagate alignment, visibility and section info.
1144       CopyGVAttributes(NG, G1);
1145
1146       // Merge the initializer...
1147       Inits.reserve(NewSize);
1148       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1149         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1150           Inits.push_back(I->getOperand(i));
1151       } else {
1152         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1153         Constant *CV = Constant::getNullValue(T1->getElementType());
1154         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1155           Inits.push_back(CV);
1156       }
1157       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1158         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1159           Inits.push_back(I->getOperand(i));
1160       } else {
1161         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1162         Constant *CV = Constant::getNullValue(T2->getElementType());
1163         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1164           Inits.push_back(CV);
1165       }
1166       NG->setInitializer(ConstantArray::get(NewType, Inits));
1167       Inits.clear();
1168
1169       // Replace any uses of the two global variables with uses of the new
1170       // global...
1171
1172       // FIXME: This should rewrite simple/straight-forward uses such as
1173       // getelementptr instructions to not use the Cast!
1174       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1175                              G1->getType()));
1176       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 
1177                              G2->getType()));
1178
1179       // Remove the two globals from the module now...
1180       M->getGlobalList().erase(G1);
1181       M->getGlobalList().erase(G2);
1182
1183       // Put the new global into the AppendingVars map so that we can handle
1184       // linking of more than two vars...
1185       Second->second = NG;
1186     }
1187     AppendingVars.erase(First);
1188   }
1189
1190   return false;
1191 }
1192
1193 static bool ResolveAliases(Module *Dest) {
1194   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1195        I != E; ++I)
1196     // We can't sue resolveGlobalAlias here because we need to preserve
1197     // bitcasts and GEPs.
1198     if (const Constant *C = I->getAliasee()) {
1199       while (dyn_cast<GlobalAlias>(C))
1200         C = cast<GlobalAlias>(C)->getAliasee();
1201       const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1202       if (C != I && !(GV && GV->isDeclaration()))
1203         I->replaceAllUsesWith(const_cast<Constant*>(C));
1204     }
1205
1206   return false;
1207 }
1208
1209 // LinkModules - This function links two modules together, with the resulting
1210 // left module modified to be the composite of the two input modules.  If an
1211 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1212 // the problem.  Upon failure, the Dest module could be in a modified state, and
1213 // shouldn't be relied on to be consistent.
1214 bool
1215 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1216   assert(Dest != 0 && "Invalid Destination module");
1217   assert(Src  != 0 && "Invalid Source Module");
1218
1219   if (Dest->getDataLayout().empty()) {
1220     if (!Src->getDataLayout().empty()) {
1221       Dest->setDataLayout(Src->getDataLayout());
1222     } else {
1223       std::string DataLayout;
1224
1225       if (Dest->getEndianness() == Module::AnyEndianness) {
1226         if (Src->getEndianness() == Module::BigEndian)
1227           DataLayout.append("E");
1228         else if (Src->getEndianness() == Module::LittleEndian)
1229           DataLayout.append("e");
1230       }
1231
1232       if (Dest->getPointerSize() == Module::AnyPointerSize) {
1233         if (Src->getPointerSize() == Module::Pointer64)
1234           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1235         else if (Src->getPointerSize() == Module::Pointer32)
1236           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1237       }
1238       Dest->setDataLayout(DataLayout);
1239     }
1240   }
1241
1242   // Copy the target triple from the source to dest if the dest's is empty.
1243   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1244     Dest->setTargetTriple(Src->getTargetTriple());
1245
1246   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1247       Src->getDataLayout() != Dest->getDataLayout())
1248     errs() << "WARNING: Linking two modules of different data layouts!\n";
1249   if (!Src->getTargetTriple().empty() &&
1250       Dest->getTargetTriple() != Src->getTargetTriple())
1251     errs() << "WARNING: Linking two modules of different target triples!\n";
1252
1253   // Append the module inline asm string.
1254   if (!Src->getModuleInlineAsm().empty()) {
1255     if (Dest->getModuleInlineAsm().empty())
1256       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1257     else
1258       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1259                                Src->getModuleInlineAsm());
1260   }
1261
1262   // Update the destination module's dependent libraries list with the libraries
1263   // from the source module. There's no opportunity for duplicates here as the
1264   // Module ensures that duplicate insertions are discarded.
1265   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1266        SI != SE; ++SI)
1267     Dest->addLibrary(*SI);
1268
1269   // LinkTypes - Go through the symbol table of the Src module and see if any
1270   // types are named in the src module that are not named in the Dst module.
1271   // Make sure there are no type name conflicts.
1272   if (LinkTypes(Dest, Src, ErrorMsg))
1273     return true;
1274
1275   // ValueMap - Mapping of values from what they used to be in Src, to what they
1276   // are now in Dest.  ValueToValueMapTy is a ValueMap, which involves some
1277   // overhead due to the use of Value handles which the Linker doesn't actually
1278   // need, but this allows us to reuse the ValueMapper code.
1279   ValueToValueMapTy ValueMap;
1280
1281   // AppendingVars - Keep track of global variables in the destination module
1282   // with appending linkage.  After the module is linked together, they are
1283   // appended and the module is rewritten.
1284   std::multimap<std::string, GlobalVariable *> AppendingVars;
1285   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1286        I != E; ++I) {
1287     // Add all of the appending globals already in the Dest module to
1288     // AppendingVars.
1289     if (I->hasAppendingLinkage())
1290       AppendingVars.insert(std::make_pair(I->getName(), I));
1291   }
1292
1293   // Insert all of the globals in src into the Dest module... without linking
1294   // initializers (which could refer to functions not yet mapped over).
1295   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1296     return true;
1297
1298   // Link the functions together between the two modules, without doing function
1299   // bodies... this just adds external function prototypes to the Dest
1300   // function...  We do this so that when we begin processing function bodies,
1301   // all of the global values that may be referenced are available in our
1302   // ValueMap.
1303   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1304     return true;
1305
1306   // If there were any alias, link them now. We really need to do this now,
1307   // because all of the aliases that may be referenced need to be available in
1308   // ValueMap
1309   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1310
1311   // Update the initializers in the Dest module now that all globals that may
1312   // be referenced are in Dest.
1313   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1314
1315   // Link in the function bodies that are defined in the source module into the
1316   // DestModule.  This consists basically of copying the function over and
1317   // fixing up references to values.
1318   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1319
1320   // If there were any appending global variables, link them together now.
1321   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1322
1323   // Resolve all uses of aliases with aliasees
1324   if (ResolveAliases(Dest)) return true;
1325
1326   // Remap all of the named mdnoes in Src into the Dest module. We do this
1327   // after linking GlobalValues so that MDNodes that reference GlobalValues
1328   // are properly remapped.
1329   LinkNamedMDNodes(Dest, Src, ValueMap);
1330
1331   // If the source library's module id is in the dependent library list of the
1332   // destination library, remove it since that module is now linked in.
1333   sys::Path modId;
1334   modId.set(Src->getModuleIdentifier());
1335   if (!modId.isEmpty())
1336     Dest->removeLibrary(modId.getBasename());
1337
1338   return false;
1339 }
1340
1341 // vim: sw=2