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