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