Remove unnecessary #include.
[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 is distributed under the University of Illinois Open Source
6 // 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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/ADT/DenseMap.h"
32 using namespace llvm;
33
34 // Error - Simple wrapper function to conditionally assign to E and return true.
35 // This just makes error return conditions a little bit simpler...
36 static inline bool Error(std::string *E, const Twine &Message) {
37   if (E) *E = Message.str();
38   return true;
39 }
40
41 // Function: ResolveTypes()
42 //
43 // Description:
44 //  Attempt to link the two specified types together.
45 //
46 // Inputs:
47 //  DestTy - The type to which we wish to resolve.
48 //  SrcTy  - The original type which we want to resolve.
49 //
50 // Outputs:
51 //  DestST - The symbol table in which the new type should be placed.
52 //
53 // Return value:
54 //  true  - There is an error and the types cannot yet be linked.
55 //  false - No errors.
56 //
57 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
58   if (DestTy == SrcTy) return false;       // If already equal, noop
59   assert(DestTy && SrcTy && "Can't handle null types");
60
61   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
62     // Type _is_ in module, just opaque...
63     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
64   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
65     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
66   } else {
67     return true;  // Cannot link types... not-equal and neither is opaque.
68   }
69   return false;
70 }
71
72 /// LinkerTypeMap - This implements a map of types that is stable
73 /// even if types are resolved/refined to other types.  This is not a general
74 /// purpose map, it is specific to the linker's use.
75 namespace {
76 class LinkerTypeMap : public AbstractTypeUser {
77   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
78   TheMapTy TheMap;
79
80   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
82 public:
83   LinkerTypeMap() {}
84   ~LinkerTypeMap() {
85     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
86          E = TheMap.end(); I != E; ++I)
87       I->first->removeAbstractTypeUser(this);
88   }
89
90   /// lookup - Return the value for the specified type or null if it doesn't
91   /// exist.
92   const Type *lookup(const Type *Ty) const {
93     TheMapTy::const_iterator I = TheMap.find(Ty);
94     if (I != TheMap.end()) return I->second;
95     return 0;
96   }
97
98   /// erase - Remove the specified type, returning true if it was in the set.
99   bool erase(const Type *Ty) {
100     if (!TheMap.erase(Ty))
101       return false;
102     if (Ty->isAbstract())
103       Ty->removeAbstractTypeUser(this);
104     return true;
105   }
106
107   /// insert - This returns true if the pointer was new to the set, false if it
108   /// was already in the set.
109   bool insert(const Type *Src, const Type *Dst) {
110     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
111       return false;  // Already in map.
112     if (Src->isAbstract())
113       Src->addAbstractTypeUser(this);
114     return true;
115   }
116
117 protected:
118   /// refineAbstractType - The callback method invoked when an abstract type is
119   /// resolved to another type.  An object must override this method to update
120   /// its internal state to reference NewType instead of OldType.
121   ///
122   virtual void refineAbstractType(const DerivedType *OldTy,
123                                   const Type *NewTy) {
124     TheMapTy::iterator I = TheMap.find(OldTy);
125     const Type *DstTy = I->second;
126
127     TheMap.erase(I);
128     if (OldTy->isAbstract())
129       OldTy->removeAbstractTypeUser(this);
130
131     // Don't reinsert into the map if the key is concrete now.
132     if (NewTy->isAbstract())
133       insert(NewTy, DstTy);
134   }
135
136   /// The other case which AbstractTypeUsers must be aware of is when a type
137   /// makes the transition from being abstract (where it has clients on it's
138   /// AbstractTypeUsers list) to concrete (where it does not).  This method
139   /// notifies ATU's when this occurs for a type.
140   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
141     TheMap.erase(AbsTy);
142     AbsTy->removeAbstractTypeUser(this);
143   }
144
145   // for debugging...
146   virtual void dump() const {
147     errs() << "AbstractTypeSet!\n";
148   }
149 };
150 }
151
152
153 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
154 // recurses down into derived types, merging the used types if the parent types
155 // are compatible.
156 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
157                                    LinkerTypeMap &Pointers) {
158   if (DstTy == SrcTy) return false;       // If already equal, noop
159
160   // If we found our opaque type, resolve it now!
161   if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
162     return ResolveTypes(DstTy, SrcTy);
163
164   // Two types cannot be resolved together if they are of different primitive
165   // type.  For example, we cannot resolve an int to a float.
166   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
167
168   // If neither type is abstract, then they really are just different types.
169   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
170     return true;
171
172   // Otherwise, resolve the used type used by this derived type...
173   switch (DstTy->getTypeID()) {
174   default:
175     return true;
176   case Type::FunctionTyID: {
177     const FunctionType *DstFT = cast<FunctionType>(DstTy);
178     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
179     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
180         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
181       return true;
182
183     // Use TypeHolder's so recursive resolution won't break us.
184     PATypeHolder ST(SrcFT), DT(DstFT);
185     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
186       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
187       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
188         return true;
189     }
190     return false;
191   }
192   case Type::StructTyID: {
193     const StructType *DstST = cast<StructType>(DstTy);
194     const StructType *SrcST = cast<StructType>(SrcTy);
195     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
196       return true;
197
198     PATypeHolder ST(SrcST), DT(DstST);
199     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
200       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
201       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
202         return true;
203     }
204     return false;
205   }
206   case Type::ArrayTyID: {
207     const ArrayType *DAT = cast<ArrayType>(DstTy);
208     const ArrayType *SAT = cast<ArrayType>(SrcTy);
209     if (DAT->getNumElements() != SAT->getNumElements()) return true;
210     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
211                                   Pointers);
212   }
213   case Type::VectorTyID: {
214     const VectorType *DVT = cast<VectorType>(DstTy);
215     const VectorType *SVT = cast<VectorType>(SrcTy);
216     if (DVT->getNumElements() != SVT->getNumElements()) return true;
217     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
218                                   Pointers);
219   }
220   case Type::PointerTyID: {
221     const PointerType *DstPT = cast<PointerType>(DstTy);
222     const PointerType *SrcPT = cast<PointerType>(SrcTy);
223
224     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
225       return true;
226
227     // If this is a pointer type, check to see if we have already seen it.  If
228     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
229     // an associative container for this search, because the type pointers (keys
230     // in the container) change whenever types get resolved.
231     if (SrcPT->isAbstract())
232       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
233         return ExistingDestTy != DstPT;
234
235     if (DstPT->isAbstract())
236       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
237         return ExistingSrcTy != SrcPT;
238     // Otherwise, add the current pointers to the vector to stop recursion on
239     // this pair.
240     if (DstPT->isAbstract())
241       Pointers.insert(DstPT, SrcPT);
242     if (SrcPT->isAbstract())
243       Pointers.insert(SrcPT, DstPT);
244
245     return RecursiveResolveTypesI(DstPT->getElementType(),
246                                   SrcPT->getElementType(), Pointers);
247   }
248   }
249 }
250
251 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
252   LinkerTypeMap PointerTypes;
253   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
254 }
255
256
257 // LinkTypes - Go through the symbol table of the Src module and see if any
258 // types are named in the src module that are not named in the Dst module.
259 // Make sure there are no type name conflicts.
260 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
261         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
262   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
263
264   // Look for a type plane for Type's...
265   TypeSymbolTable::const_iterator TI = SrcST->begin();
266   TypeSymbolTable::const_iterator TE = SrcST->end();
267   if (TI == TE) return false;  // No named types, do nothing.
268
269   // Some types cannot be resolved immediately because they depend on other
270   // types being resolved to each other first.  This contains a list of types we
271   // are waiting to recheck.
272   std::vector<std::string> DelayedTypesToResolve;
273
274   for ( ; TI != TE; ++TI ) {
275     const std::string &Name = TI->first;
276     const Type *RHS = TI->second;
277
278     // Check to see if this type name is already in the dest module.
279     Type *Entry = DestST->lookup(Name);
280
281     // If the name is just in the source module, bring it over to the dest.
282     if (Entry == 0) {
283       if (!Name.empty())
284         DestST->insert(Name, const_cast<Type*>(RHS));
285     } else if (ResolveTypes(Entry, RHS)) {
286       // They look different, save the types 'till later to resolve.
287       DelayedTypesToResolve.push_back(Name);
288     }
289   }
290
291   // Iteratively resolve types while we can...
292   while (!DelayedTypesToResolve.empty()) {
293     // Loop over all of the types, attempting to resolve them if possible...
294     unsigned OldSize = DelayedTypesToResolve.size();
295
296     // Try direct resolution by name...
297     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
298       const std::string &Name = DelayedTypesToResolve[i];
299       Type *T1 = SrcST->lookup(Name);
300       Type *T2 = DestST->lookup(Name);
301       if (!ResolveTypes(T2, T1)) {
302         // We are making progress!
303         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
304         --i;
305       }
306     }
307
308     // Did we not eliminate any types?
309     if (DelayedTypesToResolve.size() == OldSize) {
310       // Attempt to resolve subelements of types.  This allows us to merge these
311       // two types: { int* } and { opaque* }
312       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
313         const std::string &Name = DelayedTypesToResolve[i];
314         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
315           // We are making progress!
316           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
317
318           // Go back to the main loop, perhaps we can resolve directly by name
319           // now...
320           break;
321         }
322       }
323
324       // If we STILL cannot resolve the types, then there is something wrong.
325       if (DelayedTypesToResolve.size() == OldSize) {
326         // Remove the symbol name from the destination.
327         DelayedTypesToResolve.pop_back();
328       }
329     }
330   }
331
332
333   return false;
334 }
335
336 #ifndef NDEBUG
337 static void PrintMap(const std::map<const Value*, Value*> &M) {
338   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
339        I != E; ++I) {
340     errs() << " Fr: " << (void*)I->first << " ";
341     I->first->dump();
342     errs() << " To: " << (void*)I->second << " ";
343     I->second->dump();
344     errs() << "\n";
345   }
346 }
347 #endif
348
349
350 // RemapOperand - Use ValueMap to convert constants from one module to another.
351 static Value *RemapOperand(const Value *In,
352                            std::map<const Value*, Value*> &ValueMap,
353                            LLVMContext &Context) {
354   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
355   if (I != ValueMap.end())
356     return I->second;
357
358   // Check to see if it's a constant that we are interested in transforming.
359   Value *Result = 0;
360   if (const Constant *CPV = dyn_cast<Constant>(In)) {
361     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
362         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
363       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
364
365     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
366       std::vector<Constant*> Operands(CPA->getNumOperands());
367       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
368         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap, 
369                                                  Context));
370       Result =
371           ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
372     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
373       std::vector<Constant*> Operands(CPS->getNumOperands());
374       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
375         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
376                                                  Context));
377       Result =
378          ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
379     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
380       Result = const_cast<Constant*>(CPV);
381     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
382       std::vector<Constant*> Operands(CP->getNumOperands());
383       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
384         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
385                                      Context));
386       Result = ConstantVector::get(Operands);
387     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
388       std::vector<Constant*> Ops;
389       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
390         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
391                                      Context)));
392       Result = CE->getWithOperands(Ops);
393     } else {
394       assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
395       llvm_unreachable("Unknown type of derived type constant value!");
396     }
397   } else if (isa<MetadataBase>(In)) {
398     Result = const_cast<Value*>(In);
399   } else if (isa<InlineAsm>(In)) {
400     Result = const_cast<Value*>(In);
401   }
402
403   // Cache the mapping in our local map structure
404   if (Result) {
405     ValueMap[In] = Result;
406     return Result;
407   }
408
409 #ifndef NDEBUG
410   errs() << "LinkModules ValueMap: \n";
411   PrintMap(ValueMap);
412
413   errs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
414   llvm_unreachable("Couldn't remap value!");
415 #endif
416   return 0;
417 }
418
419 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
420 /// in the symbol table.  This is good for all clients except for us.  Go
421 /// through the trouble to force this back.
422 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
423   assert(GV->getName() != Name && "Can't force rename to self");
424   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
425
426   // If there is a conflict, rename the conflict.
427   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
428     assert(ConflictGV->hasLocalLinkage() &&
429            "Not conflicting with a static global, should link instead!");
430     GV->takeName(ConflictGV);
431     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
432     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
433   } else {
434     GV->setName(Name);              // Force the name back
435   }
436 }
437
438 /// CopyGVAttributes - copy additional attributes (those not needed to construct
439 /// a GlobalValue) from the SrcGV to the DestGV.
440 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
441   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
442   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
443   DestGV->copyAttributesFrom(SrcGV);
444   DestGV->setAlignment(Alignment);
445 }
446
447 /// GetLinkageResult - This analyzes the two global values and determines what
448 /// the result will look like in the destination module.  In particular, it
449 /// computes the resultant linkage type, computes whether the global in the
450 /// source should be copied over to the destination (replacing the existing
451 /// one), and computes whether this linkage is an error or not. It also performs
452 /// visibility checks: we cannot link together two symbols with different
453 /// visibilities.
454 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
455                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
456                              std::string *Err) {
457   assert((!Dest || !Src->hasLocalLinkage()) &&
458          "If Src has internal linkage, Dest shouldn't be set!");
459   if (!Dest) {
460     // Linking something to nothing.
461     LinkFromSrc = true;
462     LT = Src->getLinkage();
463   } else if (Src->isDeclaration()) {
464     // If Src is external or if both Src & Dest are external..  Just link the
465     // external globals, we aren't adding anything.
466     if (Src->hasDLLImportLinkage()) {
467       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
468       if (Dest->isDeclaration()) {
469         LinkFromSrc = true;
470         LT = Src->getLinkage();
471       }
472     } else if (Dest->hasExternalWeakLinkage()) {
473       // If the Dest is weak, use the source linkage.
474       LinkFromSrc = true;
475       LT = Src->getLinkage();
476     } else {
477       LinkFromSrc = false;
478       LT = Dest->getLinkage();
479     }
480   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
481     // If Dest is external but Src is not:
482     LinkFromSrc = true;
483     LT = Src->getLinkage();
484   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
485     if (Src->getLinkage() != Dest->getLinkage())
486       return Error(Err, "Linking globals named '" + Src->getName() +
487             "': can only link appending global with another appending global!");
488     LinkFromSrc = true; // Special cased.
489     LT = Src->getLinkage();
490   } else if (Src->isWeakForLinker()) {
491     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
492     // or DLL* linkage.
493     if (Dest->hasExternalWeakLinkage() ||
494         Dest->hasAvailableExternallyLinkage() ||
495         (Dest->hasLinkOnceLinkage() &&
496          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
497       LinkFromSrc = true;
498       LT = Src->getLinkage();
499     } else {
500       LinkFromSrc = false;
501       LT = Dest->getLinkage();
502     }
503   } else if (Dest->isWeakForLinker()) {
504     // At this point we know that Src has External* or DLL* linkage.
505     if (Src->hasExternalWeakLinkage()) {
506       LinkFromSrc = false;
507       LT = Dest->getLinkage();
508     } else {
509       LinkFromSrc = true;
510       LT = GlobalValue::ExternalLinkage;
511     }
512   } else {
513     assert((Dest->hasExternalLinkage() ||
514             Dest->hasDLLImportLinkage() ||
515             Dest->hasDLLExportLinkage() ||
516             Dest->hasExternalWeakLinkage()) &&
517            (Src->hasExternalLinkage() ||
518             Src->hasDLLImportLinkage() ||
519             Src->hasDLLExportLinkage() ||
520             Src->hasExternalWeakLinkage()) &&
521            "Unexpected linkage type!");
522     return Error(Err, "Linking globals named '" + Src->getName() +
523                  "': symbol multiply defined!");
524   }
525
526   // Check visibility
527   if (Dest && Src->getVisibility() != Dest->getVisibility())
528     if (!Src->isDeclaration() && !Dest->isDeclaration())
529       return Error(Err, "Linking globals named '" + Src->getName() +
530                    "': symbols have different visibilities!");
531   return false;
532 }
533
534 // Insert all of the named mdnoes in Src into the Dest module.
535 static void LinkNamedMDNodes(Module *Dest, Module *Src) {
536   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
537          E = Src->named_metadata_end(); I != E; ++I) {
538     const NamedMDNode *SrcNMD = I;
539     NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
540     if (!DestNMD)
541       NamedMDNode::Create(SrcNMD, Dest);
542     else {
543       // Add Src elements into Dest node.
544       for (unsigned i = 0, e = SrcNMD->getNumElements(); i != e; ++i) 
545         DestNMD->addElement(SrcNMD->getElement(i));
546     }
547   }
548 }
549
550 // LinkGlobals - Loop through the global variables in the src module and merge
551 // them into the dest module.
552 static bool LinkGlobals(Module *Dest, const Module *Src,
553                         std::map<const Value*, Value*> &ValueMap,
554                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
555                         std::string *Err) {
556   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
557
558   // Loop over all of the globals in the src module, mapping them over as we go
559   for (Module::const_global_iterator I = Src->global_begin(),
560        E = Src->global_end(); I != E; ++I) {
561     const GlobalVariable *SGV = I;
562     GlobalValue *DGV = 0;
563
564     // Check to see if may have to link the global with the global, alias or
565     // function.
566     if (SGV->hasName() && !SGV->hasLocalLinkage())
567       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
568
569     // If we found a global with the same name in the dest module, but it has
570     // internal linkage, we are really not doing any linkage here.
571     if (DGV && DGV->hasLocalLinkage())
572       DGV = 0;
573
574     // If types don't agree due to opaque types, try to resolve them.
575     if (DGV && DGV->getType() != SGV->getType())
576       RecursiveResolveTypes(SGV->getType(), DGV->getType());
577
578     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
579             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
580            "Global must either be external or have an initializer!");
581
582     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
583     bool LinkFromSrc = false;
584     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
585       return true;
586
587     if (DGV == 0) {
588       // No linking to be performed, simply create an identical version of the
589       // symbol over in the dest module... the initializer will be filled in
590       // later by LinkGlobalInits.
591       GlobalVariable *NewDGV =
592         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
593                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
594                            SGV->getName(), 0, false,
595                            SGV->getType()->getAddressSpace());
596       // Propagate alignment, visibility and section info.
597       CopyGVAttributes(NewDGV, SGV);
598
599       // If the LLVM runtime renamed the global, but it is an externally visible
600       // symbol, DGV must be an existing global with internal linkage.  Rename
601       // it.
602       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
603         ForceRenaming(NewDGV, SGV->getName());
604
605       // Make sure to remember this mapping.
606       ValueMap[SGV] = NewDGV;
607
608       // Keep track that this is an appending variable.
609       if (SGV->hasAppendingLinkage())
610         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
611       continue;
612     }
613
614     // If the visibilities of the symbols disagree and the destination is a
615     // prototype, take the visibility of its input.
616     if (DGV->isDeclaration())
617       DGV->setVisibility(SGV->getVisibility());
618
619     if (DGV->hasAppendingLinkage()) {
620       // No linking is performed yet.  Just insert a new copy of the global, and
621       // keep track of the fact that it is an appending variable in the
622       // AppendingVars map.  The name is cleared out so that no linkage is
623       // performed.
624       GlobalVariable *NewDGV =
625         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
626                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
627                            "", 0, false,
628                            SGV->getType()->getAddressSpace());
629
630       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
631       NewDGV->setAlignment(DGV->getAlignment());
632       // Propagate alignment, section and visibility info.
633       CopyGVAttributes(NewDGV, SGV);
634
635       // Make sure to remember this mapping...
636       ValueMap[SGV] = NewDGV;
637
638       // Keep track that this is an appending variable...
639       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
640       continue;
641     }
642
643     if (LinkFromSrc) {
644       if (isa<GlobalAlias>(DGV))
645         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
646                      "': symbol multiple defined");
647
648       // If the types don't match, and if we are to link from the source, nuke
649       // DGV and create a new one of the appropriate type.  Note that the thing
650       // we are replacing may be a function (if a prototype, weak, etc) or a
651       // global variable.
652       GlobalVariable *NewDGV =
653         new GlobalVariable(*Dest, SGV->getType()->getElementType(), 
654                            SGV->isConstant(), NewLinkage, /*init*/0, 
655                            DGV->getName(), 0, false,
656                            SGV->getType()->getAddressSpace());
657
658       // Propagate alignment, section, and visibility info.
659       CopyGVAttributes(NewDGV, SGV);
660       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 
661                                                               DGV->getType()));
662
663       // DGV will conflict with NewDGV because they both had the same
664       // name. We must erase this now so ForceRenaming doesn't assert
665       // because DGV might not have internal linkage.
666       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
667         Var->eraseFromParent();
668       else
669         cast<Function>(DGV)->eraseFromParent();
670       DGV = NewDGV;
671
672       // If the symbol table renamed the global, but it is an externally visible
673       // symbol, DGV must be an existing global with internal linkage.  Rename.
674       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
675         ForceRenaming(NewDGV, SGV->getName());
676
677       // Inherit const as appropriate.
678       NewDGV->setConstant(SGV->isConstant());
679
680       // Make sure to remember this mapping.
681       ValueMap[SGV] = NewDGV;
682       continue;
683     }
684
685     // Not "link from source", keep the one in the DestModule and remap the
686     // input onto it.
687
688     // Special case for const propagation.
689     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
690       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
691         DGVar->setConstant(true);
692
693     // SGV is global, but DGV is alias.
694     if (isa<GlobalAlias>(DGV)) {
695       // The only valid mappings are:
696       // - SGV is external declaration, which is effectively a no-op.
697       // - SGV is weak, when we just need to throw SGV out.
698       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
699         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
700                      "': symbol multiple defined");
701     }
702
703     // Set calculated linkage
704     DGV->setLinkage(NewLinkage);
705
706     // Make sure to remember this mapping...
707     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
708   }
709   return false;
710 }
711
712 static GlobalValue::LinkageTypes
713 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
714   GlobalValue::LinkageTypes SL = SGV->getLinkage();
715   GlobalValue::LinkageTypes DL = DGV->getLinkage();
716   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
717     return GlobalValue::ExternalLinkage;
718   else if (SL == GlobalValue::WeakAnyLinkage ||
719            DL == GlobalValue::WeakAnyLinkage)
720     return GlobalValue::WeakAnyLinkage;
721   else if (SL == GlobalValue::WeakODRLinkage ||
722            DL == GlobalValue::WeakODRLinkage)
723     return GlobalValue::WeakODRLinkage;
724   else if (SL == GlobalValue::InternalLinkage &&
725            DL == GlobalValue::InternalLinkage)
726     return GlobalValue::InternalLinkage;
727   else if (SL == GlobalValue::LinkerPrivateLinkage &&
728            DL == GlobalValue::LinkerPrivateLinkage)
729     return GlobalValue::LinkerPrivateLinkage;
730   else {
731     assert (SL == GlobalValue::PrivateLinkage &&
732             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
733     return GlobalValue::PrivateLinkage;
734   }
735 }
736
737 // LinkAlias - Loop through the alias in the src module and link them into the
738 // dest module. We're assuming, that all functions/global variables were already
739 // linked in.
740 static bool LinkAlias(Module *Dest, const Module *Src,
741                       std::map<const Value*, Value*> &ValueMap,
742                       std::string *Err) {
743   // Loop over all alias in the src module
744   for (Module::const_alias_iterator I = Src->alias_begin(),
745          E = Src->alias_end(); I != E; ++I) {
746     const GlobalAlias *SGA = I;
747     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
748     GlobalAlias *NewGA = NULL;
749
750     // Globals were already linked, thus we can just query ValueMap for variant
751     // of SAliasee in Dest.
752     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
753     assert(VMI != ValueMap.end() && "Aliasee not linked");
754     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
755     GlobalValue* DGV = NULL;
756
757     // Try to find something 'similar' to SGA in destination module.
758     if (!DGV && !SGA->hasLocalLinkage()) {
759       DGV = Dest->getNamedAlias(SGA->getName());
760
761       // If types don't agree due to opaque types, try to resolve them.
762       if (DGV && DGV->getType() != SGA->getType())
763         RecursiveResolveTypes(SGA->getType(), DGV->getType());
764     }
765
766     if (!DGV && !SGA->hasLocalLinkage()) {
767       DGV = Dest->getGlobalVariable(SGA->getName());
768
769       // If types don't agree due to opaque types, try to resolve them.
770       if (DGV && DGV->getType() != SGA->getType())
771         RecursiveResolveTypes(SGA->getType(), DGV->getType());
772     }
773
774     if (!DGV && !SGA->hasLocalLinkage()) {
775       DGV = Dest->getFunction(SGA->getName());
776
777       // If types don't agree due to opaque types, try to resolve them.
778       if (DGV && DGV->getType() != SGA->getType())
779         RecursiveResolveTypes(SGA->getType(), DGV->getType());
780     }
781
782     // No linking to be performed on internal stuff.
783     if (DGV && DGV->hasLocalLinkage())
784       DGV = NULL;
785
786     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
787       // Types are known to be the same, check whether aliasees equal. As
788       // globals are already linked we just need query ValueMap to find the
789       // mapping.
790       if (DAliasee == DGA->getAliasedGlobal()) {
791         // This is just two copies of the same alias. Propagate linkage, if
792         // necessary.
793         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
794
795         NewGA = DGA;
796         // Proceed to 'common' steps
797       } else
798         return Error(Err, "Alias Collision on '"  + SGA->getName()+
799                      "': aliases have different aliasees");
800     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
801       // The only allowed way is to link alias with external declaration or weak
802       // symbol..
803       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
804         // But only if aliasee is global too...
805         if (!isa<GlobalVariable>(DAliasee))
806           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
807                        "': aliasee is not global variable");
808
809         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
810                                 SGA->getName(), DAliasee, Dest);
811         CopyGVAttributes(NewGA, SGA);
812
813         // Any uses of DGV need to change to NewGA, with cast, if needed.
814         if (SGA->getType() != DGVar->getType())
815           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
816                                                              DGVar->getType()));
817         else
818           DGVar->replaceAllUsesWith(NewGA);
819
820         // DGVar will conflict with NewGA because they both had the same
821         // name. We must erase this now so ForceRenaming doesn't assert
822         // because DGV might not have internal linkage.
823         DGVar->eraseFromParent();
824
825         // Proceed to 'common' steps
826       } else
827         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
828                      "': symbol multiple defined");
829     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
830       // The only allowed way is to link alias with external declaration or weak
831       // symbol...
832       if (DF->isDeclaration() || DF->isWeakForLinker()) {
833         // But only if aliasee is function too...
834         if (!isa<Function>(DAliasee))
835           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
836                        "': aliasee is not function");
837
838         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
839                                 SGA->getName(), DAliasee, Dest);
840         CopyGVAttributes(NewGA, SGA);
841
842         // Any uses of DF need to change to NewGA, with cast, if needed.
843         if (SGA->getType() != DF->getType())
844           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
845                                                           DF->getType()));
846         else
847           DF->replaceAllUsesWith(NewGA);
848
849         // DF will conflict with NewGA because they both had the same
850         // name. We must erase this now so ForceRenaming doesn't assert
851         // because DF might not have internal linkage.
852         DF->eraseFromParent();
853
854         // Proceed to 'common' steps
855       } else
856         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
857                      "': symbol multiple defined");
858     } else {
859       // No linking to be performed, simply create an identical version of the
860       // alias over in the dest module...
861
862       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
863                               SGA->getName(), DAliasee, Dest);
864       CopyGVAttributes(NewGA, SGA);
865
866       // Proceed to 'common' steps
867     }
868
869     assert(NewGA && "No alias was created in destination module!");
870
871     // If the symbol table renamed the alias, but it is an externally visible
872     // symbol, DGA must be an global value with internal linkage. Rename it.
873     if (NewGA->getName() != SGA->getName() &&
874         !NewGA->hasLocalLinkage())
875       ForceRenaming(NewGA, SGA->getName());
876
877     // Remember this mapping so uses in the source module get remapped
878     // later by RemapOperand.
879     ValueMap[SGA] = NewGA;
880   }
881
882   return false;
883 }
884
885
886 // LinkGlobalInits - Update the initializers in the Dest module now that all
887 // globals that may be referenced are in Dest.
888 static bool LinkGlobalInits(Module *Dest, const Module *Src,
889                             std::map<const Value*, Value*> &ValueMap,
890                             std::string *Err) {
891   // Loop over all of the globals in the src module, mapping them over as we go
892   for (Module::const_global_iterator I = Src->global_begin(),
893        E = Src->global_end(); I != E; ++I) {
894     const GlobalVariable *SGV = I;
895
896     if (SGV->hasInitializer()) {      // Only process initialized GV's
897       // Figure out what the initializer looks like in the dest module...
898       Constant *SInit =
899         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
900                        Dest->getContext()));
901       // Grab destination global variable or alias.
902       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
903
904       // If dest if global variable, check that initializers match.
905       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
906         if (DGVar->hasInitializer()) {
907           if (SGV->hasExternalLinkage()) {
908             if (DGVar->getInitializer() != SInit)
909               return Error(Err, "Global Variable Collision on '" +
910                            SGV->getName() +
911                            "': global variables have different initializers");
912           } else if (DGVar->isWeakForLinker()) {
913             // Nothing is required, mapped values will take the new global
914             // automatically.
915           } else if (SGV->isWeakForLinker()) {
916             // Nothing is required, mapped values will take the new global
917             // automatically.
918           } else if (DGVar->hasAppendingLinkage()) {
919             llvm_unreachable("Appending linkage unimplemented!");
920           } else {
921             llvm_unreachable("Unknown linkage!");
922           }
923         } else {
924           // Copy the initializer over now...
925           DGVar->setInitializer(SInit);
926         }
927       } else {
928         // Destination is alias, the only valid situation is when source is
929         // weak. Also, note, that we already checked linkage in LinkGlobals(),
930         // thus we assert here.
931         // FIXME: Should we weaken this assumption, 'dereference' alias and
932         // check for initializer of aliasee?
933         assert(SGV->isWeakForLinker());
934       }
935     }
936   }
937   return false;
938 }
939
940 // LinkFunctionProtos - Link the functions together between the two modules,
941 // without doing function bodies... this just adds external function prototypes
942 // to the Dest function...
943 //
944 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
945                                std::map<const Value*, Value*> &ValueMap,
946                                std::string *Err) {
947   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
948
949   // Loop over all of the functions in the src module, mapping them over
950   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
951     const Function *SF = I;   // SrcFunction
952     GlobalValue *DGV = 0;
953
954     // Check to see if may have to link the function with the global, alias or
955     // function.
956     if (SF->hasName() && !SF->hasLocalLinkage())
957       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
958
959     // If we found a global with the same name in the dest module, but it has
960     // internal linkage, we are really not doing any linkage here.
961     if (DGV && DGV->hasLocalLinkage())
962       DGV = 0;
963
964     // If types don't agree due to opaque types, try to resolve them.
965     if (DGV && DGV->getType() != SF->getType())
966       RecursiveResolveTypes(SF->getType(), DGV->getType());
967
968     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
969     bool LinkFromSrc = false;
970     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
971       return true;
972
973     // If there is no linkage to be performed, just bring over SF without
974     // modifying it.
975     if (DGV == 0) {
976       // Function does not already exist, simply insert an function signature
977       // identical to SF into the dest module.
978       Function *NewDF = Function::Create(SF->getFunctionType(),
979                                          SF->getLinkage(),
980                                          SF->getName(), Dest);
981       CopyGVAttributes(NewDF, SF);
982
983       // If the LLVM runtime renamed the function, but it is an externally
984       // visible symbol, DF must be an existing function with internal linkage.
985       // Rename it.
986       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
987         ForceRenaming(NewDF, SF->getName());
988
989       // ... and remember this mapping...
990       ValueMap[SF] = NewDF;
991       continue;
992     }
993
994     // If the visibilities of the symbols disagree and the destination is a
995     // prototype, take the visibility of its input.
996     if (DGV->isDeclaration())
997       DGV->setVisibility(SF->getVisibility());
998
999     if (LinkFromSrc) {
1000       if (isa<GlobalAlias>(DGV))
1001         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1002                      "': symbol multiple defined");
1003
1004       // We have a definition of the same name but different type in the
1005       // source module. Copy the prototype to the destination and replace
1006       // uses of the destination's prototype with the new prototype.
1007       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1008                                          SF->getName(), Dest);
1009       CopyGVAttributes(NewDF, SF);
1010
1011       // Any uses of DF need to change to NewDF, with cast
1012       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, 
1013                                                               DGV->getType()));
1014
1015       // DF will conflict with NewDF because they both had the same. We must
1016       // erase this now so ForceRenaming doesn't assert because DF might
1017       // not have internal linkage.
1018       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1019         Var->eraseFromParent();
1020       else
1021         cast<Function>(DGV)->eraseFromParent();
1022
1023       // If the symbol table renamed the function, but it is an externally
1024       // visible symbol, DF must be an existing function with internal
1025       // linkage.  Rename it.
1026       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
1027         ForceRenaming(NewDF, SF->getName());
1028
1029       // Remember this mapping so uses in the source module get remapped
1030       // later by RemapOperand.
1031       ValueMap[SF] = NewDF;
1032       continue;
1033     }
1034
1035     // Not "link from source", keep the one in the DestModule and remap the
1036     // input onto it.
1037
1038     if (isa<GlobalAlias>(DGV)) {
1039       // The only valid mappings are:
1040       // - SF is external declaration, which is effectively a no-op.
1041       // - SF is weak, when we just need to throw SF out.
1042       if (!SF->isDeclaration() && !SF->isWeakForLinker())
1043         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1044                      "': symbol multiple defined");
1045     }
1046
1047     // Set calculated linkage
1048     DGV->setLinkage(NewLinkage);
1049
1050     // Make sure to remember this mapping.
1051     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1052   }
1053   return false;
1054 }
1055
1056 // LinkFunctionBody - Copy the source function over into the dest function and
1057 // fix up references to values.  At this point we know that Dest is an external
1058 // function, and that Src is not.
1059 static bool LinkFunctionBody(Function *Dest, Function *Src,
1060                              std::map<const Value*, Value*> &ValueMap,
1061                              std::string *Err) {
1062   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1063
1064   // Go through and convert function arguments over, remembering the mapping.
1065   Function::arg_iterator DI = Dest->arg_begin();
1066   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1067        I != E; ++I, ++DI) {
1068     DI->setName(I->getName());  // Copy the name information over...
1069
1070     // Add a mapping to our local map
1071     ValueMap[I] = DI;
1072   }
1073
1074   // Splice the body of the source function into the dest function.
1075   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1076
1077   // At this point, all of the instructions and values of the function are now
1078   // copied over.  The only problem is that they are still referencing values in
1079   // the Source function as operands.  Loop through all of the operands of the
1080   // functions and patch them up to point to the local versions...
1081   //
1082   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1083     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1084       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1085            OI != OE; ++OI)
1086         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1087           *OI = RemapOperand(*OI, ValueMap, Dest->getContext());
1088
1089   // There is no need to map the arguments anymore.
1090   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1091        I != E; ++I)
1092     ValueMap.erase(I);
1093
1094   return false;
1095 }
1096
1097
1098 // LinkFunctionBodies - Link in the function bodies that are defined in the
1099 // source module into the DestModule.  This consists basically of copying the
1100 // function over and fixing up references to values.
1101 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1102                                std::map<const Value*, Value*> &ValueMap,
1103                                std::string *Err) {
1104
1105   // Loop over all of the functions in the src module, mapping them over as we
1106   // go
1107   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1108     if (!SF->isDeclaration()) {               // No body if function is external
1109       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1110
1111       // DF not external SF external?
1112       if (DF && DF->isDeclaration())
1113         // Only provide the function body if there isn't one already.
1114         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1115           return true;
1116     }
1117   }
1118   return false;
1119 }
1120
1121 // LinkAppendingVars - If there were any appending global variables, link them
1122 // together now.  Return true on error.
1123 static bool LinkAppendingVars(Module *M,
1124                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1125                               std::string *ErrorMsg) {
1126   if (AppendingVars.empty()) return false; // Nothing to do.
1127
1128   // Loop over the multimap of appending vars, processing any variables with the
1129   // same name, forming a new appending global variable with both of the
1130   // initializers merged together, then rewrite references to the old variables
1131   // and delete them.
1132   std::vector<Constant*> Inits;
1133   while (AppendingVars.size() > 1) {
1134     // Get the first two elements in the map...
1135     std::multimap<std::string,
1136       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1137
1138     // If the first two elements are for different names, there is no pair...
1139     // Otherwise there is a pair, so link them together...
1140     if (First->first == Second->first) {
1141       GlobalVariable *G1 = First->second, *G2 = Second->second;
1142       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1143       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1144
1145       // Check to see that they two arrays agree on type...
1146       if (T1->getElementType() != T2->getElementType())
1147         return Error(ErrorMsg,
1148          "Appending variables with different element types need to be linked!");
1149       if (G1->isConstant() != G2->isConstant())
1150         return Error(ErrorMsg,
1151                      "Appending variables linked with different const'ness!");
1152
1153       if (G1->getAlignment() != G2->getAlignment())
1154         return Error(ErrorMsg,
1155          "Appending variables with different alignment need to be linked!");
1156
1157       if (G1->getVisibility() != G2->getVisibility())
1158         return Error(ErrorMsg,
1159          "Appending variables with different visibility need to be linked!");
1160
1161       if (G1->getSection() != G2->getSection())
1162         return Error(ErrorMsg,
1163          "Appending variables with different section name need to be linked!");
1164
1165       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1166       ArrayType *NewType = ArrayType::get(T1->getElementType(), 
1167                                                          NewSize);
1168
1169       G1->setName("");   // Clear G1's name in case of a conflict!
1170
1171       // Create the new global variable...
1172       GlobalVariable *NG =
1173         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1174                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1175                            G1->getType()->getAddressSpace());
1176
1177       // Propagate alignment, visibility and section info.
1178       CopyGVAttributes(NG, G1);
1179
1180       // Merge the initializer...
1181       Inits.reserve(NewSize);
1182       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1183         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1184           Inits.push_back(I->getOperand(i));
1185       } else {
1186         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1187         Constant *CV = Constant::getNullValue(T1->getElementType());
1188         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1189           Inits.push_back(CV);
1190       }
1191       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1192         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1193           Inits.push_back(I->getOperand(i));
1194       } else {
1195         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1196         Constant *CV = Constant::getNullValue(T2->getElementType());
1197         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1198           Inits.push_back(CV);
1199       }
1200       NG->setInitializer(ConstantArray::get(NewType, Inits));
1201       Inits.clear();
1202
1203       // Replace any uses of the two global variables with uses of the new
1204       // global...
1205
1206       // FIXME: This should rewrite simple/straight-forward uses such as
1207       // getelementptr instructions to not use the Cast!
1208       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1209                              G1->getType()));
1210       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 
1211                              G2->getType()));
1212
1213       // Remove the two globals from the module now...
1214       M->getGlobalList().erase(G1);
1215       M->getGlobalList().erase(G2);
1216
1217       // Put the new global into the AppendingVars map so that we can handle
1218       // linking of more than two vars...
1219       Second->second = NG;
1220     }
1221     AppendingVars.erase(First);
1222   }
1223
1224   return false;
1225 }
1226
1227 static bool ResolveAliases(Module *Dest) {
1228   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1229        I != E; ++I)
1230     if (const GlobalValue *GV = I->resolveAliasedGlobal())
1231       if (GV != I && !GV->isDeclaration())
1232         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
1233
1234   return false;
1235 }
1236
1237 // LinkModules - This function links two modules together, with the resulting
1238 // left module modified to be the composite of the two input modules.  If an
1239 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1240 // the problem.  Upon failure, the Dest module could be in a modified state, and
1241 // shouldn't be relied on to be consistent.
1242 bool
1243 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1244   assert(Dest != 0 && "Invalid Destination module");
1245   assert(Src  != 0 && "Invalid Source Module");
1246
1247   if (Dest->getDataLayout().empty()) {
1248     if (!Src->getDataLayout().empty()) {
1249       Dest->setDataLayout(Src->getDataLayout());
1250     } else {
1251       std::string DataLayout;
1252
1253       if (Dest->getEndianness() == Module::AnyEndianness) {
1254         if (Src->getEndianness() == Module::BigEndian)
1255           DataLayout.append("E");
1256         else if (Src->getEndianness() == Module::LittleEndian)
1257           DataLayout.append("e");
1258       }
1259
1260       if (Dest->getPointerSize() == Module::AnyPointerSize) {
1261         if (Src->getPointerSize() == Module::Pointer64)
1262           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1263         else if (Src->getPointerSize() == Module::Pointer32)
1264           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1265       }
1266       Dest->setDataLayout(DataLayout);
1267     }
1268   }
1269
1270   // Copy the target triple from the source to dest if the dest's is empty.
1271   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1272     Dest->setTargetTriple(Src->getTargetTriple());
1273
1274   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1275       Src->getDataLayout() != Dest->getDataLayout())
1276     errs() << "WARNING: Linking two modules of different data layouts!\n";
1277   if (!Src->getTargetTriple().empty() &&
1278       Dest->getTargetTriple() != Src->getTargetTriple())
1279     errs() << "WARNING: Linking two modules of different target triples!\n";
1280
1281   // Append the module inline asm string.
1282   if (!Src->getModuleInlineAsm().empty()) {
1283     if (Dest->getModuleInlineAsm().empty())
1284       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1285     else
1286       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1287                                Src->getModuleInlineAsm());
1288   }
1289
1290   // Update the destination module's dependent libraries list with the libraries
1291   // from the source module. There's no opportunity for duplicates here as the
1292   // Module ensures that duplicate insertions are discarded.
1293   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1294        SI != SE; ++SI)
1295     Dest->addLibrary(*SI);
1296
1297   // LinkTypes - Go through the symbol table of the Src module and see if any
1298   // types are named in the src module that are not named in the Dst module.
1299   // Make sure there are no type name conflicts.
1300   if (LinkTypes(Dest, Src, ErrorMsg))
1301     return true;
1302
1303   // ValueMap - Mapping of values from what they used to be in Src, to what they
1304   // are now in Dest.
1305   std::map<const Value*, Value*> ValueMap;
1306
1307   // AppendingVars - Keep track of global variables in the destination module
1308   // with appending linkage.  After the module is linked together, they are
1309   // appended and the module is rewritten.
1310   std::multimap<std::string, GlobalVariable *> AppendingVars;
1311   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1312        I != E; ++I) {
1313     // Add all of the appending globals already in the Dest module to
1314     // AppendingVars.
1315     if (I->hasAppendingLinkage())
1316       AppendingVars.insert(std::make_pair(I->getName(), I));
1317   }
1318
1319   // Insert all of the named mdnoes in Src into the Dest module.
1320   LinkNamedMDNodes(Dest, Src);
1321
1322   // Insert all of the globals in src into the Dest module... without linking
1323   // initializers (which could refer to functions not yet mapped over).
1324   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1325     return true;
1326
1327   // Link the functions together between the two modules, without doing function
1328   // bodies... this just adds external function prototypes to the Dest
1329   // function...  We do this so that when we begin processing function bodies,
1330   // all of the global values that may be referenced are available in our
1331   // ValueMap.
1332   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1333     return true;
1334
1335   // If there were any alias, link them now. We really need to do this now,
1336   // because all of the aliases that may be referenced need to be available in
1337   // ValueMap
1338   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1339
1340   // Update the initializers in the Dest module now that all globals that may
1341   // be referenced are in Dest.
1342   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1343
1344   // Link in the function bodies that are defined in the source module into the
1345   // DestModule.  This consists basically of copying the function over and
1346   // fixing up references to values.
1347   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1348
1349   // If there were any appending global variables, link them together now.
1350   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1351
1352   // Resolve all uses of aliases with aliasees
1353   if (ResolveAliases(Dest)) return true;
1354
1355   // If the source library's module id is in the dependent library list of the
1356   // destination library, remove it since that module is now linked in.
1357   sys::Path modId;
1358   modId.set(Src->getModuleIdentifier());
1359   if (!modId.isEmpty())
1360     Dest->removeLibrary(modId.getBasename());
1361
1362   return false;
1363 }
1364
1365 // vim: sw=2