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