eliminate some ugly code, using ConstantExpr::getWithOperands instead.
[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       std::vector<Constant*> Ops;
299       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
300         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
301       Result = CE->getWithOperands(Ops);
302     } else {
303       assert(0 && "Unknown type of derived type constant value!");
304     }
305   } else if (isa<InlineAsm>(In)) {
306     Result = const_cast<Value*>(In);
307   }
308   
309   // Cache the mapping in our local map structure...
310   if (Result) {
311     ValueMap.insert(std::make_pair(In, Result));
312     return Result;
313   }
314   
315
316   std::cerr << "LinkModules ValueMap: \n";
317   PrintMap(ValueMap);
318
319   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
320   assert(0 && "Couldn't remap value!");
321   return 0;
322 }
323
324 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
325 /// in the symbol table.  This is good for all clients except for us.  Go
326 /// through the trouble to force this back.
327 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
328   assert(GV->getName() != Name && "Can't force rename to self");
329   SymbolTable &ST = GV->getParent()->getSymbolTable();
330
331   // If there is a conflict, rename the conflict.
332   Value *ConflictVal = ST.lookup(GV->getType(), Name);
333   assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
334   GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
335   assert(ConflictGV->hasInternalLinkage() &&
336          "Not conflicting with a static global, should link instead!");
337
338   ConflictGV->setName("");          // Eliminate the conflict
339   GV->setName(Name);                // Force the name back
340   ConflictGV->setName(Name);        // This will cause ConflictGV to get renamed
341   assert(GV->getName() == Name && ConflictGV->getName() != Name &&
342          "ForceRenaming didn't work");
343 }
344
345 /// GetLinkageResult - This analyzes the two global values and determines what
346 /// the result will look like in the destination module.  In particular, it
347 /// computes the resultant linkage type, computes whether the global in the
348 /// source should be copied over to the destination (replacing the existing
349 /// one), and computes whether this linkage is an error or not.
350 static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
351                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
352                              std::string *Err) {
353   assert((!Dest || !Src->hasInternalLinkage()) &&
354          "If Src has internal linkage, Dest shouldn't be set!");
355   if (!Dest) {
356     // Linking something to nothing.
357     LinkFromSrc = true;
358     LT = Src->getLinkage();
359   } else if (Src->isExternal()) {
360     // If Src is external or if both Src & Drc are external..  Just link the
361     // external globals, we aren't adding anything.
362     LinkFromSrc = false;
363     LT = Dest->getLinkage();
364   } else if (Dest->isExternal()) {
365     // If Dest is external but Src is not:
366     LinkFromSrc = true;
367     LT = Src->getLinkage();
368   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
369     if (Src->getLinkage() != Dest->getLinkage())
370       return Error(Err, "Linking globals named '" + Src->getName() +
371             "': can only link appending global with another appending global!");
372     LinkFromSrc = true; // Special cased.
373     LT = Src->getLinkage();
374   } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
375     // At this point we know that Dest has LinkOnce, External or Weak linkage.
376     if (Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) {
377       LinkFromSrc = true;
378       LT = Src->getLinkage();
379     } else {
380       LinkFromSrc = false;
381       LT = Dest->getLinkage();
382     }
383   } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
384     // At this point we know that Src has External linkage.
385     LinkFromSrc = true;
386     LT = GlobalValue::ExternalLinkage;
387   } else {
388     assert(Dest->hasExternalLinkage() && Src->hasExternalLinkage() &&
389            "Unexpected linkage type!");
390     return Error(Err, "Linking globals named '" + Src->getName() +
391                  "': symbol multiply defined!");
392   }
393   return false;
394 }
395
396 // LinkGlobals - Loop through the global variables in the src module and merge
397 // them into the dest module.
398 static bool LinkGlobals(Module *Dest, Module *Src,
399                         std::map<const Value*, Value*> &ValueMap,
400                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
401                         std::map<std::string, GlobalValue*> &GlobalsByName,
402                         std::string *Err) {
403   // We will need a module level symbol table if the src module has a module
404   // level symbol table...
405   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
406
407   // Loop over all of the globals in the src module, mapping them over as we go
408   for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
409        I != E; ++I) {
410     GlobalVariable *SGV = I;
411     GlobalVariable *DGV = 0;
412     // Check to see if may have to link the global.
413     if (SGV->hasName() && !SGV->hasInternalLinkage())
414       if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
415                                           SGV->getType()->getElementType()))) {
416         std::map<std::string, GlobalValue*>::iterator EGV =
417           GlobalsByName.find(SGV->getName());
418         if (EGV != GlobalsByName.end())
419           DGV = dyn_cast<GlobalVariable>(EGV->second);
420         if (DGV)
421           // If types don't agree due to opaque types, try to resolve them.
422           RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
423       }
424
425     if (DGV && DGV->hasInternalLinkage())
426       DGV = 0;
427
428     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
429            "Global must either be external or have an initializer!");
430
431     GlobalValue::LinkageTypes NewLinkage;
432     bool LinkFromSrc;
433     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
434       return true;
435
436     if (!DGV) {
437       // No linking to be performed, simply create an identical version of the
438       // symbol over in the dest module... the initializer will be filled in
439       // later by LinkGlobalInits...
440       GlobalVariable *NewDGV =
441         new GlobalVariable(SGV->getType()->getElementType(),
442                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
443                            SGV->getName(), Dest);
444       // Propagate alignment info.
445       NewDGV->setAlignment(SGV->getAlignment());
446       
447       // If the LLVM runtime renamed the global, but it is an externally visible
448       // symbol, DGV must be an existing global with internal linkage.  Rename
449       // it.
450       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
451         ForceRenaming(NewDGV, SGV->getName());
452
453       // Make sure to remember this mapping...
454       ValueMap.insert(std::make_pair(SGV, NewDGV));
455       if (SGV->hasAppendingLinkage())
456         // Keep track that this is an appending variable...
457         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
458     } else if (DGV->hasAppendingLinkage()) {
459       // No linking is performed yet.  Just insert a new copy of the global, and
460       // keep track of the fact that it is an appending variable in the
461       // AppendingVars map.  The name is cleared out so that no linkage is
462       // performed.
463       GlobalVariable *NewDGV =
464         new GlobalVariable(SGV->getType()->getElementType(),
465                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
466                            "", Dest);
467
468       // Propagate alignment info.
469       NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
470
471       // Make sure to remember this mapping...
472       ValueMap.insert(std::make_pair(SGV, NewDGV));
473
474       // Keep track that this is an appending variable...
475       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
476     } else {
477       // Propagate alignment info.
478       DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
479
480       // Otherwise, perform the mapping as instructed by GetLinkageResult.  If
481       // the types don't match, and if we are to link from the source, nuke DGV
482       // and create a new one of the appropriate type.
483       if (SGV->getType() != DGV->getType() && LinkFromSrc) {
484         GlobalVariable *NewDGV =
485           new GlobalVariable(SGV->getType()->getElementType(),
486                              DGV->isConstant(), DGV->getLinkage());
487         NewDGV->setAlignment(DGV->getAlignment());
488         Dest->getGlobalList().insert(DGV, NewDGV);
489         DGV->replaceAllUsesWith(ConstantExpr::getCast(NewDGV, DGV->getType()));
490         DGV->eraseFromParent();
491         NewDGV->setName(SGV->getName());
492         DGV = NewDGV;
493       }
494
495       DGV->setLinkage(NewLinkage);
496
497       if (LinkFromSrc) {
498         // Inherit const as appropriate
499         DGV->setConstant(SGV->isConstant());
500         DGV->setInitializer(0);
501       } else {
502         if (SGV->isConstant() && !DGV->isConstant()) {
503           if (DGV->isExternal())
504             DGV->setConstant(true);
505         }
506         SGV->setLinkage(GlobalValue::ExternalLinkage);
507         SGV->setInitializer(0);
508       }
509
510       ValueMap.insert(std::make_pair(SGV,
511                                      ConstantExpr::getCast(DGV,
512                                                            SGV->getType())));
513     }
514   }
515   return false;
516 }
517
518
519 // LinkGlobalInits - Update the initializers in the Dest module now that all
520 // globals that may be referenced are in Dest.
521 static bool LinkGlobalInits(Module *Dest, const Module *Src,
522                             std::map<const Value*, Value*> &ValueMap,
523                             std::string *Err) {
524
525   // Loop over all of the globals in the src module, mapping them over as we go
526   for (Module::const_global_iterator I = Src->global_begin(),
527        E = Src->global_end(); I != E; ++I) {
528     const GlobalVariable *SGV = I;
529
530     if (SGV->hasInitializer()) {      // Only process initialized GV's
531       // Figure out what the initializer looks like in the dest module...
532       Constant *SInit =
533         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
534
535       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
536       if (DGV->hasInitializer()) {
537         if (SGV->hasExternalLinkage()) {
538           if (DGV->getInitializer() != SInit)
539             return Error(Err, "Global Variable Collision on '" +
540                          ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
541                          " - Global variables have different initializers");
542         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
543           // Nothing is required, mapped values will take the new global
544           // automatically.
545         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
546           // Nothing is required, mapped values will take the new global
547           // automatically.
548         } else if (DGV->hasAppendingLinkage()) {
549           assert(0 && "Appending linkage unimplemented!");
550         } else {
551           assert(0 && "Unknown linkage!");
552         }
553       } else {
554         // Copy the initializer over now...
555         DGV->setInitializer(SInit);
556       }
557     }
558   }
559   return false;
560 }
561
562 // LinkFunctionProtos - Link the functions together between the two modules,
563 // without doing function bodies... this just adds external function prototypes
564 // to the Dest function...
565 //
566 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
567                                std::map<const Value*, Value*> &ValueMap,
568                              std::map<std::string, GlobalValue*> &GlobalsByName,
569                                std::string *Err) {
570   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
571
572   // Loop over all of the functions in the src module, mapping them over as we
573   // go
574   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
575     const Function *SF = I;   // SrcFunction
576     Function *DF = 0;
577     if (SF->hasName() && !SF->hasInternalLinkage()) {
578       // Check to see if may have to link the function.
579       if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
580         std::map<std::string, GlobalValue*>::iterator EF =
581           GlobalsByName.find(SF->getName());
582         if (EF != GlobalsByName.end())
583           DF = dyn_cast<Function>(EF->second);
584         if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
585           DF = 0;  // FIXME: gross.
586       }
587     }
588
589     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
590       // Function does not already exist, simply insert an function signature
591       // identical to SF into the dest module...
592       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
593                                      SF->getName(), Dest);
594       NewDF->setCallingConv(SF->getCallingConv());
595
596       // If the LLVM runtime renamed the function, but it is an externally
597       // visible symbol, DF must be an existing function with internal linkage.
598       // Rename it.
599       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
600         ForceRenaming(NewDF, SF->getName());
601
602       // ... and remember this mapping...
603       ValueMap.insert(std::make_pair(SF, NewDF));
604     } else if (SF->isExternal()) {
605       // If SF is external or if both SF & DF are external..  Just link the
606       // external functions, we aren't adding anything.
607       ValueMap.insert(std::make_pair(SF, DF));
608     } else if (DF->isExternal()) {   // If DF is external but SF is not...
609       // Link the external functions, update linkage qualifiers
610       ValueMap.insert(std::make_pair(SF, DF));
611       DF->setLinkage(SF->getLinkage());
612
613     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
614       // At this point we know that DF has LinkOnce, Weak, or External linkage.
615       ValueMap.insert(std::make_pair(SF, DF));
616
617       // Linkonce+Weak = Weak
618       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
619         DF->setLinkage(SF->getLinkage());
620
621     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
622       // At this point we know that SF has LinkOnce or External linkage.
623       ValueMap.insert(std::make_pair(SF, DF));
624       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
625         DF->setLinkage(SF->getLinkage());
626
627     } else if (SF->getLinkage() != DF->getLinkage()) {
628       return Error(Err, "Functions named '" + SF->getName() +
629                    "' have different linkage specifiers!");
630     } else if (SF->hasExternalLinkage()) {
631       // The function is defined in both modules!!
632       return Error(Err, "Function '" +
633                    ToStr(SF->getFunctionType(), Src) + "':\"" +
634                    SF->getName() + "\" - Function is already defined!");
635     } else {
636       assert(0 && "Unknown linkage configuration found!");
637     }
638   }
639   return false;
640 }
641
642 // LinkFunctionBody - Copy the source function over into the dest function and
643 // fix up references to values.  At this point we know that Dest is an external
644 // function, and that Src is not.
645 static bool LinkFunctionBody(Function *Dest, Function *Src,
646                              std::map<const Value*, Value*> &GlobalMap,
647                              std::string *Err) {
648   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
649
650   // Go through and convert function arguments over, remembering the mapping.
651   Function::arg_iterator DI = Dest->arg_begin();
652   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
653        I != E; ++I, ++DI) {
654     DI->setName(I->getName());  // Copy the name information over...
655
656     // Add a mapping to our local map
657     GlobalMap.insert(std::make_pair(I, DI));
658   }
659
660   // Splice the body of the source function into the dest function.
661   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
662
663   // At this point, all of the instructions and values of the function are now
664   // copied over.  The only problem is that they are still referencing values in
665   // the Source function as operands.  Loop through all of the operands of the
666   // functions and patch them up to point to the local versions...
667   //
668   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
669     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
670       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
671            OI != OE; ++OI)
672         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
673           *OI = RemapOperand(*OI, GlobalMap);
674
675   // There is no need to map the arguments anymore.
676   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
677        I != E; ++I)
678     GlobalMap.erase(I);
679
680   return false;
681 }
682
683
684 // LinkFunctionBodies - Link in the function bodies that are defined in the
685 // source module into the DestModule.  This consists basically of copying the
686 // function over and fixing up references to values.
687 static bool LinkFunctionBodies(Module *Dest, Module *Src,
688                                std::map<const Value*, Value*> &ValueMap,
689                                std::string *Err) {
690
691   // Loop over all of the functions in the src module, mapping them over as we
692   // go
693   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
694     if (!SF->isExternal()) {                  // No body if function is external
695       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
696
697       // DF not external SF external?
698       if (DF->isExternal()) {
699         // Only provide the function body if there isn't one already.
700         if (LinkFunctionBody(DF, SF, ValueMap, Err))
701           return true;
702       }
703     }
704   }
705   return false;
706 }
707
708 // LinkAppendingVars - If there were any appending global variables, link them
709 // together now.  Return true on error.
710 static bool LinkAppendingVars(Module *M,
711                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
712                               std::string *ErrorMsg) {
713   if (AppendingVars.empty()) return false; // Nothing to do.
714
715   // Loop over the multimap of appending vars, processing any variables with the
716   // same name, forming a new appending global variable with both of the
717   // initializers merged together, then rewrite references to the old variables
718   // and delete them.
719   std::vector<Constant*> Inits;
720   while (AppendingVars.size() > 1) {
721     // Get the first two elements in the map...
722     std::multimap<std::string,
723       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
724
725     // If the first two elements are for different names, there is no pair...
726     // Otherwise there is a pair, so link them together...
727     if (First->first == Second->first) {
728       GlobalVariable *G1 = First->second, *G2 = Second->second;
729       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
730       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
731
732       // Check to see that they two arrays agree on type...
733       if (T1->getElementType() != T2->getElementType())
734         return Error(ErrorMsg,
735          "Appending variables with different element types need to be linked!");
736       if (G1->isConstant() != G2->isConstant())
737         return Error(ErrorMsg,
738                      "Appending variables linked with different const'ness!");
739
740       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
741       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
742
743       G1->setName("");   // Clear G1's name in case of a conflict!
744       
745       // Create the new global variable...
746       GlobalVariable *NG =
747         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
748                            /*init*/0, First->first, M);
749
750       // Merge the initializer...
751       Inits.reserve(NewSize);
752       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
753         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
754           Inits.push_back(I->getOperand(i));
755       } else {
756         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
757         Constant *CV = Constant::getNullValue(T1->getElementType());
758         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
759           Inits.push_back(CV);
760       }
761       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
762         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
763           Inits.push_back(I->getOperand(i));
764       } else {
765         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
766         Constant *CV = Constant::getNullValue(T2->getElementType());
767         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
768           Inits.push_back(CV);
769       }
770       NG->setInitializer(ConstantArray::get(NewType, Inits));
771       Inits.clear();
772
773       // Replace any uses of the two global variables with uses of the new
774       // global...
775
776       // FIXME: This should rewrite simple/straight-forward uses such as
777       // getelementptr instructions to not use the Cast!
778       G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
779       G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
780
781       // Remove the two globals from the module now...
782       M->getGlobalList().erase(G1);
783       M->getGlobalList().erase(G2);
784
785       // Put the new global into the AppendingVars map so that we can handle
786       // linking of more than two vars...
787       Second->second = NG;
788     }
789     AppendingVars.erase(First);
790   }
791
792   return false;
793 }
794
795
796 // LinkModules - This function links two modules together, with the resulting
797 // left module modified to be the composite of the two input modules.  If an
798 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
799 // the problem.  Upon failure, the Dest module could be in a modified state, and
800 // shouldn't be relied on to be consistent.
801 bool
802 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
803   assert(Dest != 0 && "Invalid Destination module");
804   assert(Src  != 0 && "Invalid Source Module");
805
806   if (Dest->getEndianness() == Module::AnyEndianness)
807     Dest->setEndianness(Src->getEndianness());
808   if (Dest->getPointerSize() == Module::AnyPointerSize)
809     Dest->setPointerSize(Src->getPointerSize());
810   if (Dest->getTargetTriple().empty())
811     Dest->setTargetTriple(Src->getTargetTriple());
812
813   if (Src->getEndianness() != Module::AnyEndianness &&
814       Dest->getEndianness() != Src->getEndianness())
815     std::cerr << "WARNING: Linking two modules of different endianness!\n";
816   if (Src->getPointerSize() != Module::AnyPointerSize &&
817       Dest->getPointerSize() != Src->getPointerSize())
818     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
819   if (!Src->getTargetTriple().empty() &&
820       Dest->getTargetTriple() != Src->getTargetTriple())
821     std::cerr << "WARNING: Linking two modules of different target triples!\n";
822
823   if (!Src->getModuleInlineAsm().empty()) {
824     if (Dest->getModuleInlineAsm().empty())
825       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
826     else
827       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
828                                Src->getModuleInlineAsm());
829   }
830   
831   // Update the destination module's dependent libraries list with the libraries
832   // from the source module. There's no opportunity for duplicates here as the
833   // Module ensures that duplicate insertions are discarded.
834   Module::lib_iterator SI = Src->lib_begin();
835   Module::lib_iterator SE = Src->lib_end();
836   while ( SI != SE ) {
837     Dest->addLibrary(*SI);
838     ++SI;
839   }
840
841   // LinkTypes - Go through the symbol table of the Src module and see if any
842   // types are named in the src module that are not named in the Dst module.
843   // Make sure there are no type name conflicts.
844   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
845
846   // ValueMap - Mapping of values from what they used to be in Src, to what they
847   // are now in Dest.
848   std::map<const Value*, Value*> ValueMap;
849
850   // AppendingVars - Keep track of global variables in the destination module
851   // with appending linkage.  After the module is linked together, they are
852   // appended and the module is rewritten.
853   std::multimap<std::string, GlobalVariable *> AppendingVars;
854
855   // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
856   // linking by separating globals by type.  Until PR411 is fixed, we replicate
857   // it's functionality here.
858   std::map<std::string, GlobalValue*> GlobalsByName;
859
860   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
861        I != E; ++I) {
862     // Add all of the appending globals already in the Dest module to
863     // AppendingVars.
864     if (I->hasAppendingLinkage())
865       AppendingVars.insert(std::make_pair(I->getName(), I));
866
867     // Keep track of all globals by name.
868     if (!I->hasInternalLinkage() && I->hasName())
869       GlobalsByName[I->getName()] = I;
870   }
871
872   // Keep track of all globals by name.
873   for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
874     if (!I->hasInternalLinkage() && I->hasName())
875       GlobalsByName[I->getName()] = I;
876
877   // Insert all of the globals in src into the Dest module... without linking
878   // initializers (which could refer to functions not yet mapped over).
879   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
880     return true;
881
882   // Link the functions together between the two modules, without doing function
883   // bodies... this just adds external function prototypes to the Dest
884   // function...  We do this so that when we begin processing function bodies,
885   // all of the global values that may be referenced are available in our
886   // ValueMap.
887   if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
888     return true;
889
890   // Update the initializers in the Dest module now that all globals that may
891   // be referenced are in Dest.
892   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
893
894   // Link in the function bodies that are defined in the source module into the
895   // DestModule.  This consists basically of copying the function over and
896   // fixing up references to values.
897   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
898
899   // If there were any appending global variables, link them together now.
900   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
901
902   // If the source library's module id is in the dependent library list of the
903   // destination library, remove it since that module is now linked in.
904   sys::Path modId;
905   modId.set(Src->getModuleIdentifier());
906   if (!modId.isEmpty())
907     Dest->removeLibrary(modId.getBasename());
908
909   return false;
910 }
911
912 // vim: sw=2