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