The process of linking types can cause their addresses to become invalid. For this...
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
2 //
3 // This file implements the LLVM module linker.
4 //
5 // Specifically, this:
6 //  * Merges global variables between the two modules
7 //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
8 //  * Merges functions between two modules
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Module.h"
14 #include "llvm/SymbolTable.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/iOther.h"
17 #include "llvm/Constants.h"
18
19 // Error - Simple wrapper function to conditionally assign to E and return true.
20 // This just makes error return conditions a little bit simpler...
21 //
22 static inline bool Error(std::string *E, const std::string &Message) {
23   if (E) *E = Message;
24   return true;
25 }
26
27 // ResolveTypes - Attempt to link the two specified types together.  Return true
28 // if there is an error and they cannot yet be linked.
29 //
30 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
31                          SymbolTable *DestST, const std::string &Name) {
32   if (DestTy == SrcTy) return false;       // If already equal, noop
33
34   // Does the type already exist in the module?
35   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
36     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
37       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
38     } else {
39       return true;  // Cannot link types... neither is opaque and not-equal
40     }
41   } else {                       // Type not in dest module.  Add it now.
42     if (DestTy)                  // Type _is_ in module, just opaque...
43       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
44                            ->refineAbstractTypeTo(SrcTy);
45     else
46       DestST->insert(Name, const_cast<Type*>(SrcTy));
47   }
48   return false;
49 }
50
51 static const FunctionType *getFT(const PATypeHolder &TH) {
52   return cast<FunctionType>(TH.get());
53 }
54 static const StructType *getsT(const PATypeHolder &TH) {
55   return cast<StructType>(TH.get());
56 }
57
58 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
59 // recurses down into derived types, merging the used types if the parent types
60 // are compatible.
61 //
62 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
63                                   const PATypeHolder &SrcTy,
64                                   SymbolTable *DestST, const std::string &Name){
65   const Type *SrcTyT = SrcTy.get();
66   const Type *DestTyT = DestTy.get();
67   if (DestTyT == SrcTyT) return false;       // If already equal, noop
68   
69   // If we found our opaque type, resolve it now!
70   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
71     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
72   
73   // Two types cannot be resolved together if they are of different primitive
74   // type.  For example, we cannot resolve an int to a float.
75   if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
76
77   // Otherwise, resolve the used type used by this derived type...
78   switch (DestTyT->getPrimitiveID()) {
79   case Type::FunctionTyID: {
80     if (cast<FunctionType>(DestTyT)->isVarArg() !=
81         cast<FunctionType>(SrcTyT)->isVarArg())
82       return true;
83     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
84       if (RecursiveResolveTypes(getFT(DestTy)->getContainedType(i),
85                                 getFT(SrcTy)->getContainedType(i), DestST,Name))
86         return true;
87     return false;
88   }
89   case Type::StructTyID: {
90     if (getST(DestTy)->getNumContainedTypes() != 
91         getST(SrcTy)->getNumContainedTypes()) return 1;
92     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
93       if (RecursiveResolveTypes(getST(DestTy)->getContainedType(i),
94                                 getST(SrcTy)->getContainedType(i), DestST,Name))
95         return true;
96     return false;
97   }
98   case Type::ArrayTyID: {
99     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
100     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
101     if (DAT->getNumElements() != SAT->getNumElements()) return true;
102     return RecursiveResolveTypes(DAT->getElementType(), SAT->getElementType(),
103                                  DestST, Name);
104   }
105   case Type::PointerTyID:
106     return RecursiveResolveTypes(
107                               cast<PointerType>(DestTy.get())->getElementType(),
108                               cast<PointerType>(SrcTy.get())->getElementType(),
109                                  DestST, Name);
110   default: assert(0 && "Unexpected type!"); return true;
111   }  
112 }
113
114
115 // LinkTypes - Go through the symbol table of the Src module and see if any
116 // types are named in the src module that are not named in the Dst module.
117 // Make sure there are no type name conflicts.
118 //
119 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
120   SymbolTable       *DestST = &Dest->getSymbolTable();
121   const SymbolTable *SrcST  = &Src->getSymbolTable();
122
123   // Look for a type plane for Type's...
124   SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
125   if (PI == SrcST->end()) return false;  // No named types, do nothing.
126
127   // Some types cannot be resolved immediately becuse they depend on other types
128   // being resolved to each other first.  This contains a list of types we are
129   // waiting to recheck.
130   std::vector<std::string> DelayedTypesToResolve;
131
132   const SymbolTable::VarMap &VM = PI->second;
133   for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
134        I != E; ++I) {
135     const std::string &Name = I->first;
136     Type *RHS = cast<Type>(I->second);
137
138     // Check to see if this type name is already in the dest module...
139     Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
140
141     if (ResolveTypes(Entry, RHS, DestST, Name)) {
142       // They look different, save the types 'till later to resolve.
143       DelayedTypesToResolve.push_back(Name);
144     }
145   }
146
147   // Iteratively resolve types while we can...
148   while (!DelayedTypesToResolve.empty()) {
149     // Loop over all of the types, attempting to resolve them if possible...
150     unsigned OldSize = DelayedTypesToResolve.size();
151
152     // Try direct resolution by name...
153     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
154       const std::string &Name = DelayedTypesToResolve[i];
155       Type *T1 = cast<Type>(VM.find(Name)->second);
156       Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
157       if (!ResolveTypes(T2, T1, DestST, Name)) {
158         // We are making progress!
159         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
160         --i;
161       }
162     }
163
164     // Did we not eliminate any types?
165     if (DelayedTypesToResolve.size() == OldSize) {
166       // Attempt to resolve subelements of types.  This allows us to merge these
167       // two types: { int* } and { opaque* }
168       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
169         const std::string &Name = DelayedTypesToResolve[i];
170         PATypeHolder T1(cast<Type>(VM.find(Name)->second));
171         PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
172
173         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
174           // We are making progress!
175           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
176           
177           // Go back to the main loop, perhaps we can resolve directly by name
178           // now...
179           break;
180         }
181       }
182
183       // If we STILL cannot resolve the types, then there is something wrong.
184       // Report the error.
185       if (DelayedTypesToResolve.size() == OldSize) {
186         // Build up an error message of all of the mismatched types.
187         std::string ErrorMessage;
188         for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
189           const std::string &Name = DelayedTypesToResolve[i];
190           const Type *T1 = cast<Type>(VM.find(Name)->second);
191           const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
192           ErrorMessage += "  Type named '" + Name + 
193                           "' conflicts.\n    Src='" + T1->getDescription() +
194                           "'.\n   Dest='" + T2->getDescription() + "'\n";
195         }
196         return Error(Err, "Type conflict between types in modules:\n" +
197                      ErrorMessage);
198       }
199     }
200   }
201
202
203   return false;
204 }
205
206 static void PrintMap(const std::map<const Value*, Value*> &M) {
207   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
208        I != E; ++I) {
209     std::cerr << " Fr: " << (void*)I->first << " ";
210     I->first->dump();
211     std::cerr << " To: " << (void*)I->second << " ";
212     I->second->dump();
213     std::cerr << "\n";
214   }
215 }
216
217
218 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
219 // module to another.  This is somewhat sophisticated in that it can
220 // automatically handle constant references correctly as well...
221 //
222 static Value *RemapOperand(const Value *In,
223                            std::map<const Value*, Value*> &LocalMap,
224                            std::map<const Value*, Value*> *GlobalMap) {
225   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
226   if (I != LocalMap.end()) return I->second;
227
228   if (GlobalMap) {
229     I = GlobalMap->find(In);
230     if (I != GlobalMap->end()) return I->second;
231   }
232
233   // Check to see if it's a constant that we are interesting in transforming...
234   if (const Constant *CPV = dyn_cast<Constant>(In)) {
235     if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
236       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
237
238     Constant *Result = 0;
239
240     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
241       const std::vector<Use> &Ops = CPA->getValues();
242       std::vector<Constant*> Operands(Ops.size());
243       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
244         Operands[i] = 
245           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
246       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
247     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
248       const std::vector<Use> &Ops = CPS->getValues();
249       std::vector<Constant*> Operands(Ops.size());
250       for (unsigned i = 0; i < Ops.size(); ++i)
251         Operands[i] = 
252           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
253       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
254     } else if (isa<ConstantPointerNull>(CPV)) {
255       Result = const_cast<Constant*>(CPV);
256     } else if (const ConstantPointerRef *CPR =
257                       dyn_cast<ConstantPointerRef>(CPV)) {
258       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
259       Result = ConstantPointerRef::get(cast<GlobalValue>(V));
260     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
261       if (CE->getOpcode() == Instruction::GetElementPtr) {
262         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
263         std::vector<Constant*> Indices;
264         Indices.reserve(CE->getNumOperands()-1);
265         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
266           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
267                                                         LocalMap, GlobalMap)));
268
269         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
270       } else if (CE->getNumOperands() == 1) {
271         // Cast instruction
272         assert(CE->getOpcode() == Instruction::Cast);
273         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
274         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
275       } else if (CE->getNumOperands() == 2) {
276         // Binary operator...
277         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
278         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
279
280         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
281                                    cast<Constant>(V2));        
282       } else {
283         assert(0 && "Unknown constant expr type!");
284       }
285
286     } else {
287       assert(0 && "Unknown type of derived type constant value!");
288     }
289
290     // Cache the mapping in our local map structure...
291     if (GlobalMap)
292       GlobalMap->insert(std::make_pair(In, Result));
293     else
294       LocalMap.insert(std::make_pair(In, Result));
295     return Result;
296   }
297
298   std::cerr << "XXX LocalMap: \n";
299   PrintMap(LocalMap);
300
301   if (GlobalMap) {
302     std::cerr << "XXX GlobalMap: \n";
303     PrintMap(*GlobalMap);
304   }
305
306   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
307   assert(0 && "Couldn't remap value!");
308   return 0;
309 }
310
311
312 // LinkGlobals - Loop through the global variables in the src module and merge
313 // them into the dest module.
314 //
315 static bool LinkGlobals(Module *Dest, const Module *Src,
316                         std::map<const Value*, Value*> &ValueMap,
317                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
318                         std::string *Err) {
319   // We will need a module level symbol table if the src module has a module
320   // level symbol table...
321   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
322   
323   // Loop over all of the globals in the src module, mapping them over as we go
324   //
325   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
326     const GlobalVariable *SGV = I;
327     GlobalVariable *DGV = 0;
328     if (SGV->hasName()) {
329       // A same named thing is a global variable, because the only two things
330       // that may be in a module level symbol table are Global Vars and
331       // Functions, and they both have distinct, nonoverlapping, possible types.
332       // 
333       DGV = cast_or_null<GlobalVariable>(ST->lookup(SGV->getType(),
334                                                     SGV->getName()));
335     }
336
337     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
338            "Global must either be external or have an initializer!");
339
340     bool SGExtern = SGV->isExternal();
341     bool DGExtern = DGV ? DGV->isExternal() : false;
342
343     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
344       // No linking to be performed, simply create an identical version of the
345       // symbol over in the dest module... the initializer will be filled in
346       // later by LinkGlobalInits...
347       //
348       GlobalVariable *NewDGV =
349         new GlobalVariable(SGV->getType()->getElementType(),
350                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
351                            SGV->getName(), Dest);
352
353       // If the LLVM runtime renamed the global, but it is an externally visible
354       // symbol, DGV must be an existing global with internal linkage.  Rename
355       // it.
356       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
357         assert(DGV && DGV->getName() == SGV->getName() &&
358                DGV->hasInternalLinkage());
359         DGV->setName("");
360         NewDGV->setName(SGV->getName());  // Force the name back
361         DGV->setName(SGV->getName());     // This will cause a renaming
362         assert(NewDGV->getName() == SGV->getName() &&
363                DGV->getName() != SGV->getName());
364       }
365
366       // Make sure to remember this mapping...
367       ValueMap.insert(std::make_pair(SGV, NewDGV));
368       if (SGV->hasAppendingLinkage())
369         // Keep track that this is an appending variable...
370         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
371
372     } else if (SGV->isExternal()) {
373       // If SGV is external or if both SGV & DGV are external..  Just link the
374       // external globals, we aren't adding anything.
375       ValueMap.insert(std::make_pair(SGV, DGV));
376
377     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
378       ValueMap.insert(std::make_pair(SGV, DGV));
379       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
380     } else if (SGV->getLinkage() != DGV->getLinkage()) {
381       return Error(Err, "Global variables named '" + SGV->getName() +
382                    "' have different linkage specifiers!");
383     } else if (SGV->hasExternalLinkage()) {
384       // Allow linking two exactly identical external global variables...
385       if (SGV->isConstant() != DGV->isConstant() ||
386           SGV->getInitializer() != DGV->getInitializer())
387         return Error(Err, "Global Variable Collision on '" + 
388                      SGV->getType()->getDescription() + " %" + SGV->getName() +
389                      "' - Global variables differ in const'ness");
390       ValueMap.insert(std::make_pair(SGV, DGV));
391     } else if (SGV->hasLinkOnceLinkage()) {
392       // If the global variable has a name, and that name is already in use in
393       // the Dest module, make sure that the name is a compatible global
394       // variable...
395       //
396       // Check to see if the two GV's have the same Const'ness...
397       if (SGV->isConstant() != DGV->isConstant())
398         return Error(Err, "Global Variable Collision on '" + 
399                      SGV->getType()->getDescription() + " %" + SGV->getName() +
400                      "' - Global variables differ in const'ness");
401
402       // Okay, everything is cool, remember the mapping...
403       ValueMap.insert(std::make_pair(SGV, DGV));
404     } else if (SGV->hasAppendingLinkage()) {
405       // No linking is performed yet.  Just insert a new copy of the global, and
406       // keep track of the fact that it is an appending variable in the
407       // AppendingVars map.  The name is cleared out so that no linkage is
408       // performed.
409       GlobalVariable *NewDGV =
410         new GlobalVariable(SGV->getType()->getElementType(),
411                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
412                            "", Dest);
413
414       // Make sure to remember this mapping...
415       ValueMap.insert(std::make_pair(SGV, NewDGV));
416
417       // Keep track that this is an appending variable...
418       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
419     } else {
420       assert(0 && "Unknown linkage!");
421     }
422   }
423   return false;
424 }
425
426
427 // LinkGlobalInits - Update the initializers in the Dest module now that all
428 // globals that may be referenced are in Dest.
429 //
430 static bool LinkGlobalInits(Module *Dest, const Module *Src,
431                             std::map<const Value*, Value*> &ValueMap,
432                             std::string *Err) {
433
434   // Loop over all of the globals in the src module, mapping them over as we go
435   //
436   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
437     const GlobalVariable *SGV = I;
438
439     if (SGV->hasInitializer()) {      // Only process initialized GV's
440       // Figure out what the initializer looks like in the dest module...
441       Constant *SInit =
442         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
443
444       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
445       if (DGV->hasInitializer()) {
446         assert(SGV->getLinkage() == DGV->getLinkage());
447         if (SGV->hasExternalLinkage()) {
448           if (DGV->getInitializer() != SInit)
449             return Error(Err, "Global Variable Collision on '" + 
450                          SGV->getType()->getDescription() +"':%"+SGV->getName()+
451                          " - Global variables have different initializers");
452         } else if (DGV->hasLinkOnceLinkage()) {
453           // Nothing is required, mapped values will take the new global
454           // automatically.
455         } else if (DGV->hasAppendingLinkage()) {
456           assert(0 && "Appending linkage unimplemented!");
457         } else {
458           assert(0 && "Unknown linkage!");
459         }
460       } else {
461         // Copy the initializer over now...
462         DGV->setInitializer(SInit);
463       }
464     }
465   }
466   return false;
467 }
468
469 // LinkFunctionProtos - Link the functions together between the two modules,
470 // without doing function bodies... this just adds external function prototypes
471 // to the Dest function...
472 //
473 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
474                                std::map<const Value*, Value*> &ValueMap,
475                                std::string *Err) {
476   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
477   
478   // Loop over all of the functions in the src module, mapping them over as we
479   // go
480   //
481   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
482     const Function *SF = I;   // SrcFunction
483     Function *DF = 0;
484     if (SF->hasName())
485       // The same named thing is a Function, because the only two things
486       // that may be in a module level symbol table are Global Vars and
487       // Functions, and they both have distinct, nonoverlapping, possible types.
488       // 
489       DF = cast_or_null<Function>(ST->lookup(SF->getType(), SF->getName()));
490
491     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
492       // Function does not already exist, simply insert an function signature
493       // identical to SF into the dest module...
494       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
495                                      SF->getName(), Dest);
496
497       // If the LLVM runtime renamed the function, but it is an externally
498       // visible symbol, DF must be an existing function with internal linkage.
499       // Rename it.
500       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
501         assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
502         DF->setName("");
503         NewDF->setName(SF->getName());  // Force the name back
504         DF->setName(SF->getName());     // This will cause a renaming
505         assert(NewDF->getName() == SF->getName() &&
506                DF->getName() != SF->getName());
507       }
508
509       // ... and remember this mapping...
510       ValueMap.insert(std::make_pair(SF, NewDF));
511     } else if (SF->isExternal()) {
512       // If SF is external or if both SF & DF are external..  Just link the
513       // external functions, we aren't adding anything.
514       ValueMap.insert(std::make_pair(SF, DF));
515     } else if (DF->isExternal()) {   // If DF is external but SF is not...
516       // Link the external functions, update linkage qualifiers
517       ValueMap.insert(std::make_pair(SF, DF));
518       DF->setLinkage(SF->getLinkage());
519
520     } else if (SF->getLinkage() != DF->getLinkage()) {
521       return Error(Err, "Functions named '" + SF->getName() +
522                    "' have different linkage specifiers!");
523     } else if (SF->hasExternalLinkage()) {
524       // The function is defined in both modules!!
525       return Error(Err, "Function '" + 
526                    SF->getFunctionType()->getDescription() + "':\"" + 
527                    SF->getName() + "\" - Function is already defined!");
528     } else if (SF->hasLinkOnceLinkage()) {
529       // Completely ignore the source function.
530       ValueMap.insert(std::make_pair(SF, DF));
531     } else {
532       assert(0 && "Unknown linkage configuration found!");
533     }
534   }
535   return false;
536 }
537
538 // LinkFunctionBody - Copy the source function over into the dest function and
539 // fix up references to values.  At this point we know that Dest is an external
540 // function, and that Src is not.
541 //
542 static bool LinkFunctionBody(Function *Dest, const Function *Src,
543                              std::map<const Value*, Value*> &GlobalMap,
544                              std::string *Err) {
545   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
546   std::map<const Value*, Value*> LocalMap;   // Map for function local values
547
548   // Go through and convert function arguments over...
549   Function::aiterator DI = Dest->abegin();
550   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
551        I != E; ++I, ++DI) {
552     DI->setName(I->getName());  // Copy the name information over...
553
554     // Add a mapping to our local map
555     LocalMap.insert(std::make_pair(I, DI));
556   }
557
558   // Loop over all of the basic blocks, copying the instructions over...
559   //
560   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
561     // Create new basic block and add to mapping and the Dest function...
562     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
563     LocalMap.insert(std::make_pair(I, DBB));
564
565     // Loop over all of the instructions in the src basic block, copying them
566     // over.  Note that this is broken in a strict sense because the cloned
567     // instructions will still be referencing values in the Src module, not
568     // the remapped values.  In our case, however, we will not get caught and 
569     // so we can delay patching the values up until later...
570     //
571     for (BasicBlock::const_iterator II = I->begin(), IE = I->end(); 
572          II != IE; ++II) {
573       Instruction *DI = II->clone();
574       DI->setName(II->getName());
575       DBB->getInstList().push_back(DI);
576       LocalMap.insert(std::make_pair(II, DI));
577     }
578   }
579
580   // At this point, all of the instructions and values of the function are now
581   // copied over.  The only problem is that they are still referencing values in
582   // the Source function as operands.  Loop through all of the operands of the
583   // functions and patch them up to point to the local versions...
584   //
585   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
586     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
587       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
588            OI != OE; ++OI)
589         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
590
591   return false;
592 }
593
594
595 // LinkFunctionBodies - Link in the function bodies that are defined in the
596 // source module into the DestModule.  This consists basically of copying the
597 // function over and fixing up references to values.
598 //
599 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
600                                std::map<const Value*, Value*> &ValueMap,
601                                std::string *Err) {
602
603   // Loop over all of the functions in the src module, mapping them over as we
604   // go
605   //
606   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
607     if (!SF->isExternal()) {                  // No body if function is external
608       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
609
610       // DF not external SF external?
611       if (!DF->isExternal()) {
612         if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
613         if (Err)
614           *Err = "Function '" + (SF->hasName() ? SF->getName() :std::string(""))
615                + "' body multiply defined!";
616         return true;
617       }
618
619       if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
620     }
621   }
622   return false;
623 }
624
625 // LinkAppendingVars - If there were any appending global variables, link them
626 // together now.  Return true on error.
627 //
628 static bool LinkAppendingVars(Module *M,
629                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
630                               std::string *ErrorMsg) {
631   if (AppendingVars.empty()) return false; // Nothing to do.
632   
633   // Loop over the multimap of appending vars, processing any variables with the
634   // same name, forming a new appending global variable with both of the
635   // initializers merged together, then rewrite references to the old variables
636   // and delete them.
637   //
638   std::vector<Constant*> Inits;
639   while (AppendingVars.size() > 1) {
640     // Get the first two elements in the map...
641     std::multimap<std::string,
642       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
643
644     // If the first two elements are for different names, there is no pair...
645     // Otherwise there is a pair, so link them together...
646     if (First->first == Second->first) {
647       GlobalVariable *G1 = First->second, *G2 = Second->second;
648       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
649       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
650       
651       // Check to see that they two arrays agree on type...
652       if (T1->getElementType() != T2->getElementType())
653         return Error(ErrorMsg,
654          "Appending variables with different element types need to be linked!");
655       if (G1->isConstant() != G2->isConstant())
656         return Error(ErrorMsg,
657                      "Appending variables linked with different const'ness!");
658
659       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
660       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
661
662       // Create the new global variable...
663       GlobalVariable *NG =
664         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
665                            /*init*/0, First->first, M);
666
667       // Merge the initializer...
668       Inits.reserve(NewSize);
669       ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
670       for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
671         Inits.push_back(cast<Constant>(I->getValues()[i]));
672       I = cast<ConstantArray>(G2->getInitializer());
673       for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
674         Inits.push_back(cast<Constant>(I->getValues()[i]));
675       NG->setInitializer(ConstantArray::get(NewType, Inits));
676       Inits.clear();
677
678       // Replace any uses of the two global variables with uses of the new
679       // global...
680
681       // FIXME: This should rewrite simple/straight-forward uses such as
682       // getelementptr instructions to not use the Cast!
683       ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
684       G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
685       G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
686
687       // Remove the two globals from the module now...
688       M->getGlobalList().erase(G1);
689       M->getGlobalList().erase(G2);
690
691       // Put the new global into the AppendingVars map so that we can handle
692       // linking of more than two vars...
693       Second->second = NG;
694     }
695     AppendingVars.erase(First);
696   }
697
698   return false;
699 }
700
701
702 // LinkModules - This function links two modules together, with the resulting
703 // left module modified to be the composite of the two input modules.  If an
704 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
705 // the problem.  Upon failure, the Dest module could be in a modified state, and
706 // shouldn't be relied on to be consistent.
707 //
708 bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
709   if (Dest->getEndianness() != Src->getEndianness())
710     std::cerr << "WARNING: Linking two modules of different endianness!\n";
711   if (Dest->getPointerSize() != Src->getPointerSize())
712     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
713
714   // LinkTypes - Go through the symbol table of the Src module and see if any
715   // types are named in the src module that are not named in the Dst module.
716   // Make sure there are no type name conflicts.
717   //
718   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
719
720   // ValueMap - Mapping of values from what they used to be in Src, to what they
721   // are now in Dest.
722   //
723   std::map<const Value*, Value*> ValueMap;
724
725   // AppendingVars - Keep track of global variables in the destination module
726   // with appending linkage.  After the module is linked together, they are
727   // appended and the module is rewritten.
728   //
729   std::multimap<std::string, GlobalVariable *> AppendingVars;
730
731   // Add all of the appending globals already in the Dest module to
732   // AppendingVars.
733   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
734     if (I->hasAppendingLinkage())
735       AppendingVars.insert(std::make_pair(I->getName(), I));
736
737   // Insert all of the globals in src into the Dest module... without linking
738   // initializers (which could refer to functions not yet mapped over).
739   //
740   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
741
742   // Link the functions together between the two modules, without doing function
743   // bodies... this just adds external function prototypes to the Dest
744   // function...  We do this so that when we begin processing function bodies,
745   // all of the global values that may be referenced are available in our
746   // ValueMap.
747   //
748   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
749
750   // Update the initializers in the Dest module now that all globals that may
751   // be referenced are in Dest.
752   //
753   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
754
755   // Link in the function bodies that are defined in the source module into the
756   // DestModule.  This consists basically of copying the function over and
757   // fixing up references to values.
758   //
759   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
760
761   // If there were any appending global variables, link them together now.
762   //
763   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
764
765   return false;
766 }
767