LinkModules.cpp revision 7bf5cf401f27ac7cafe3e2c097cf14b7bb30a653
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/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/System/Path.h"
32#include "llvm/ADT/DenseMap.h"
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    dbgs() << "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    dbgs() << " Fr: " << (void*)I->first << " ";
342    I->first->dump();
343    dbgs() << " To: " << (void*)I->second << " ";
344    I->second->dump();
345    dbgs() << "\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  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      Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
370    } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
371      std::vector<Constant*> Operands(CPS->getNumOperands());
372      for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
373        Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
374      Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
375    } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
376      Result = const_cast<Constant*>(CPV);
377    } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
378      std::vector<Constant*> Operands(CP->getNumOperands());
379      for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
380        Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
381      Result = ConstantVector::get(Operands);
382    } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
383      std::vector<Constant*> Ops;
384      for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
385        Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
386      Result = CE->getWithOperands(Ops);
387    } else if (const BlockAddress *CE = dyn_cast<BlockAddress>(CPV)) {
388      Result = BlockAddress::get(
389                 cast<Function>(RemapOperand(CE->getFunction(), ValueMap)),
390                                 CE->getBasicBlock());
391    } else {
392      assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
393      llvm_unreachable("Unknown type of derived type constant value!");
394    }
395  } else if (const MDNode *MD = dyn_cast<MDNode>(In)) {
396    if (MD->isFunctionLocal()) {
397      SmallVector<Value*, 4> Elts;
398      for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
399        Elts.push_back(RemapOperand(MD->getOperand(i), ValueMap));
400      Result = MDNode::get(In->getContext(), Elts.data(), MD->getNumOperands());
401    } else {
402      Result = const_cast<Value*>(In);
403    }
404  } else if (isa<MDString>(In) || isa<InlineAsm>(In) || isa<Instruction>(In)) {
405    Result = const_cast<Value*>(In);
406  }
407
408  // Cache the mapping in our local map structure
409  if (Result) {
410    ValueMap[In] = Result;
411    return Result;
412  }
413
414#ifndef NDEBUG
415  dbgs() << "LinkModules ValueMap: \n";
416  PrintMap(ValueMap);
417
418  dbgs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
419  llvm_unreachable("Couldn't remap value!");
420#endif
421  return 0;
422}
423
424/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
425/// in the symbol table.  This is good for all clients except for us.  Go
426/// through the trouble to force this back.
427static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
428  assert(GV->getName() != Name && "Can't force rename to self");
429  ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
430
431  // If there is a conflict, rename the conflict.
432  if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
433    assert(ConflictGV->hasLocalLinkage() &&
434           "Not conflicting with a static global, should link instead!");
435    GV->takeName(ConflictGV);
436    ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
437    assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
438  } else {
439    GV->setName(Name);              // Force the name back
440  }
441}
442
443/// CopyGVAttributes - copy additional attributes (those not needed to construct
444/// a GlobalValue) from the SrcGV to the DestGV.
445static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
446  // Use the maximum alignment, rather than just copying the alignment of SrcGV.
447  unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
448  DestGV->copyAttributesFrom(SrcGV);
449  DestGV->setAlignment(Alignment);
450}
451
452/// GetLinkageResult - This analyzes the two global values and determines what
453/// the result will look like in the destination module.  In particular, it
454/// computes the resultant linkage type, computes whether the global in the
455/// source should be copied over to the destination (replacing the existing
456/// one), and computes whether this linkage is an error or not. It also performs
457/// visibility checks: we cannot link together two symbols with different
458/// visibilities.
459static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
460                             GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
461                             std::string *Err) {
462  assert((!Dest || !Src->hasLocalLinkage()) &&
463         "If Src has internal linkage, Dest shouldn't be set!");
464  if (!Dest) {
465    // Linking something to nothing.
466    LinkFromSrc = true;
467    LT = Src->getLinkage();
468  } else if (Src->isDeclaration()) {
469    // If Src is external or if both Src & Dest are external..  Just link the
470    // external globals, we aren't adding anything.
471    if (Src->hasDLLImportLinkage()) {
472      // If one of GVs has DLLImport linkage, result should be dllimport'ed.
473      if (Dest->isDeclaration()) {
474        LinkFromSrc = true;
475        LT = Src->getLinkage();
476      }
477    } else if (Dest->hasExternalWeakLinkage()) {
478      // If the Dest is weak, use the source linkage.
479      LinkFromSrc = true;
480      LT = Src->getLinkage();
481    } else {
482      LinkFromSrc = false;
483      LT = Dest->getLinkage();
484    }
485  } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
486    // If Dest is external but Src is not:
487    LinkFromSrc = true;
488    LT = Src->getLinkage();
489  } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
490    if (Src->getLinkage() != Dest->getLinkage())
491      return Error(Err, "Linking globals named '" + Src->getName() +
492            "': can only link appending global with another appending global!");
493    LinkFromSrc = true; // Special cased.
494    LT = Src->getLinkage();
495  } else if (Src->isWeakForLinker()) {
496    // At this point we know that Dest has LinkOnce, External*, Weak, Common,
497    // or DLL* linkage.
498    if (Dest->hasExternalWeakLinkage() ||
499        Dest->hasAvailableExternallyLinkage() ||
500        (Dest->hasLinkOnceLinkage() &&
501         (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
502      LinkFromSrc = true;
503      LT = Src->getLinkage();
504    } else {
505      LinkFromSrc = false;
506      LT = Dest->getLinkage();
507    }
508  } else if (Dest->isWeakForLinker()) {
509    // At this point we know that Src has External* or DLL* linkage.
510    if (Src->hasExternalWeakLinkage()) {
511      LinkFromSrc = false;
512      LT = Dest->getLinkage();
513    } else {
514      LinkFromSrc = true;
515      LT = GlobalValue::ExternalLinkage;
516    }
517  } else {
518    assert((Dest->hasExternalLinkage() ||
519            Dest->hasDLLImportLinkage() ||
520            Dest->hasDLLExportLinkage() ||
521            Dest->hasExternalWeakLinkage()) &&
522           (Src->hasExternalLinkage() ||
523            Src->hasDLLImportLinkage() ||
524            Src->hasDLLExportLinkage() ||
525            Src->hasExternalWeakLinkage()) &&
526           "Unexpected linkage type!");
527    return Error(Err, "Linking globals named '" + Src->getName() +
528                 "': symbol multiply defined!");
529  }
530
531  // Check visibility
532  if (Dest && Src->getVisibility() != Dest->getVisibility())
533    if (!Src->isDeclaration() && !Dest->isDeclaration())
534      return Error(Err, "Linking globals named '" + Src->getName() +
535                   "': symbols have different visibilities!");
536  return false;
537}
538
539// Insert all of the named mdnoes in Src into the Dest module.
540static void LinkNamedMDNodes(Module *Dest, Module *Src) {
541  for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
542         E = Src->named_metadata_end(); I != E; ++I) {
543    const NamedMDNode *SrcNMD = I;
544    NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
545    if (!DestNMD)
546      NamedMDNode::Create(SrcNMD, Dest);
547    else {
548      // Add Src elements into Dest node.
549      for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
550        DestNMD->addOperand(SrcNMD->getOperand(i));
551    }
552  }
553}
554
555// LinkGlobals - Loop through the global variables in the src module and merge
556// them into the dest module.
557static bool LinkGlobals(Module *Dest, const Module *Src,
558                        std::map<const Value*, Value*> &ValueMap,
559                    std::multimap<std::string, GlobalVariable *> &AppendingVars,
560                        std::string *Err) {
561  ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
562
563  // Loop over all of the globals in the src module, mapping them over as we go
564  for (Module::const_global_iterator I = Src->global_begin(),
565       E = Src->global_end(); I != E; ++I) {
566    const GlobalVariable *SGV = I;
567    GlobalValue *DGV = 0;
568
569    // Check to see if may have to link the global with the global, alias or
570    // function.
571    if (SGV->hasName() && !SGV->hasLocalLinkage())
572      DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
573
574    // If we found a global with the same name in the dest module, but it has
575    // internal linkage, we are really not doing any linkage here.
576    if (DGV && DGV->hasLocalLinkage())
577      DGV = 0;
578
579    // If types don't agree due to opaque types, try to resolve them.
580    if (DGV && DGV->getType() != SGV->getType())
581      RecursiveResolveTypes(SGV->getType(), DGV->getType());
582
583    assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
584            SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
585           "Global must either be external or have an initializer!");
586
587    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
588    bool LinkFromSrc = false;
589    if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
590      return true;
591
592    if (DGV == 0) {
593      // No linking to be performed, simply create an identical version of the
594      // symbol over in the dest module... the initializer will be filled in
595      // later by LinkGlobalInits.
596      GlobalVariable *NewDGV =
597        new GlobalVariable(*Dest, SGV->getType()->getElementType(),
598                           SGV->isConstant(), SGV->getLinkage(), /*init*/0,
599                           SGV->getName(), 0, false,
600                           SGV->getType()->getAddressSpace());
601      // Propagate alignment, visibility and section info.
602      CopyGVAttributes(NewDGV, SGV);
603
604      // If the LLVM runtime renamed the global, but it is an externally visible
605      // symbol, DGV must be an existing global with internal linkage.  Rename
606      // it.
607      if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
608        ForceRenaming(NewDGV, SGV->getName());
609
610      // Make sure to remember this mapping.
611      ValueMap[SGV] = NewDGV;
612
613      // Keep track that this is an appending variable.
614      if (SGV->hasAppendingLinkage())
615        AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
616      continue;
617    }
618
619    // If the visibilities of the symbols disagree and the destination is a
620    // prototype, take the visibility of its input.
621    if (DGV->isDeclaration())
622      DGV->setVisibility(SGV->getVisibility());
623
624    if (DGV->hasAppendingLinkage()) {
625      // No linking is performed yet.  Just insert a new copy of the global, and
626      // keep track of the fact that it is an appending variable in the
627      // AppendingVars map.  The name is cleared out so that no linkage is
628      // performed.
629      GlobalVariable *NewDGV =
630        new GlobalVariable(*Dest, SGV->getType()->getElementType(),
631                           SGV->isConstant(), SGV->getLinkage(), /*init*/0,
632                           "", 0, false,
633                           SGV->getType()->getAddressSpace());
634
635      // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
636      NewDGV->setAlignment(DGV->getAlignment());
637      // Propagate alignment, section and visibility info.
638      CopyGVAttributes(NewDGV, SGV);
639
640      // Make sure to remember this mapping...
641      ValueMap[SGV] = NewDGV;
642
643      // Keep track that this is an appending variable...
644      AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
645      continue;
646    }
647
648    if (LinkFromSrc) {
649      if (isa<GlobalAlias>(DGV))
650        return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
651                     "': symbol multiple defined");
652
653      // If the types don't match, and if we are to link from the source, nuke
654      // DGV and create a new one of the appropriate type.  Note that the thing
655      // we are replacing may be a function (if a prototype, weak, etc) or a
656      // global variable.
657      GlobalVariable *NewDGV =
658        new GlobalVariable(*Dest, SGV->getType()->getElementType(),
659                           SGV->isConstant(), NewLinkage, /*init*/0,
660                           DGV->getName(), 0, false,
661                           SGV->getType()->getAddressSpace());
662
663      // Propagate alignment, section, and visibility info.
664      CopyGVAttributes(NewDGV, SGV);
665      DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
666                                                              DGV->getType()));
667
668      // DGV will conflict with NewDGV because they both had the same
669      // name. We must erase this now so ForceRenaming doesn't assert
670      // because DGV might not have internal linkage.
671      if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
672        Var->eraseFromParent();
673      else
674        cast<Function>(DGV)->eraseFromParent();
675
676      // If the symbol table renamed the global, but it is an externally visible
677      // symbol, DGV must be an existing global with internal linkage.  Rename.
678      if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
679        ForceRenaming(NewDGV, SGV->getName());
680
681      // Inherit const as appropriate.
682      NewDGV->setConstant(SGV->isConstant());
683
684      // Make sure to remember this mapping.
685      ValueMap[SGV] = NewDGV;
686      continue;
687    }
688
689    // Not "link from source", keep the one in the DestModule and remap the
690    // input onto it.
691
692    // Special case for const propagation.
693    if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
694      if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
695        DGVar->setConstant(true);
696
697    // SGV is global, but DGV is alias.
698    if (isa<GlobalAlias>(DGV)) {
699      // The only valid mappings are:
700      // - SGV is external declaration, which is effectively a no-op.
701      // - SGV is weak, when we just need to throw SGV out.
702      if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
703        return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
704                     "': symbol multiple defined");
705    }
706
707    // Set calculated linkage
708    DGV->setLinkage(NewLinkage);
709
710    // Make sure to remember this mapping...
711    ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
712  }
713  return false;
714}
715
716static GlobalValue::LinkageTypes
717CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
718  GlobalValue::LinkageTypes SL = SGV->getLinkage();
719  GlobalValue::LinkageTypes DL = DGV->getLinkage();
720  if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
721    return GlobalValue::ExternalLinkage;
722  else if (SL == GlobalValue::WeakAnyLinkage ||
723           DL == GlobalValue::WeakAnyLinkage)
724    return GlobalValue::WeakAnyLinkage;
725  else if (SL == GlobalValue::WeakODRLinkage ||
726           DL == GlobalValue::WeakODRLinkage)
727    return GlobalValue::WeakODRLinkage;
728  else if (SL == GlobalValue::InternalLinkage &&
729           DL == GlobalValue::InternalLinkage)
730    return GlobalValue::InternalLinkage;
731  else if (SL == GlobalValue::LinkerPrivateLinkage &&
732           DL == GlobalValue::LinkerPrivateLinkage)
733    return GlobalValue::LinkerPrivateLinkage;
734  else {
735    assert (SL == GlobalValue::PrivateLinkage &&
736            DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
737    return GlobalValue::PrivateLinkage;
738  }
739}
740
741// LinkAlias - Loop through the alias in the src module and link them into the
742// dest module. We're assuming, that all functions/global variables were already
743// linked in.
744static bool LinkAlias(Module *Dest, const Module *Src,
745                      std::map<const Value*, Value*> &ValueMap,
746                      std::string *Err) {
747  // Loop over all alias in the src module
748  for (Module::const_alias_iterator I = Src->alias_begin(),
749         E = Src->alias_end(); I != E; ++I) {
750    const GlobalAlias *SGA = I;
751    const GlobalValue *SAliasee = SGA->getAliasedGlobal();
752    GlobalAlias *NewGA = NULL;
753
754    // Globals were already linked, thus we can just query ValueMap for variant
755    // of SAliasee in Dest.
756    std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
757    assert(VMI != ValueMap.end() && "Aliasee not linked");
758    GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
759    GlobalValue* DGV = NULL;
760
761    // Try to find something 'similar' to SGA in destination module.
762    if (!DGV && !SGA->hasLocalLinkage()) {
763      DGV = Dest->getNamedAlias(SGA->getName());
764
765      // If types don't agree due to opaque types, try to resolve them.
766      if (DGV && DGV->getType() != SGA->getType())
767        RecursiveResolveTypes(SGA->getType(), DGV->getType());
768    }
769
770    if (!DGV && !SGA->hasLocalLinkage()) {
771      DGV = Dest->getGlobalVariable(SGA->getName());
772
773      // If types don't agree due to opaque types, try to resolve them.
774      if (DGV && DGV->getType() != SGA->getType())
775        RecursiveResolveTypes(SGA->getType(), DGV->getType());
776    }
777
778    if (!DGV && !SGA->hasLocalLinkage()) {
779      DGV = Dest->getFunction(SGA->getName());
780
781      // If types don't agree due to opaque types, try to resolve them.
782      if (DGV && DGV->getType() != SGA->getType())
783        RecursiveResolveTypes(SGA->getType(), DGV->getType());
784    }
785
786    // No linking to be performed on internal stuff.
787    if (DGV && DGV->hasLocalLinkage())
788      DGV = NULL;
789
790    if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
791      // Types are known to be the same, check whether aliasees equal. As
792      // globals are already linked we just need query ValueMap to find the
793      // mapping.
794      if (DAliasee == DGA->getAliasedGlobal()) {
795        // This is just two copies of the same alias. Propagate linkage, if
796        // necessary.
797        DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
798
799        NewGA = DGA;
800        // Proceed to 'common' steps
801      } else
802        return Error(Err, "Alias Collision on '"  + SGA->getName()+
803                     "': aliases have different aliasees");
804    } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
805      // The only allowed way is to link alias with external declaration or weak
806      // symbol..
807      if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
808        // But only if aliasee is global too...
809        if (!isa<GlobalVariable>(DAliasee))
810          return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
811                       "': aliasee is not global variable");
812
813        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
814                                SGA->getName(), DAliasee, Dest);
815        CopyGVAttributes(NewGA, SGA);
816
817        // Any uses of DGV need to change to NewGA, with cast, if needed.
818        if (SGA->getType() != DGVar->getType())
819          DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
820                                                             DGVar->getType()));
821        else
822          DGVar->replaceAllUsesWith(NewGA);
823
824        // DGVar will conflict with NewGA because they both had the same
825        // name. We must erase this now so ForceRenaming doesn't assert
826        // because DGV might not have internal linkage.
827        DGVar->eraseFromParent();
828
829        // Proceed to 'common' steps
830      } else
831        return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
832                     "': symbol multiple defined");
833    } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
834      // The only allowed way is to link alias with external declaration or weak
835      // symbol...
836      if (DF->isDeclaration() || DF->isWeakForLinker()) {
837        // But only if aliasee is function too...
838        if (!isa<Function>(DAliasee))
839          return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
840                       "': aliasee is not function");
841
842        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
843                                SGA->getName(), DAliasee, Dest);
844        CopyGVAttributes(NewGA, SGA);
845
846        // Any uses of DF need to change to NewGA, with cast, if needed.
847        if (SGA->getType() != DF->getType())
848          DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
849                                                          DF->getType()));
850        else
851          DF->replaceAllUsesWith(NewGA);
852
853        // DF will conflict with NewGA because they both had the same
854        // name. We must erase this now so ForceRenaming doesn't assert
855        // because DF might not have internal linkage.
856        DF->eraseFromParent();
857
858        // Proceed to 'common' steps
859      } else
860        return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
861                     "': symbol multiple defined");
862    } else {
863      // No linking to be performed, simply create an identical version of the
864      // alias over in the dest module...
865      Constant *Aliasee = DAliasee;
866      // Fixup aliases to bitcasts.  Note that aliases to GEPs are still broken
867      // by this, but aliases to GEPs are broken to a lot of other things, so
868      // it's less important.
869      if (SGA->getType() != DAliasee->getType())
870        Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
871      NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
872                              SGA->getName(), Aliasee, Dest);
873      CopyGVAttributes(NewGA, SGA);
874
875      // Proceed to 'common' steps
876    }
877
878    assert(NewGA && "No alias was created in destination module!");
879
880    // If the symbol table renamed the alias, but it is an externally visible
881    // symbol, DGA must be an global value with internal linkage. Rename it.
882    if (NewGA->getName() != SGA->getName() &&
883        !NewGA->hasLocalLinkage())
884      ForceRenaming(NewGA, SGA->getName());
885
886    // Remember this mapping so uses in the source module get remapped
887    // later by RemapOperand.
888    ValueMap[SGA] = NewGA;
889  }
890
891  return false;
892}
893
894
895// LinkGlobalInits - Update the initializers in the Dest module now that all
896// globals that may be referenced are in Dest.
897static bool LinkGlobalInits(Module *Dest, const Module *Src,
898                            std::map<const Value*, Value*> &ValueMap,
899                            std::string *Err) {
900  // Loop over all of the globals in the src module, mapping them over as we go
901  for (Module::const_global_iterator I = Src->global_begin(),
902       E = Src->global_end(); I != E; ++I) {
903    const GlobalVariable *SGV = I;
904
905    if (SGV->hasInitializer()) {      // Only process initialized GV's
906      // Figure out what the initializer looks like in the dest module...
907      Constant *SInit =
908        cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
909      // Grab destination global variable or alias.
910      GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
911
912      // If dest if global variable, check that initializers match.
913      if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
914        if (DGVar->hasInitializer()) {
915          if (SGV->hasExternalLinkage()) {
916            if (DGVar->getInitializer() != SInit)
917              return Error(Err, "Global Variable Collision on '" +
918                           SGV->getName() +
919                           "': global variables have different initializers");
920          } else if (DGVar->isWeakForLinker()) {
921            // Nothing is required, mapped values will take the new global
922            // automatically.
923          } else if (SGV->isWeakForLinker()) {
924            // Nothing is required, mapped values will take the new global
925            // automatically.
926          } else if (DGVar->hasAppendingLinkage()) {
927            llvm_unreachable("Appending linkage unimplemented!");
928          } else {
929            llvm_unreachable("Unknown linkage!");
930          }
931        } else {
932          // Copy the initializer over now...
933          DGVar->setInitializer(SInit);
934        }
935      } else {
936        // Destination is alias, the only valid situation is when source is
937        // weak. Also, note, that we already checked linkage in LinkGlobals(),
938        // thus we assert here.
939        // FIXME: Should we weaken this assumption, 'dereference' alias and
940        // check for initializer of aliasee?
941        assert(SGV->isWeakForLinker());
942      }
943    }
944  }
945  return false;
946}
947
948// LinkFunctionProtos - Link the functions together between the two modules,
949// without doing function bodies... this just adds external function prototypes
950// to the Dest function...
951//
952static bool LinkFunctionProtos(Module *Dest, const Module *Src,
953                               std::map<const Value*, Value*> &ValueMap,
954                               std::string *Err) {
955  ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
956
957  // Loop over all of the functions in the src module, mapping them over
958  for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
959    const Function *SF = I;   // SrcFunction
960    GlobalValue *DGV = 0;
961
962    // Check to see if may have to link the function with the global, alias or
963    // function.
964    if (SF->hasName() && !SF->hasLocalLinkage())
965      DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
966
967    // If we found a global with the same name in the dest module, but it has
968    // internal linkage, we are really not doing any linkage here.
969    if (DGV && DGV->hasLocalLinkage())
970      DGV = 0;
971
972    // If types don't agree due to opaque types, try to resolve them.
973    if (DGV && DGV->getType() != SF->getType())
974      RecursiveResolveTypes(SF->getType(), DGV->getType());
975
976    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
977    bool LinkFromSrc = false;
978    if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
979      return true;
980
981    // If there is no linkage to be performed, just bring over SF without
982    // modifying it.
983    if (DGV == 0) {
984      // Function does not already exist, simply insert an function signature
985      // identical to SF into the dest module.
986      Function *NewDF = Function::Create(SF->getFunctionType(),
987                                         SF->getLinkage(),
988                                         SF->getName(), Dest);
989      CopyGVAttributes(NewDF, SF);
990
991      // If the LLVM runtime renamed the function, but it is an externally
992      // visible symbol, DF must be an existing function with internal linkage.
993      // Rename it.
994      if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
995        ForceRenaming(NewDF, SF->getName());
996
997      // ... and remember this mapping...
998      ValueMap[SF] = NewDF;
999      continue;
1000    }
1001
1002    // If the visibilities of the symbols disagree and the destination is a
1003    // prototype, take the visibility of its input.
1004    if (DGV->isDeclaration())
1005      DGV->setVisibility(SF->getVisibility());
1006
1007    if (LinkFromSrc) {
1008      if (isa<GlobalAlias>(DGV))
1009        return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1010                     "': symbol multiple defined");
1011
1012      // We have a definition of the same name but different type in the
1013      // source module. Copy the prototype to the destination and replace
1014      // uses of the destination's prototype with the new prototype.
1015      Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1016                                         SF->getName(), Dest);
1017      CopyGVAttributes(NewDF, SF);
1018
1019      // Any uses of DF need to change to NewDF, with cast
1020      DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
1021                                                              DGV->getType()));
1022
1023      // DF will conflict with NewDF because they both had the same. We must
1024      // erase this now so ForceRenaming doesn't assert because DF might
1025      // not have internal linkage.
1026      if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1027        Var->eraseFromParent();
1028      else
1029        cast<Function>(DGV)->eraseFromParent();
1030
1031      // If the symbol table renamed the function, but it is an externally
1032      // visible symbol, DF must be an existing function with internal
1033      // linkage.  Rename it.
1034      if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
1035        ForceRenaming(NewDF, SF->getName());
1036
1037      // Remember this mapping so uses in the source module get remapped
1038      // later by RemapOperand.
1039      ValueMap[SF] = NewDF;
1040      continue;
1041    }
1042
1043    // Not "link from source", keep the one in the DestModule and remap the
1044    // input onto it.
1045
1046    if (isa<GlobalAlias>(DGV)) {
1047      // The only valid mappings are:
1048      // - SF is external declaration, which is effectively a no-op.
1049      // - SF is weak, when we just need to throw SF out.
1050      if (!SF->isDeclaration() && !SF->isWeakForLinker())
1051        return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1052                     "': symbol multiple defined");
1053    }
1054
1055    // Set calculated linkage
1056    DGV->setLinkage(NewLinkage);
1057
1058    // Make sure to remember this mapping.
1059    ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
1060  }
1061  return false;
1062}
1063
1064// LinkFunctionBody - Copy the source function over into the dest function and
1065// fix up references to values.  At this point we know that Dest is an external
1066// function, and that Src is not.
1067static bool LinkFunctionBody(Function *Dest, Function *Src,
1068                             std::map<const Value*, Value*> &ValueMap,
1069                             std::string *Err) {
1070  assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1071
1072  // Go through and convert function arguments over, remembering the mapping.
1073  Function::arg_iterator DI = Dest->arg_begin();
1074  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1075       I != E; ++I, ++DI) {
1076    DI->setName(I->getName());  // Copy the name information over...
1077
1078    // Add a mapping to our local map
1079    ValueMap[I] = DI;
1080  }
1081
1082  // Splice the body of the source function into the dest function.
1083  Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1084
1085  // At this point, all of the instructions and values of the function are now
1086  // copied over.  The only problem is that they are still referencing values in
1087  // the Source function as operands.  Loop through all of the operands of the
1088  // functions and patch them up to point to the local versions...
1089  //
1090  for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1091    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1092      for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1093           OI != OE; ++OI)
1094        if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1095          *OI = RemapOperand(*OI, ValueMap);
1096
1097  // There is no need to map the arguments anymore.
1098  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1099       I != E; ++I)
1100    ValueMap.erase(I);
1101
1102  return false;
1103}
1104
1105
1106// LinkFunctionBodies - Link in the function bodies that are defined in the
1107// source module into the DestModule.  This consists basically of copying the
1108// function over and fixing up references to values.
1109static bool LinkFunctionBodies(Module *Dest, Module *Src,
1110                               std::map<const Value*, Value*> &ValueMap,
1111                               std::string *Err) {
1112
1113  // Loop over all of the functions in the src module, mapping them over as we
1114  // go
1115  for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1116    if (!SF->isDeclaration()) {               // No body if function is external
1117      Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1118
1119      // DF not external SF external?
1120      if (DF && DF->isDeclaration())
1121        // Only provide the function body if there isn't one already.
1122        if (LinkFunctionBody(DF, SF, ValueMap, Err))
1123          return true;
1124    }
1125  }
1126  return false;
1127}
1128
1129// LinkAppendingVars - If there were any appending global variables, link them
1130// together now.  Return true on error.
1131static bool LinkAppendingVars(Module *M,
1132                  std::multimap<std::string, GlobalVariable *> &AppendingVars,
1133                              std::string *ErrorMsg) {
1134  if (AppendingVars.empty()) return false; // Nothing to do.
1135
1136  // Loop over the multimap of appending vars, processing any variables with the
1137  // same name, forming a new appending global variable with both of the
1138  // initializers merged together, then rewrite references to the old variables
1139  // and delete them.
1140  std::vector<Constant*> Inits;
1141  while (AppendingVars.size() > 1) {
1142    // Get the first two elements in the map...
1143    std::multimap<std::string,
1144      GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1145
1146    // If the first two elements are for different names, there is no pair...
1147    // Otherwise there is a pair, so link them together...
1148    if (First->first == Second->first) {
1149      GlobalVariable *G1 = First->second, *G2 = Second->second;
1150      const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1151      const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1152
1153      // Check to see that they two arrays agree on type...
1154      if (T1->getElementType() != T2->getElementType())
1155        return Error(ErrorMsg,
1156         "Appending variables with different element types need to be linked!");
1157      if (G1->isConstant() != G2->isConstant())
1158        return Error(ErrorMsg,
1159                     "Appending variables linked with different const'ness!");
1160
1161      if (G1->getAlignment() != G2->getAlignment())
1162        return Error(ErrorMsg,
1163         "Appending variables with different alignment need to be linked!");
1164
1165      if (G1->getVisibility() != G2->getVisibility())
1166        return Error(ErrorMsg,
1167         "Appending variables with different visibility need to be linked!");
1168
1169      if (G1->getSection() != G2->getSection())
1170        return Error(ErrorMsg,
1171         "Appending variables with different section name need to be linked!");
1172
1173      unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1174      ArrayType *NewType = ArrayType::get(T1->getElementType(),
1175                                                         NewSize);
1176
1177      G1->setName("");   // Clear G1's name in case of a conflict!
1178
1179      // Create the new global variable...
1180      GlobalVariable *NG =
1181        new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1182                           /*init*/0, First->first, 0, G1->isThreadLocal(),
1183                           G1->getType()->getAddressSpace());
1184
1185      // Propagate alignment, visibility and section info.
1186      CopyGVAttributes(NG, G1);
1187
1188      // Merge the initializer...
1189      Inits.reserve(NewSize);
1190      if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1191        for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1192          Inits.push_back(I->getOperand(i));
1193      } else {
1194        assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1195        Constant *CV = Constant::getNullValue(T1->getElementType());
1196        for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1197          Inits.push_back(CV);
1198      }
1199      if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1200        for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1201          Inits.push_back(I->getOperand(i));
1202      } else {
1203        assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1204        Constant *CV = Constant::getNullValue(T2->getElementType());
1205        for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1206          Inits.push_back(CV);
1207      }
1208      NG->setInitializer(ConstantArray::get(NewType, Inits));
1209      Inits.clear();
1210
1211      // Replace any uses of the two global variables with uses of the new
1212      // global...
1213
1214      // FIXME: This should rewrite simple/straight-forward uses such as
1215      // getelementptr instructions to not use the Cast!
1216      G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1217                             G1->getType()));
1218      G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1219                             G2->getType()));
1220
1221      // Remove the two globals from the module now...
1222      M->getGlobalList().erase(G1);
1223      M->getGlobalList().erase(G2);
1224
1225      // Put the new global into the AppendingVars map so that we can handle
1226      // linking of more than two vars...
1227      Second->second = NG;
1228    }
1229    AppendingVars.erase(First);
1230  }
1231
1232  return false;
1233}
1234
1235static bool ResolveAliases(Module *Dest) {
1236  for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1237       I != E; ++I)
1238    // We can't sue resolveGlobalAlias here because we need to preserve
1239    // bitcasts and GEPs.
1240    if (const Constant *C = I->getAliasee()) {
1241      while (dyn_cast<GlobalAlias>(C))
1242        C = cast<GlobalAlias>(C)->getAliasee();
1243      const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1244      if (C != I && !(GV && GV->isDeclaration()))
1245        I->replaceAllUsesWith(const_cast<Constant*>(C));
1246    }
1247
1248  return false;
1249}
1250
1251// LinkModules - This function links two modules together, with the resulting
1252// left module modified to be the composite of the two input modules.  If an
1253// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1254// the problem.  Upon failure, the Dest module could be in a modified state, and
1255// shouldn't be relied on to be consistent.
1256bool
1257Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1258  assert(Dest != 0 && "Invalid Destination module");
1259  assert(Src  != 0 && "Invalid Source Module");
1260
1261  if (Dest->getDataLayout().empty()) {
1262    if (!Src->getDataLayout().empty()) {
1263      Dest->setDataLayout(Src->getDataLayout());
1264    } else {
1265      std::string DataLayout;
1266
1267      if (Dest->getEndianness() == Module::AnyEndianness) {
1268        if (Src->getEndianness() == Module::BigEndian)
1269          DataLayout.append("E");
1270        else if (Src->getEndianness() == Module::LittleEndian)
1271          DataLayout.append("e");
1272      }
1273
1274      if (Dest->getPointerSize() == Module::AnyPointerSize) {
1275        if (Src->getPointerSize() == Module::Pointer64)
1276          DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1277        else if (Src->getPointerSize() == Module::Pointer32)
1278          DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1279      }
1280      Dest->setDataLayout(DataLayout);
1281    }
1282  }
1283
1284  // Copy the target triple from the source to dest if the dest's is empty.
1285  if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1286    Dest->setTargetTriple(Src->getTargetTriple());
1287
1288  if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1289      Src->getDataLayout() != Dest->getDataLayout())
1290    errs() << "WARNING: Linking two modules of different data layouts!\n";
1291  if (!Src->getTargetTriple().empty() &&
1292      Dest->getTargetTriple() != Src->getTargetTriple())
1293    errs() << "WARNING: Linking two modules of different target triples!\n";
1294
1295  // Append the module inline asm string.
1296  if (!Src->getModuleInlineAsm().empty()) {
1297    if (Dest->getModuleInlineAsm().empty())
1298      Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1299    else
1300      Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1301                               Src->getModuleInlineAsm());
1302  }
1303
1304  // Update the destination module's dependent libraries list with the libraries
1305  // from the source module. There's no opportunity for duplicates here as the
1306  // Module ensures that duplicate insertions are discarded.
1307  for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1308       SI != SE; ++SI)
1309    Dest->addLibrary(*SI);
1310
1311  // LinkTypes - Go through the symbol table of the Src module and see if any
1312  // types are named in the src module that are not named in the Dst module.
1313  // Make sure there are no type name conflicts.
1314  if (LinkTypes(Dest, Src, ErrorMsg))
1315    return true;
1316
1317  // ValueMap - Mapping of values from what they used to be in Src, to what they
1318  // are now in Dest.
1319  std::map<const Value*, Value*> ValueMap;
1320
1321  // AppendingVars - Keep track of global variables in the destination module
1322  // with appending linkage.  After the module is linked together, they are
1323  // appended and the module is rewritten.
1324  std::multimap<std::string, GlobalVariable *> AppendingVars;
1325  for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1326       I != E; ++I) {
1327    // Add all of the appending globals already in the Dest module to
1328    // AppendingVars.
1329    if (I->hasAppendingLinkage())
1330      AppendingVars.insert(std::make_pair(I->getName(), I));
1331  }
1332
1333  // Insert all of the named mdnoes in Src into the Dest module.
1334  LinkNamedMDNodes(Dest, Src);
1335
1336  // Insert all of the globals in src into the Dest module... without linking
1337  // initializers (which could refer to functions not yet mapped over).
1338  if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1339    return true;
1340
1341  // Link the functions together between the two modules, without doing function
1342  // bodies... this just adds external function prototypes to the Dest
1343  // function...  We do this so that when we begin processing function bodies,
1344  // all of the global values that may be referenced are available in our
1345  // ValueMap.
1346  if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1347    return true;
1348
1349  // If there were any alias, link them now. We really need to do this now,
1350  // because all of the aliases that may be referenced need to be available in
1351  // ValueMap
1352  if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1353
1354  // Update the initializers in the Dest module now that all globals that may
1355  // be referenced are in Dest.
1356  if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1357
1358  // Link in the function bodies that are defined in the source module into the
1359  // DestModule.  This consists basically of copying the function over and
1360  // fixing up references to values.
1361  if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1362
1363  // If there were any appending global variables, link them together now.
1364  if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1365
1366  // Resolve all uses of aliases with aliasees
1367  if (ResolveAliases(Dest)) return true;
1368
1369  // If the source library's module id is in the dependent library list of the
1370  // destination library, remove it since that module is now linked in.
1371  sys::Path modId;
1372  modId.set(Src->getModuleIdentifier());
1373  if (!modId.isEmpty())
1374    Dest->removeLibrary(modId.getBasename());
1375
1376  return false;
1377}
1378
1379// vim: sw=2
1380