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