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