Fix Regression/Linker/2006-06-15-GlobalVarAnment.ll
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/SymbolTable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/System/Path.h"
27 #include <iostream>
28 #include <sstream>
29 using namespace llvm;
30
31 // Error - Simple wrapper function to conditionally assign to E and return true.
32 // This just makes error return conditions a little bit simpler...
33 static inline bool Error(std::string *E, const std::string &Message) {
34   if (E) *E = Message;
35   return true;
36 }
37
38 // ToStr - Simple wrapper function to convert a type to a string.
39 static std::string ToStr(const Type *Ty, const Module *M) {
40   std::ostringstream OS;
41   WriteTypeSymbolic(OS, Ty, M);
42   return OS.str();
43 }
44
45 //
46 // Function: ResolveTypes()
47 //
48 // Description:
49 //  Attempt to link the two specified types together.
50 //
51 // Inputs:
52 //  DestTy - The type to which we wish to resolve.
53 //  SrcTy  - The original type which we want to resolve.
54 //  Name   - The name of the type.
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                          SymbolTable *DestST, const std::string &Name) {
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     else if (!Name.empty())
79       DestST->insert(Name, const_cast<Type*>(SrcTy));
80   }
81   return false;
82 }
83
84 static const FunctionType *getFT(const PATypeHolder &TH) {
85   return cast<FunctionType>(TH.get());
86 }
87 static const StructType *getST(const PATypeHolder &TH) {
88   return cast<StructType>(TH.get());
89 }
90
91 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
92 // recurses down into derived types, merging the used types if the parent types
93 // are compatible.
94 static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
95                                    const PATypeHolder &SrcTy,
96                                    SymbolTable *DestST, const std::string &Name,
97                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
98   const Type *SrcTyT = SrcTy.get();
99   const Type *DestTyT = DestTy.get();
100   if (DestTyT == SrcTyT) return false;       // If already equal, noop
101
102   // If we found our opaque type, resolve it now!
103   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
104     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
105
106   // Two types cannot be resolved together if they are of different primitive
107   // type.  For example, we cannot resolve an int to a float.
108   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
109
110   // Otherwise, resolve the used type used by this derived type...
111   switch (DestTyT->getTypeID()) {
112   case Type::FunctionTyID: {
113     if (cast<FunctionType>(DestTyT)->isVarArg() !=
114         cast<FunctionType>(SrcTyT)->isVarArg() ||
115         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
116         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
117       return true;
118     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
119       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
120                                  getFT(SrcTy)->getContainedType(i), DestST, "",
121                                  Pointers))
122         return true;
123     return false;
124   }
125   case Type::StructTyID: {
126     if (getST(DestTy)->getNumContainedTypes() !=
127         getST(SrcTy)->getNumContainedTypes()) return 1;
128     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
129       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
130                                  getST(SrcTy)->getContainedType(i), DestST, "",
131                                  Pointers))
132         return true;
133     return false;
134   }
135   case Type::ArrayTyID: {
136     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
137     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
138     if (DAT->getNumElements() != SAT->getNumElements()) return true;
139     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
140                                   DestST, "", Pointers);
141   }
142   case Type::PointerTyID: {
143     // If this is a pointer type, check to see if we have already seen it.  If
144     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
145     // an associative container for this search, because the type pointers (keys
146     // in the container) change whenever types get resolved...
147     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
148       if (Pointers[i].first == DestTy)
149         return Pointers[i].second != SrcTy;
150
151     // Otherwise, add the current pointers to the vector to stop recursion on
152     // this pair.
153     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
154     bool Result =
155       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
156                              cast<PointerType>(SrcTy.get())->getElementType(),
157                              DestST, "", Pointers);
158     Pointers.pop_back();
159     return Result;
160   }
161   default: assert(0 && "Unexpected type!"); return true;
162   }
163 }
164
165 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
166                                   const PATypeHolder &SrcTy,
167                                   SymbolTable *DestST, const std::string &Name){
168   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
169   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
170 }
171
172
173 // LinkTypes - Go through the symbol table of the Src module and see if any
174 // types are named in the src module that are not named in the Dst module.
175 // Make sure there are no type name conflicts.
176 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
177   SymbolTable       *DestST = &Dest->getSymbolTable();
178   const SymbolTable *SrcST  = &Src->getSymbolTable();
179
180   // Look for a type plane for Type's...
181   SymbolTable::type_const_iterator TI = SrcST->type_begin();
182   SymbolTable::type_const_iterator TE = SrcST->type_end();
183   if (TI == TE) return false;  // No named types, do nothing.
184
185   // Some types cannot be resolved immediately because they depend on other
186   // types being resolved to each other first.  This contains a list of types we
187   // are waiting to recheck.
188   std::vector<std::string> DelayedTypesToResolve;
189
190   for ( ; TI != TE; ++TI ) {
191     const std::string &Name = TI->first;
192     const Type *RHS = TI->second;
193
194     // Check to see if this type name is already in the dest module...
195     Type *Entry = DestST->lookupType(Name);
196
197     if (ResolveTypes(Entry, RHS, DestST, Name)) {
198       // They look different, save the types 'till later to resolve.
199       DelayedTypesToResolve.push_back(Name);
200     }
201   }
202
203   // Iteratively resolve types while we can...
204   while (!DelayedTypesToResolve.empty()) {
205     // Loop over all of the types, attempting to resolve them if possible...
206     unsigned OldSize = DelayedTypesToResolve.size();
207
208     // Try direct resolution by name...
209     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
210       const std::string &Name = DelayedTypesToResolve[i];
211       Type *T1 = SrcST->lookupType(Name);
212       Type *T2 = DestST->lookupType(Name);
213       if (!ResolveTypes(T2, T1, DestST, Name)) {
214         // We are making progress!
215         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
216         --i;
217       }
218     }
219
220     // Did we not eliminate any types?
221     if (DelayedTypesToResolve.size() == OldSize) {
222       // Attempt to resolve subelements of types.  This allows us to merge these
223       // two types: { int* } and { opaque* }
224       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
225         const std::string &Name = DelayedTypesToResolve[i];
226         PATypeHolder T1(SrcST->lookupType(Name));
227         PATypeHolder T2(DestST->lookupType(Name));
228
229         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
230           // We are making progress!
231           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
232
233           // Go back to the main loop, perhaps we can resolve directly by name
234           // now...
235           break;
236         }
237       }
238
239       // If we STILL cannot resolve the types, then there is something wrong.
240       if (DelayedTypesToResolve.size() == OldSize) {
241         // Remove the symbol name from the destination.
242         DelayedTypesToResolve.pop_back();
243       }
244     }
245   }
246
247
248   return false;
249 }
250
251 static void PrintMap(const std::map<const Value*, Value*> &M) {
252   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
253        I != E; ++I) {
254     std::cerr << " Fr: " << (void*)I->first << " ";
255     I->first->dump();
256     std::cerr << " To: " << (void*)I->second << " ";
257     I->second->dump();
258     std::cerr << "\n";
259   }
260 }
261
262
263 // RemapOperand - Use ValueMap to convert references from one module to another.
264 // This is somewhat sophisticated in that it can automatically handle constant
265 // references correctly as well.
266 static Value *RemapOperand(const Value *In,
267                            std::map<const Value*, Value*> &ValueMap) {
268   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
269   if (I != ValueMap.end()) return I->second;
270
271   // Check to see if it's a constant that we are interesting in transforming.
272   Value *Result = 0;
273   if (const Constant *CPV = dyn_cast<Constant>(In)) {
274     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
275         isa<ConstantAggregateZero>(CPV))
276       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
277
278     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
279       std::vector<Constant*> Operands(CPA->getNumOperands());
280       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
281         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
282       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
283     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
284       std::vector<Constant*> Operands(CPS->getNumOperands());
285       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
286         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
287       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
288     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
289       Result = const_cast<Constant*>(CPV);
290     } else if (isa<GlobalValue>(CPV)) {
291       Result = cast<Constant>(RemapOperand(CPV, ValueMap));
292     } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CPV)) {
293       std::vector<Constant*> Operands(CP->getNumOperands());
294       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
295         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
296       Result = ConstantPacked::get(Operands);
297     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
298       if (CE->getOpcode() == Instruction::GetElementPtr) {
299         Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
300         std::vector<Constant*> Indices;
301         Indices.reserve(CE->getNumOperands()-1);
302         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
303           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
304                                                         ValueMap)));
305
306         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
307       } else if (CE->getOpcode() == Instruction::ExtractElement) {
308         Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
309         Value *Idx = RemapOperand(CE->getOperand(1), ValueMap);
310         Result = ConstantExpr::getExtractElement(cast<Constant>(Ptr),
311                                                  cast<Constant>(Idx));
312       } else if (CE->getOpcode() == Instruction::InsertElement) {
313         Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
314         Value *Elt = RemapOperand(CE->getOperand(1), ValueMap);
315         Value *Idx = RemapOperand(CE->getOperand(2), ValueMap);
316         Result = ConstantExpr::getInsertElement(cast<Constant>(Ptr),
317                                                 cast<Constant>(Elt),
318                                                 cast<Constant>(Idx));
319       } else if (CE->getOpcode() == Instruction::ShuffleVector) {
320         Value *V1 = RemapOperand(CE->getOperand(0), ValueMap);
321         Value *V2 = RemapOperand(CE->getOperand(1), ValueMap);
322         Result = ConstantExpr::getShuffleVector(cast<Constant>(V1),
323                                                 cast<Constant>(V2),
324                                              cast<Constant>(CE->getOperand(2)));
325       } else if (CE->getNumOperands() == 1) {
326         // Cast instruction
327         assert(CE->getOpcode() == Instruction::Cast);
328         Value *V = RemapOperand(CE->getOperand(0), ValueMap);
329         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
330       } else if (CE->getNumOperands() == 3) {
331         // Select instruction
332         assert(CE->getOpcode() == Instruction::Select);
333         Value *V1 = RemapOperand(CE->getOperand(0), ValueMap);
334         Value *V2 = RemapOperand(CE->getOperand(1), ValueMap);
335         Value *V3 = RemapOperand(CE->getOperand(2), ValueMap);
336         Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
337                                          cast<Constant>(V3));
338       } else if (CE->getNumOperands() == 2) {
339         // Binary operator...
340         Value *V1 = RemapOperand(CE->getOperand(0), ValueMap);
341         Value *V2 = RemapOperand(CE->getOperand(1), ValueMap);
342
343         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
344                                    cast<Constant>(V2));
345       } else {
346         assert(0 && "Unknown constant expr type!");
347       }
348
349     } else {
350       assert(0 && "Unknown type of derived type constant value!");
351     }
352   } else if (isa<InlineAsm>(In)) {
353     Result = const_cast<Value*>(In);
354   }
355   
356   // Cache the mapping in our local map structure...
357   if (Result) {
358     ValueMap.insert(std::make_pair(In, Result));
359     return Result;
360   }
361   
362
363   std::cerr << "LinkModules ValueMap: \n";
364   PrintMap(ValueMap);
365
366   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
367   assert(0 && "Couldn't remap value!");
368   return 0;
369 }
370
371 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
372 /// in the symbol table.  This is good for all clients except for us.  Go
373 /// through the trouble to force this back.
374 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
375   assert(GV->getName() != Name && "Can't force rename to self");
376   SymbolTable &ST = GV->getParent()->getSymbolTable();
377
378   // If there is a conflict, rename the conflict.
379   Value *ConflictVal = ST.lookup(GV->getType(), Name);
380   assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
381   GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
382   assert(ConflictGV->hasInternalLinkage() &&
383          "Not conflicting with a static global, should link instead!");
384
385   ConflictGV->setName("");          // Eliminate the conflict
386   GV->setName(Name);                // Force the name back
387   ConflictGV->setName(Name);        // This will cause ConflictGV to get renamed
388   assert(GV->getName() == Name && ConflictGV->getName() != Name &&
389          "ForceRenaming didn't work");
390 }
391
392 /// GetLinkageResult - This analyzes the two global values and determines what
393 /// the result will look like in the destination module.  In particular, it
394 /// computes the resultant linkage type, computes whether the global in the
395 /// source should be copied over to the destination (replacing the existing
396 /// one), and computes whether this linkage is an error or not.
397 static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
398                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
399                              std::string *Err) {
400   assert((!Dest || !Src->hasInternalLinkage()) &&
401          "If Src has internal linkage, Dest shouldn't be set!");
402   if (!Dest) {
403     // Linking something to nothing.
404     LinkFromSrc = true;
405     LT = Src->getLinkage();
406   } else if (Src->isExternal()) {
407     // If Src is external or if both Src & Drc are external..  Just link the
408     // external globals, we aren't adding anything.
409     LinkFromSrc = false;
410     LT = Dest->getLinkage();
411   } else if (Dest->isExternal()) {
412     // If Dest is external but Src is not:
413     LinkFromSrc = true;
414     LT = Src->getLinkage();
415   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
416     if (Src->getLinkage() != Dest->getLinkage())
417       return Error(Err, "Linking globals named '" + Src->getName() +
418             "': can only link appending global with another appending global!");
419     LinkFromSrc = true; // Special cased.
420     LT = Src->getLinkage();
421   } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
422     // At this point we know that Dest has LinkOnce, External or Weak linkage.
423     if (Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) {
424       LinkFromSrc = true;
425       LT = Src->getLinkage();
426     } else {
427       LinkFromSrc = false;
428       LT = Dest->getLinkage();
429     }
430   } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
431     // At this point we know that Src has External linkage.
432     LinkFromSrc = true;
433     LT = GlobalValue::ExternalLinkage;
434   } else {
435     assert(Dest->hasExternalLinkage() && Src->hasExternalLinkage() &&
436            "Unexpected linkage type!");
437     return Error(Err, "Linking globals named '" + Src->getName() +
438                  "': symbol multiply defined!");
439   }
440   return false;
441 }
442
443 // LinkGlobals - Loop through the global variables in the src module and merge
444 // them into the dest module.
445 static bool LinkGlobals(Module *Dest, Module *Src,
446                         std::map<const Value*, Value*> &ValueMap,
447                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
448                         std::map<std::string, GlobalValue*> &GlobalsByName,
449                         std::string *Err) {
450   // We will need a module level symbol table if the src module has a module
451   // level symbol table...
452   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
453
454   // Loop over all of the globals in the src module, mapping them over as we go
455   for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
456        I != E; ++I) {
457     GlobalVariable *SGV = I;
458     GlobalVariable *DGV = 0;
459     // Check to see if may have to link the global.
460     if (SGV->hasName() && !SGV->hasInternalLinkage())
461       if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
462                                           SGV->getType()->getElementType()))) {
463         std::map<std::string, GlobalValue*>::iterator EGV =
464           GlobalsByName.find(SGV->getName());
465         if (EGV != GlobalsByName.end())
466           DGV = dyn_cast<GlobalVariable>(EGV->second);
467         if (DGV)
468           // If types don't agree due to opaque types, try to resolve them.
469           RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
470       }
471
472     if (DGV && DGV->hasInternalLinkage())
473       DGV = 0;
474
475     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
476            "Global must either be external or have an initializer!");
477
478     GlobalValue::LinkageTypes NewLinkage;
479     bool LinkFromSrc;
480     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
481       return true;
482
483     if (!DGV) {
484       // No linking to be performed, simply create an identical version of the
485       // symbol over in the dest module... the initializer will be filled in
486       // later by LinkGlobalInits...
487       GlobalVariable *NewDGV =
488         new GlobalVariable(SGV->getType()->getElementType(),
489                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
490                            SGV->getName(), Dest);
491       // Propagate alignment info.
492       NewDGV->setAlignment(SGV->getAlignment());
493       
494       // If the LLVM runtime renamed the global, but it is an externally visible
495       // symbol, DGV must be an existing global with internal linkage.  Rename
496       // it.
497       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
498         ForceRenaming(NewDGV, SGV->getName());
499
500       // Make sure to remember this mapping...
501       ValueMap.insert(std::make_pair(SGV, NewDGV));
502       if (SGV->hasAppendingLinkage())
503         // Keep track that this is an appending variable...
504         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
505     } else if (DGV->hasAppendingLinkage()) {
506       // No linking is performed yet.  Just insert a new copy of the global, and
507       // keep track of the fact that it is an appending variable in the
508       // AppendingVars map.  The name is cleared out so that no linkage is
509       // performed.
510       GlobalVariable *NewDGV =
511         new GlobalVariable(SGV->getType()->getElementType(),
512                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
513                            "", Dest);
514
515       // Propagate alignment info.
516       NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
517
518       // Make sure to remember this mapping...
519       ValueMap.insert(std::make_pair(SGV, NewDGV));
520
521       // Keep track that this is an appending variable...
522       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
523     } else {
524       // Propagate alignment info.
525       DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
526
527       // Otherwise, perform the mapping as instructed by GetLinkageResult.  If
528       // the types don't match, and if we are to link from the source, nuke DGV
529       // and create a new one of the appropriate type.
530       if (SGV->getType() != DGV->getType() && LinkFromSrc) {
531         GlobalVariable *NewDGV =
532           new GlobalVariable(SGV->getType()->getElementType(),
533                              DGV->isConstant(), DGV->getLinkage());
534         NewDGV->setAlignment(DGV->getAlignment());
535         Dest->getGlobalList().insert(DGV, NewDGV);
536         DGV->replaceAllUsesWith(ConstantExpr::getCast(NewDGV, DGV->getType()));
537         DGV->eraseFromParent();
538         NewDGV->setName(SGV->getName());
539         DGV = NewDGV;
540       }
541
542       DGV->setLinkage(NewLinkage);
543
544       if (LinkFromSrc) {
545         // Inherit const as appropriate
546         DGV->setConstant(SGV->isConstant());
547         DGV->setInitializer(0);
548       } else {
549         if (SGV->isConstant() && !DGV->isConstant()) {
550           if (DGV->isExternal())
551             DGV->setConstant(true);
552         }
553         SGV->setLinkage(GlobalValue::ExternalLinkage);
554         SGV->setInitializer(0);
555       }
556
557       ValueMap.insert(std::make_pair(SGV,
558                                      ConstantExpr::getCast(DGV,
559                                                            SGV->getType())));
560     }
561   }
562   return false;
563 }
564
565
566 // LinkGlobalInits - Update the initializers in the Dest module now that all
567 // globals that may be referenced are in Dest.
568 static bool LinkGlobalInits(Module *Dest, const Module *Src,
569                             std::map<const Value*, Value*> &ValueMap,
570                             std::string *Err) {
571
572   // Loop over all of the globals in the src module, mapping them over as we go
573   for (Module::const_global_iterator I = Src->global_begin(),
574        E = Src->global_end(); I != E; ++I) {
575     const GlobalVariable *SGV = I;
576
577     if (SGV->hasInitializer()) {      // Only process initialized GV's
578       // Figure out what the initializer looks like in the dest module...
579       Constant *SInit =
580         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
581
582       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
583       if (DGV->hasInitializer()) {
584         if (SGV->hasExternalLinkage()) {
585           if (DGV->getInitializer() != SInit)
586             return Error(Err, "Global Variable Collision on '" +
587                          ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
588                          " - Global variables have different initializers");
589         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
590           // Nothing is required, mapped values will take the new global
591           // automatically.
592         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
593           // Nothing is required, mapped values will take the new global
594           // automatically.
595         } else if (DGV->hasAppendingLinkage()) {
596           assert(0 && "Appending linkage unimplemented!");
597         } else {
598           assert(0 && "Unknown linkage!");
599         }
600       } else {
601         // Copy the initializer over now...
602         DGV->setInitializer(SInit);
603       }
604     }
605   }
606   return false;
607 }
608
609 // LinkFunctionProtos - Link the functions together between the two modules,
610 // without doing function bodies... this just adds external function prototypes
611 // to the Dest function...
612 //
613 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
614                                std::map<const Value*, Value*> &ValueMap,
615                              std::map<std::string, GlobalValue*> &GlobalsByName,
616                                std::string *Err) {
617   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
618
619   // Loop over all of the functions in the src module, mapping them over as we
620   // go
621   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
622     const Function *SF = I;   // SrcFunction
623     Function *DF = 0;
624     if (SF->hasName() && !SF->hasInternalLinkage()) {
625       // Check to see if may have to link the function.
626       if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
627         std::map<std::string, GlobalValue*>::iterator EF =
628           GlobalsByName.find(SF->getName());
629         if (EF != GlobalsByName.end())
630           DF = dyn_cast<Function>(EF->second);
631         if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
632           DF = 0;  // FIXME: gross.
633       }
634     }
635
636     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
637       // Function does not already exist, simply insert an function signature
638       // identical to SF into the dest module...
639       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
640                                      SF->getName(), Dest);
641       NewDF->setCallingConv(SF->getCallingConv());
642
643       // If the LLVM runtime renamed the function, but it is an externally
644       // visible symbol, DF must be an existing function with internal linkage.
645       // Rename it.
646       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
647         ForceRenaming(NewDF, SF->getName());
648
649       // ... and remember this mapping...
650       ValueMap.insert(std::make_pair(SF, NewDF));
651     } else if (SF->isExternal()) {
652       // If SF is external or if both SF & DF are external..  Just link the
653       // external functions, we aren't adding anything.
654       ValueMap.insert(std::make_pair(SF, DF));
655     } else if (DF->isExternal()) {   // If DF is external but SF is not...
656       // Link the external functions, update linkage qualifiers
657       ValueMap.insert(std::make_pair(SF, DF));
658       DF->setLinkage(SF->getLinkage());
659
660     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
661       // At this point we know that DF has LinkOnce, Weak, or External linkage.
662       ValueMap.insert(std::make_pair(SF, DF));
663
664       // Linkonce+Weak = Weak
665       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
666         DF->setLinkage(SF->getLinkage());
667
668     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
669       // At this point we know that SF has LinkOnce or External linkage.
670       ValueMap.insert(std::make_pair(SF, DF));
671       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
672         DF->setLinkage(SF->getLinkage());
673
674     } else if (SF->getLinkage() != DF->getLinkage()) {
675       return Error(Err, "Functions named '" + SF->getName() +
676                    "' have different linkage specifiers!");
677     } else if (SF->hasExternalLinkage()) {
678       // The function is defined in both modules!!
679       return Error(Err, "Function '" +
680                    ToStr(SF->getFunctionType(), Src) + "':\"" +
681                    SF->getName() + "\" - Function is already defined!");
682     } else {
683       assert(0 && "Unknown linkage configuration found!");
684     }
685   }
686   return false;
687 }
688
689 // LinkFunctionBody - Copy the source function over into the dest function and
690 // fix up references to values.  At this point we know that Dest is an external
691 // function, and that Src is not.
692 static bool LinkFunctionBody(Function *Dest, Function *Src,
693                              std::map<const Value*, Value*> &GlobalMap,
694                              std::string *Err) {
695   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
696
697   // Go through and convert function arguments over, remembering the mapping.
698   Function::arg_iterator DI = Dest->arg_begin();
699   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
700        I != E; ++I, ++DI) {
701     DI->setName(I->getName());  // Copy the name information over...
702
703     // Add a mapping to our local map
704     GlobalMap.insert(std::make_pair(I, DI));
705   }
706
707   // Splice the body of the source function into the dest function.
708   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
709
710   // At this point, all of the instructions and values of the function are now
711   // copied over.  The only problem is that they are still referencing values in
712   // the Source function as operands.  Loop through all of the operands of the
713   // functions and patch them up to point to the local versions...
714   //
715   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
716     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
717       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
718            OI != OE; ++OI)
719         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
720           *OI = RemapOperand(*OI, GlobalMap);
721
722   // There is no need to map the arguments anymore.
723   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
724        I != E; ++I)
725     GlobalMap.erase(I);
726
727   return false;
728 }
729
730
731 // LinkFunctionBodies - Link in the function bodies that are defined in the
732 // source module into the DestModule.  This consists basically of copying the
733 // function over and fixing up references to values.
734 static bool LinkFunctionBodies(Module *Dest, Module *Src,
735                                std::map<const Value*, Value*> &ValueMap,
736                                std::string *Err) {
737
738   // Loop over all of the functions in the src module, mapping them over as we
739   // go
740   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
741     if (!SF->isExternal()) {                  // No body if function is external
742       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
743
744       // DF not external SF external?
745       if (DF->isExternal()) {
746         // Only provide the function body if there isn't one already.
747         if (LinkFunctionBody(DF, SF, ValueMap, Err))
748           return true;
749       }
750     }
751   }
752   return false;
753 }
754
755 // LinkAppendingVars - If there were any appending global variables, link them
756 // together now.  Return true on error.
757 static bool LinkAppendingVars(Module *M,
758                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
759                               std::string *ErrorMsg) {
760   if (AppendingVars.empty()) return false; // Nothing to do.
761
762   // Loop over the multimap of appending vars, processing any variables with the
763   // same name, forming a new appending global variable with both of the
764   // initializers merged together, then rewrite references to the old variables
765   // and delete them.
766   std::vector<Constant*> Inits;
767   while (AppendingVars.size() > 1) {
768     // Get the first two elements in the map...
769     std::multimap<std::string,
770       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
771
772     // If the first two elements are for different names, there is no pair...
773     // Otherwise there is a pair, so link them together...
774     if (First->first == Second->first) {
775       GlobalVariable *G1 = First->second, *G2 = Second->second;
776       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
777       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
778
779       // Check to see that they two arrays agree on type...
780       if (T1->getElementType() != T2->getElementType())
781         return Error(ErrorMsg,
782          "Appending variables with different element types need to be linked!");
783       if (G1->isConstant() != G2->isConstant())
784         return Error(ErrorMsg,
785                      "Appending variables linked with different const'ness!");
786
787       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
788       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
789
790       G1->setName("");   // Clear G1's name in case of a conflict!
791       
792       // Create the new global variable...
793       GlobalVariable *NG =
794         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
795                            /*init*/0, First->first, M);
796
797       // Merge the initializer...
798       Inits.reserve(NewSize);
799       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
800         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
801           Inits.push_back(I->getOperand(i));
802       } else {
803         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
804         Constant *CV = Constant::getNullValue(T1->getElementType());
805         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
806           Inits.push_back(CV);
807       }
808       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
809         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
810           Inits.push_back(I->getOperand(i));
811       } else {
812         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
813         Constant *CV = Constant::getNullValue(T2->getElementType());
814         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
815           Inits.push_back(CV);
816       }
817       NG->setInitializer(ConstantArray::get(NewType, Inits));
818       Inits.clear();
819
820       // Replace any uses of the two global variables with uses of the new
821       // global...
822
823       // FIXME: This should rewrite simple/straight-forward uses such as
824       // getelementptr instructions to not use the Cast!
825       G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
826       G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
827
828       // Remove the two globals from the module now...
829       M->getGlobalList().erase(G1);
830       M->getGlobalList().erase(G2);
831
832       // Put the new global into the AppendingVars map so that we can handle
833       // linking of more than two vars...
834       Second->second = NG;
835     }
836     AppendingVars.erase(First);
837   }
838
839   return false;
840 }
841
842
843 // LinkModules - This function links two modules together, with the resulting
844 // left module modified to be the composite of the two input modules.  If an
845 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
846 // the problem.  Upon failure, the Dest module could be in a modified state, and
847 // shouldn't be relied on to be consistent.
848 bool
849 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
850   assert(Dest != 0 && "Invalid Destination module");
851   assert(Src  != 0 && "Invalid Source Module");
852
853   if (Dest->getEndianness() == Module::AnyEndianness)
854     Dest->setEndianness(Src->getEndianness());
855   if (Dest->getPointerSize() == Module::AnyPointerSize)
856     Dest->setPointerSize(Src->getPointerSize());
857   if (Dest->getTargetTriple().empty())
858     Dest->setTargetTriple(Src->getTargetTriple());
859
860   if (Src->getEndianness() != Module::AnyEndianness &&
861       Dest->getEndianness() != Src->getEndianness())
862     std::cerr << "WARNING: Linking two modules of different endianness!\n";
863   if (Src->getPointerSize() != Module::AnyPointerSize &&
864       Dest->getPointerSize() != Src->getPointerSize())
865     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
866   if (!Src->getTargetTriple().empty() &&
867       Dest->getTargetTriple() != Src->getTargetTriple())
868     std::cerr << "WARNING: Linking two modules of different target triples!\n";
869
870   if (!Src->getModuleInlineAsm().empty()) {
871     if (Dest->getModuleInlineAsm().empty())
872       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
873     else
874       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
875                                Src->getModuleInlineAsm());
876   }
877   
878   // Update the destination module's dependent libraries list with the libraries
879   // from the source module. There's no opportunity for duplicates here as the
880   // Module ensures that duplicate insertions are discarded.
881   Module::lib_iterator SI = Src->lib_begin();
882   Module::lib_iterator SE = Src->lib_end();
883   while ( SI != SE ) {
884     Dest->addLibrary(*SI);
885     ++SI;
886   }
887
888   // LinkTypes - Go through the symbol table of the Src module and see if any
889   // types are named in the src module that are not named in the Dst module.
890   // Make sure there are no type name conflicts.
891   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
892
893   // ValueMap - Mapping of values from what they used to be in Src, to what they
894   // are now in Dest.
895   std::map<const Value*, Value*> ValueMap;
896
897   // AppendingVars - Keep track of global variables in the destination module
898   // with appending linkage.  After the module is linked together, they are
899   // appended and the module is rewritten.
900   std::multimap<std::string, GlobalVariable *> AppendingVars;
901
902   // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
903   // linking by separating globals by type.  Until PR411 is fixed, we replicate
904   // it's functionality here.
905   std::map<std::string, GlobalValue*> GlobalsByName;
906
907   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
908        I != E; ++I) {
909     // Add all of the appending globals already in the Dest module to
910     // AppendingVars.
911     if (I->hasAppendingLinkage())
912       AppendingVars.insert(std::make_pair(I->getName(), I));
913
914     // Keep track of all globals by name.
915     if (!I->hasInternalLinkage() && I->hasName())
916       GlobalsByName[I->getName()] = I;
917   }
918
919   // Keep track of all globals by name.
920   for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
921     if (!I->hasInternalLinkage() && I->hasName())
922       GlobalsByName[I->getName()] = I;
923
924   // Insert all of the globals in src into the Dest module... without linking
925   // initializers (which could refer to functions not yet mapped over).
926   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
927     return true;
928
929   // Link the functions together between the two modules, without doing function
930   // bodies... this just adds external function prototypes to the Dest
931   // function...  We do this so that when we begin processing function bodies,
932   // all of the global values that may be referenced are available in our
933   // ValueMap.
934   if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
935     return true;
936
937   // Update the initializers in the Dest module now that all globals that may
938   // be referenced are in Dest.
939   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
940
941   // Link in the function bodies that are defined in the source module into the
942   // DestModule.  This consists basically of copying the function over and
943   // fixing up references to values.
944   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
945
946   // If there were any appending global variables, link them together now.
947   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
948
949   // If the source library's module id is in the dependent library list of the
950   // destination library, remove it since that module is now linked in.
951   sys::Path modId;
952   modId.set(Src->getModuleIdentifier());
953   if (!modId.isEmpty())
954     Dest->removeLibrary(modId.getBasename());
955
956   return false;
957 }
958
959 // vim: sw=2