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