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