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