LinkModules.cpp revision d13726f1e91218bc3f7103adf6cd98676bc477e2
17f49602e5ac7186c9505a0496393dd624515b459Reid Spencer//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
952f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner//
1052f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner// This file implements the LLVM module linker.
1152f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner//
1252f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner// Specifically, this:
138d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner//  * Merges global variables between the two modules
148d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner//    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner//  * Merges functions between two modules
1652f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner//
1752f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner//===----------------------------------------------------------------------===//
1852f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner
197cc371a7958c7a049c679a59023c3c8c83f6cc83Reid Spencer#include "llvm/Linker.h"
20adbc0b5287bf36893cdcae2440d48b3cb3489e38Chris Lattner#include "llvm/Constants.h"
21adbc0b5287bf36893cdcae2440d48b3cb3489e38Chris Lattner#include "llvm/DerivedTypes.h"
225c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner#include "llvm/Module.h"
2378d033e086e19e016273de014f9214aa6f3f844bReid Spencer#include "llvm/TypeSymbolTable.h"
24ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer#include "llvm/ValueSymbolTable.h"
2547b14a4a6a455c7be169cfd312fcbe796f0ad426Misha Brukman#include "llvm/Instructions.h"
26adbc0b5287bf36893cdcae2440d48b3cb3489e38Chris Lattner#include "llvm/Assembly/Writer.h"
2741edad7e4b8872414564dea5fb41fa6194375355Bill Wendling#include "llvm/Support/Streams.h"
2857a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer#include "llvm/System/Path.h"
2962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner#include "llvm/ADT/DenseMap.h"
301a097e30d39e60303ae2b19f7a56e813f3e3c18eBill Wendling#include <sstream>
31f7703df4968084c18c248c1feea9961c19a32e6aChris Lattnerusing namespace llvm;
32d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
335c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner// Error - Simple wrapper function to conditionally assign to E and return true.
345c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner// This just makes error return conditions a little bit simpler...
358166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattnerstatic inline bool Error(std::string *E, const std::string &Message) {
365c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  if (E) *E = Message;
375c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  return true;
385c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
395c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
40700867bb69ae1469f2b20005a79fd133e83fd552John Criswell// Function: ResolveTypes()
41700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//
42700867bb69ae1469f2b20005a79fd133e83fd552John Criswell// Description:
43700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  Attempt to link the two specified types together.
44700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//
45700867bb69ae1469f2b20005a79fd133e83fd552John Criswell// Inputs:
46700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  DestTy - The type to which we wish to resolve.
47700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  SrcTy  - The original type which we want to resolve.
48700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//
49700867bb69ae1469f2b20005a79fd133e83fd552John Criswell// Outputs:
50700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  DestST - The symbol table in which the new type should be placed.
51700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//
52700867bb69ae1469f2b20005a79fd133e83fd552John Criswell// Return value:
53700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  true  - There is an error and the types cannot yet be linked.
54700867bb69ae1469f2b20005a79fd133e83fd552John Criswell//  false - No errors.
554c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner//
56bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattnerstatic bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
57e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  if (DestTy == SrcTy) return false;       // If already equal, noop
58bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner  assert(DestTy && SrcTy && "Can't handle null types");
59e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner
60bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner  if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
61bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    // Type _is_ in module, just opaque...
62bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
63bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner  } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
64bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
65bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner  } else {
66bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    return true;  // Cannot link types... not-equal and neither is opaque.
674c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  }
684c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  return false;
694c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner}
704c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
7162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner/// LinkerTypeMap - This implements a map of types that is stable
7262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner/// even if types are resolved/refined to other types.  This is not a general
7362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner/// purpose map, it is specific to the linker's use.
7462a81a1eba019ab570b002f8e1686494139785a1Chris Lattnernamespace {
7562a81a1eba019ab570b002f8e1686494139785a1Chris Lattnerclass LinkerTypeMap : public AbstractTypeUser {
7662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
7762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  TheMapTy TheMap;
7862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
79fc196f9ee909ac35837f6f771a42aa0dec817584Chris Lattner  LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
80fc196f9ee909ac35837f6f771a42aa0dec817584Chris Lattner  void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
81fc196f9ee909ac35837f6f771a42aa0dec817584Chris Lattnerpublic:
82fc196f9ee909ac35837f6f771a42aa0dec817584Chris Lattner  LinkerTypeMap() {}
83fc196f9ee909ac35837f6f771a42aa0dec817584Chris Lattner  ~LinkerTypeMap() {
8462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
8562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner         E = TheMap.end(); I != E; ++I)
8662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      I->first->removeAbstractTypeUser(this);
8762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
8862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
8962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// lookup - Return the value for the specified type or null if it doesn't
9062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// exist.
9162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  const Type *lookup(const Type *Ty) const {
9262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    TheMapTy::const_iterator I = TheMap.find(Ty);
9362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (I != TheMap.end()) return I->second;
9462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    return 0;
9562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
9662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
9762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// erase - Remove the specified type, returning true if it was in the set.
9862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  bool erase(const Type *Ty) {
9962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (!TheMap.erase(Ty))
10062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      return false;
10162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (Ty->isAbstract())
10262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      Ty->removeAbstractTypeUser(this);
10362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    return true;
10462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
10562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
10662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// insert - This returns true if the pointer was new to the set, false if it
10762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// was already in the set.
10862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  bool insert(const Type *Src, const Type *Dst) {
1096b345ee9b2833cf1b2f79dc16d06d4060bec36efDan Gohman    if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
11062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      return false;  // Already in map.
11162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (Src->isAbstract())
11262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      Src->addAbstractTypeUser(this);
11362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    return true;
11462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
11562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
11662a81a1eba019ab570b002f8e1686494139785a1Chris Lattnerprotected:
11762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// refineAbstractType - The callback method invoked when an abstract type is
11862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// resolved to another type.  An object must override this method to update
11962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// its internal state to reference NewType instead of OldType.
12062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  ///
12162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  virtual void refineAbstractType(const DerivedType *OldTy,
12262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner                                  const Type *NewTy) {
12362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    TheMapTy::iterator I = TheMap.find(OldTy);
12462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    const Type *DstTy = I->second;
12562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
12662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    TheMap.erase(I);
12762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (OldTy->isAbstract())
12862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      OldTy->removeAbstractTypeUser(this);
12962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
13062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    // Don't reinsert into the map if the key is concrete now.
13162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (NewTy->isAbstract())
13262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      insert(NewTy, DstTy);
13362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
13462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
13562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// The other case which AbstractTypeUsers must be aware of is when a type
13662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// makes the transition from being abstract (where it has clients on it's
13762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// AbstractTypeUsers list) to concrete (where it does not).  This method
13862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  /// notifies ATU's when this occurs for a type.
13962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  virtual void typeBecameConcrete(const DerivedType *AbsTy) {
14062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    TheMap.erase(AbsTy);
14162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    AbsTy->removeAbstractTypeUser(this);
14262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
14362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
14462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  // for debugging...
14562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  virtual void dump() const {
14662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    cerr << "AbstractTypeSet!\n";
14762a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  }
14862a81a1eba019ab570b002f8e1686494139785a1Chris Lattner};
14962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner}
15062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
15162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
152e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner// RecursiveResolveTypes - This is just like ResolveTypes, except that it
153e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner// recurses down into derived types, merging the used types if the parent types
154e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner// are compatible.
155a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattnerstatic bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
15662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner                                   LinkerTypeMap &Pointers) {
157a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner  if (DstTy == SrcTy) return false;       // If already equal, noop
158f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
159e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  // If we found our opaque type, resolve it now!
160a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner  if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
161a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    return ResolveTypes(DstTy, SrcTy);
162f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
163e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  // Two types cannot be resolved together if they are of different primitive
164e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  // type.  For example, we cannot resolve an int to a float.
165a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner  if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
166e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner
16756539659eb1b192d493aa333b60213889129b9f1Chris Lattner  // If neither type is abstract, then they really are just different types.
168a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner  if (!DstTy->isAbstract() && !SrcTy->isAbstract())
16956539659eb1b192d493aa333b60213889129b9f1Chris Lattner    return true;
17056539659eb1b192d493aa333b60213889129b9f1Chris Lattner
171e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  // Otherwise, resolve the used type used by this derived type...
172a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner  switch (DstTy->getTypeID()) {
173f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner  default:
174f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner    return true;
175e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  case Type::FunctionTyID: {
176a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const FunctionType *DstFT = cast<FunctionType>(DstTy);
177a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
1789ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner    if (DstFT->isVarArg() != SrcFT->isVarArg() ||
1799ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner        DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
18043f4ba8c7d19664bb5de73a7b391b67061f25d22Chris Lattner      return true;
181a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner
182a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    // Use TypeHolder's so recursive resolution won't break us.
183a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    PATypeHolder ST(SrcFT), DT(DstFT);
184a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
185a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner      const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
186a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner      if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
187e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner        return true;
188a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    }
189e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner    return false;
190e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  }
191e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  case Type::StructTyID: {
192a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const StructType *DstST = cast<StructType>(DstTy);
193a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const StructType *SrcST = cast<StructType>(SrcTy);
1949ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner    if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
195f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner      return true;
196a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner
197a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    PATypeHolder ST(SrcST), DT(DstST);
198a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
199a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner      const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
200a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner      if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
201e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner        return true;
202a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    }
203e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner    return false;
204e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  }
205e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  case Type::ArrayTyID: {
206a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const ArrayType *DAT = cast<ArrayType>(DstTy);
207a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const ArrayType *SAT = cast<ArrayType>(SrcTy);
208e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner    if (DAT->getNumElements() != SAT->getNumElements()) return true;
209e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
210bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner                                  Pointers);
211e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner  }
212f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner  case Type::VectorTyID: {
213a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const VectorType *DVT = cast<VectorType>(DstTy);
214a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const VectorType *SVT = cast<VectorType>(SrcTy);
215f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner    if (DVT->getNumElements() != SVT->getNumElements()) return true;
216f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner    return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
217f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner                                  Pointers);
218f6f4f7a149e2864cc0441afcbed5fd99ff4b9587Chris Lattner  }
219e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner  case Type::PointerTyID: {
220a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const PointerType *DstPT = cast<PointerType>(DstTy);
221a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner    const PointerType *SrcPT = cast<PointerType>(SrcTy);
2229ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner
2239ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner    if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
2249ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner      return true;
2259ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner
226e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    // If this is a pointer type, check to see if we have already seen it.  If
227e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    // so, we are in a recursive branch.  Cut off the search now.  We cannot use
228e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    // an associative container for this search, because the type pointers (keys
22962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    // in the container) change whenever types get resolved.
23062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (SrcPT->isAbstract())
23162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
23262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner        return ExistingDestTy != DstPT;
23362a81a1eba019ab570b002f8e1686494139785a1Chris Lattner
23462a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (DstPT->isAbstract())
23562a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
23662a81a1eba019ab570b002f8e1686494139785a1Chris Lattner        return ExistingSrcTy != SrcPT;
237e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    // Otherwise, add the current pointers to the vector to stop recursion on
238e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner    // this pair.
23962a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (DstPT->isAbstract())
24062a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      Pointers.insert(DstPT, SrcPT);
24162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner    if (SrcPT->isAbstract())
24262a81a1eba019ab570b002f8e1686494139785a1Chris Lattner      Pointers.insert(SrcPT, DstPT);
243a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner
2449ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner    return RecursiveResolveTypesI(DstPT->getElementType(),
2459ddf2c898f5227ca137aef7abc3051e16bd60025Chris Lattner                                  SrcPT->getElementType(), Pointers);
246e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner  }
247f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman  }
248e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner}
249e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner
250a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattnerstatic bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
25162a81a1eba019ab570b002f8e1686494139785a1Chris Lattner  LinkerTypeMap PointerTypes;
252bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner  return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
253e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner}
254e3092c94ad2e3af96f37a0a8186149acbbd9700aChris Lattner
255e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner
2562c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner// LinkTypes - Go through the symbol table of the Src module and see if any
2572c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner// types are named in the src module that are not named in the Dst module.
2582c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner// Make sure there are no type name conflicts.
2595c2d335d86579941b71816196a95a64b277e8963Chris Lattnerstatic bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
26078d033e086e19e016273de014f9214aa6f3f844bReid Spencer        TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
26178d033e086e19e016273de014f9214aa6f3f844bReid Spencer  const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
2622c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner
2632c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  // Look for a type plane for Type's...
26478d033e086e19e016273de014f9214aa6f3f844bReid Spencer  TypeSymbolTable::const_iterator TI = SrcST->begin();
26578d033e086e19e016273de014f9214aa6f3f844bReid Spencer  TypeSymbolTable::const_iterator TE = SrcST->end();
266567bc2cc1ed4d610daceecbb4ff7f92ebde1b530Reid Spencer  if (TI == TE) return false;  // No named types, do nothing.
2672c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner
268cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman  // Some types cannot be resolved immediately because they depend on other
269cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman  // types being resolved to each other first.  This contains a list of types we
270cf00c4ab3ba308d45d98c5ccab87362cf802facbMisha Brukman  // are waiting to recheck.
2714c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  std::vector<std::string> DelayedTypesToResolve;
2724c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
273567bc2cc1ed4d610daceecbb4ff7f92ebde1b530Reid Spencer  for ( ; TI != TE; ++TI ) {
274567bc2cc1ed4d610daceecbb4ff7f92ebde1b530Reid Spencer    const std::string &Name = TI->first;
275c28a224c68adf0464c275778af4bce762ad25d37Reid Spencer    const Type *RHS = TI->second;
2762c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner
277bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    // Check to see if this type name is already in the dest module.
27878d033e086e19e016273de014f9214aa6f3f844bReid Spencer    Type *Entry = DestST->lookup(Name);
2794c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
280bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    // If the name is just in the source module, bring it over to the dest.
281bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    if (Entry == 0) {
282bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner      if (!Name.empty())
283bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner        DestST->insert(Name, const_cast<Type*>(RHS));
284bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner    } else if (ResolveTypes(Entry, RHS)) {
2854c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner      // They look different, save the types 'till later to resolve.
2864c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner      DelayedTypesToResolve.push_back(Name);
2874c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    }
2884c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  }
2894c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
2904c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  // Iteratively resolve types while we can...
2914c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner  while (!DelayedTypesToResolve.empty()) {
2924c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    // Loop over all of the types, attempting to resolve them if possible...
2934c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    unsigned OldSize = DelayedTypesToResolve.size();
2944c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
295e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner    // Try direct resolution by name...
2964c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
2974c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner      const std::string &Name = DelayedTypesToResolve[i];
29878d033e086e19e016273de014f9214aa6f3f844bReid Spencer      Type *T1 = SrcST->lookup(Name);
29978d033e086e19e016273de014f9214aa6f3f844bReid Spencer      Type *T2 = DestST->lookup(Name);
300bc1c82a0f73eda86cf24416cebc83b4690fcd76aChris Lattner      if (!ResolveTypes(T2, T1)) {
3014c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner        // We are making progress!
3024c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner        DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
3034c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner        --i;
3042f6bb2bce13084dfc4c8acf47f9eae0578267aaaChris Lattner      }
3054c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    }
3062f6bb2bce13084dfc4c8acf47f9eae0578267aaaChris Lattner
3074c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    // Did we not eliminate any types?
3084c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner    if (DelayedTypesToResolve.size() == OldSize) {
309e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner      // Attempt to resolve subelements of types.  This allows us to merge these
310e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner      // two types: { int* } and { opaque* }
3114c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner      for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
3124c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner        const std::string &Name = DelayedTypesToResolve[i];
313a4477f9b31ce0b6fadc5365ff9355679c1ecb954Chris Lattner        if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
314e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner          // We are making progress!
315e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner          DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
316f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
317e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner          // Go back to the main loop, perhaps we can resolve directly by name
318e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner          // now...
319e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner          break;
320e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner        }
321e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner      }
322e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner
323e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner      // If we STILL cannot resolve the types, then there is something wrong.
324e76c57ad467ed57f09f2a3ef51628d4b6eb2b304Chris Lattner      if (DelayedTypesToResolve.size() == OldSize) {
325aeb18ce9c012f8554f48bae9bb32351c6eeaa26cChris Lattner        // Remove the symbol name from the destination.
326aeb18ce9c012f8554f48bae9bb32351c6eeaa26cChris Lattner        DelayedTypesToResolve.pop_back();
3274c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner      }
3282c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner    }
3292c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  }
3304c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
3314c00e53b81de81ecf4ba0c4e287ea230c79e82aeChris Lattner
3322c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  return false;
3332c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner}
3342c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner
3350bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner#ifndef NDEBUG
3365c2d335d86579941b71816196a95a64b277e8963Chris Lattnerstatic void PrintMap(const std::map<const Value*, Value*> &M) {
3375c2d335d86579941b71816196a95a64b277e8963Chris Lattner  for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
3382d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner       I != E; ++I) {
339e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling    cerr << " Fr: " << (void*)I->first << " ";
34087182ae6baf28ca6da6ee4bc00cf1857f293acfeChris Lattner    I->first->dump();
341e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling    cerr << " To: " << (void*)I->second << " ";
34287182ae6baf28ca6da6ee4bc00cf1857f293acfeChris Lattner    I->second->dump();
343e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling    cerr << "\n";
3442d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner  }
3452d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner}
3460bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner#endif
3472d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner
3482d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner
349619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer// RemapOperand - Use ValueMap to convert constants from one module to another.
3505c2d335d86579941b71816196a95a64b277e8963Chris Lattnerstatic Value *RemapOperand(const Value *In,
3510033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner                           std::map<const Value*, Value*> &ValueMap) {
3520033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner  std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
353ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer  if (I != ValueMap.end())
354ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    return I->second;
3555c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
356619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer  // Check to see if it's a constant that we are interested in transforming.
357620fd68b1086b4d99b23951357299bee357aa62aChris Lattner  Value *Result = 0;
35818961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  if (const Constant *CPV = dyn_cast<Constant>(In)) {
359de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner    if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
360a54b7cbd452b3adb2f51346140d996b29c2cdb30Reid Spencer        isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
3610033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner      return const_cast<Constant*>(CPV);   // Simple constants stay identical.
3628d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner
36318961504fc2b299578dba817900a0696cf3ccc4dChris Lattner    if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
364cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos      std::vector<Constant*> Operands(CPA->getNumOperands());
365cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos      for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
3660033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner        Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
367e9bb2df410f7a22decad9a883f7139d5857c1520Chris Lattner      Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
36818961504fc2b299578dba817900a0696cf3ccc4dChris Lattner    } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
369cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos      std::vector<Constant*> Operands(CPS->getNumOperands());
370cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos      for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
3710033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner        Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
372e9bb2df410f7a22decad9a883f7139d5857c1520Chris Lattner      Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
373b976e668165e1875a8f1eb7af800e33bb1e4393dChris Lattner    } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
37418961504fc2b299578dba817900a0696cf3ccc4dChris Lattner      Result = const_cast<Constant*>(CPV);
3759d6565a5b1fbc4286d6ee638d8f47a3171a9ed7eReid Spencer    } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
376a88eb9287eb14ba62ca6324b2b249e0ae9fe3309Chris Lattner      std::vector<Constant*> Operands(CP->getNumOperands());
377a88eb9287eb14ba62ca6324b2b249e0ae9fe3309Chris Lattner      for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
378a88eb9287eb14ba62ca6324b2b249e0ae9fe3309Chris Lattner        Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
3799d6565a5b1fbc4286d6ee638d8f47a3171a9ed7eReid Spencer      Result = ConstantVector::get(Operands);
3806cdf1971bdf88ddd9a7d46b5f5f975497d68c38eChris Lattner    } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
38127d672136a57519095a3ef20161697749cffb57cChris Lattner      std::vector<Constant*> Ops;
38227d672136a57519095a3ef20161697749cffb57cChris Lattner      for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
38327d672136a57519095a3ef20161697749cffb57cChris Lattner        Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
38427d672136a57519095a3ef20161697749cffb57cChris Lattner      Result = CE->getWithOperands(Ops);
3858d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner    } else {
3860bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner      assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
3878d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner      assert(0 && "Unknown type of derived type constant value!");
3888d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner    }
389620fd68b1086b4d99b23951357299bee357aa62aChris Lattner  } else if (isa<InlineAsm>(In)) {
390620fd68b1086b4d99b23951357299bee357aa62aChris Lattner    Result = const_cast<Value*>(In);
391620fd68b1086b4d99b23951357299bee357aa62aChris Lattner  }
392620fd68b1086b4d99b23951357299bee357aa62aChris Lattner
393619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer  // Cache the mapping in our local map structure
394620fd68b1086b4d99b23951357299bee357aa62aChris Lattner  if (Result) {
395817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov    ValueMap[In] = Result;
3968d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner    return Result;
3978d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  }
3988bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer
3990bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner#ifndef NDEBUG
400e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  cerr << "LinkModules ValueMap: \n";
4010033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner  PrintMap(ValueMap);
4022d3e8bba628843bf2dffa21f69d9b45098d3bfc4Chris Lattner
403e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling  cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
4048d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  assert(0 && "Couldn't remap value!");
4050bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner#endif
4068d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  return 0;
4075c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
4085c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
4098bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
4108bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer/// in the symbol table.  This is good for all clients except for us.  Go
4118bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer/// through the trouble to force this back.
412c003628a612d3687fb77088a5894314210a65385Chris Lattnerstatic void ForceRenaming(GlobalValue *GV, const std::string &Name) {
413c003628a612d3687fb77088a5894314210a65385Chris Lattner  assert(GV->getName() != Name && "Can't force rename to self");
414ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer  ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
415c003628a612d3687fb77088a5894314210a65385Chris Lattner
416c003628a612d3687fb77088a5894314210a65385Chris Lattner  // If there is a conflict, rename the conflict.
41733f294930e0affa51c3818405741abd80cc90316Chris Lattner  if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
418ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    assert(ConflictGV->hasInternalLinkage() &&
419ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer           "Not conflicting with a static global, should link instead!");
42033f294930e0affa51c3818405741abd80cc90316Chris Lattner    GV->takeName(ConflictGV);
42133f294930e0affa51c3818405741abd80cc90316Chris Lattner    ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
422ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
42333f294930e0affa51c3818405741abd80cc90316Chris Lattner  } else {
42433f294930e0affa51c3818405741abd80cc90316Chris Lattner    GV->setName(Name);              // Force the name back
425ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer  }
426ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer}
427ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer
428ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer/// CopyGVAttributes - copy additional attributes (those not needed to construct
429ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer/// a GlobalValue) from the SrcGV to the DestGV.
430ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencerstatic void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
43128c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  // Use the maximum alignment, rather than just copying the alignment of SrcGV.
43228c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
43328c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  DestGV->copyAttributesFrom(SrcGV);
43428c3cff8250b3fe2adc6479306fe7dbdb48a1bdbDuncan Sands  DestGV->setAlignment(Alignment);
435c003628a612d3687fb77088a5894314210a65385Chris Lattner}
436c003628a612d3687fb77088a5894314210a65385Chris Lattner
437aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner/// GetLinkageResult - This analyzes the two global values and determines what
438aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner/// the result will look like in the destination module.  In particular, it
439aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner/// computes the resultant linkage type, computes whether the global in the
440aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner/// source should be copied over to the destination (replacing the existing
4419cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov/// one), and computes whether this linkage is an error or not. It also performs
4429cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov/// visibility checks: we cannot link together two symbols with different
4439cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov/// visibilities.
444968e39a5aba998a126278425da8287aae358e7a7Anton Korobeynikovstatic bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
445aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner                             GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
446aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner                             std::string *Err) {
447aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  assert((!Dest || !Src->hasInternalLinkage()) &&
448aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner         "If Src has internal linkage, Dest shouldn't be set!");
449aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  if (!Dest) {
450aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    // Linking something to nothing.
451aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LinkFromSrc = true;
452aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LT = Src->getLinkage();
4535cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer  } else if (Src->isDeclaration()) {
4542b48ef0450944c2c46633aec9baf6be835a3b503Anton Korobeynikov    // If Src is external or if both Src & Dest are external..  Just link the
455aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    // external globals, we aren't adding anything.
456b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov    if (Src->hasDLLImportLinkage()) {
45778ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov      // If one of GVs has DLLImport linkage, result should be dllimport'ed.
4585cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      if (Dest->isDeclaration()) {
459b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov        LinkFromSrc = true;
460b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov        LT = Src->getLinkage();
461b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov      }
4628753c447a5f8eec1421331c40ffbb72c6d411f78Andrew Lenharth    } else if (Dest->hasExternalWeakLinkage()) {
4638753c447a5f8eec1421331c40ffbb72c6d411f78Andrew Lenharth      //If the Dest is weak, use the source linkage
4648753c447a5f8eec1421331c40ffbb72c6d411f78Andrew Lenharth      LinkFromSrc = true;
4658753c447a5f8eec1421331c40ffbb72c6d411f78Andrew Lenharth      LT = Src->getLinkage();
466b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov    } else {
467b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov      LinkFromSrc = false;
468b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov      LT = Dest->getLinkage();
469b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov    }
4705cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer  } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
471aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    // If Dest is external but Src is not:
472aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LinkFromSrc = true;
473aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LT = Src->getLinkage();
474aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
475aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    if (Src->getLinkage() != Dest->getLinkage())
476aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      return Error(Err, "Linking globals named '" + Src->getName() +
477aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner            "': can only link appending global with another appending global!");
478aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LinkFromSrc = true; // Special cased.
479aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    LT = Src->getLinkage();
4805df3186f598163258fabf3448d9372843804d1abDuncan Sands  } else if (Src->mayBeOverridden()) {
481aafce77b17d340aace52bcd49d1944109d82f14aDale Johannesen    // At this point we know that Dest has LinkOnce, External*, Weak, Common,
482aafce77b17d340aace52bcd49d1944109d82f14aDale Johannesen    // or DLL* linkage.
48380585f1daac3570f19cd255c5006dfcf2ff65a89Anton Korobeynikov    if ((Dest->hasLinkOnceLinkage() &&
484aafce77b17d340aace52bcd49d1944109d82f14aDale Johannesen          (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
48578ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov        Dest->hasExternalWeakLinkage()) {
486aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      LinkFromSrc = true;
487aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      LT = Src->getLinkage();
488aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    } else {
489aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      LinkFromSrc = false;
490aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      LT = Dest->getLinkage();
491aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    }
4925df3186f598163258fabf3448d9372843804d1abDuncan Sands  } else if (Dest->mayBeOverridden()) {
49378ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov    // At this point we know that Src has External* or DLL* linkage.
49478ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov    if (Src->hasExternalWeakLinkage()) {
49578ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov      LinkFromSrc = false;
49678ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov      LT = Dest->getLinkage();
49778ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov    } else {
49878ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov      LinkFromSrc = true;
49978ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov      LT = GlobalValue::ExternalLinkage;
50078ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov    }
501aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  } else {
502b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov    assert((Dest->hasExternalLinkage() ||
503b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov            Dest->hasDLLImportLinkage() ||
50478ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov            Dest->hasDLLExportLinkage() ||
50578ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov            Dest->hasExternalWeakLinkage()) &&
506b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov           (Src->hasExternalLinkage() ||
507b74ed07bfd3af42331b1964c24c39912610a08f4Anton Korobeynikov            Src->hasDLLImportLinkage() ||
50878ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov            Src->hasDLLExportLinkage() ||
50978ee7b78c3c47b71c4b7a1475438d6574216a64bAnton Korobeynikov            Src->hasExternalWeakLinkage()) &&
510aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner           "Unexpected linkage type!");
511f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman    return Error(Err, "Linking globals named '" + Src->getName() +
512aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner                 "': symbol multiply defined!");
513aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  }
5149cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov
5159cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov  // Check visibility
5169cd3ccf5065a8a139e458d016c88a8512471598bAnton Korobeynikov  if (Dest && Src->getVisibility() != Dest->getVisibility())
51797f8b0900abddfa72fd59e777399280adb4ca0a6Chris Lattner    if (!Src->isDeclaration() && !Dest->isDeclaration())
51897f8b0900abddfa72fd59e777399280adb4ca0a6Chris Lattner      return Error(Err, "Linking globals named '" + Src->getName() +
51997f8b0900abddfa72fd59e777399280adb4ca0a6Chris Lattner                   "': symbols have different visibilities!");
520aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner  return false;
521aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner}
5225c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
5235c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner// LinkGlobals - Loop through the global variables in the src module and merge
5248166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner// them into the dest module.
525968e39a5aba998a126278425da8287aae358e7a7Anton Korobeynikovstatic bool LinkGlobals(Module *Dest, const Module *Src,
5265c2d335d86579941b71816196a95a64b277e8963Chris Lattner                        std::map<const Value*, Value*> &ValueMap,
5278166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner                    std::multimap<std::string, GlobalVariable *> &AppendingVars,
5285c2d335d86579941b71816196a95a64b277e8963Chris Lattner                        std::string *Err) {
529d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner  ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
530d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
5315c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  // Loop over all of the globals in the src module, mapping them over as we go
5320bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner  for (Module::const_global_iterator I = Src->global_begin(),
5330bb8757997392ee18ca9de0f1fab29463f8e7aebChris Lattner       E = Src->global_end(); I != E; ++I) {
534968e39a5aba998a126278425da8287aae358e7a7Anton Korobeynikov    const GlobalVariable *SGV = I;
53501f69399352380532d480f6749daed660f50b15cAnton Korobeynikov    GlobalValue *DGV = 0;
53601f69399352380532d480f6749daed660f50b15cAnton Korobeynikov
537d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // Check to see if may have to link the global with the global, alias or
538d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // function.
539d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    if (SGV->hasName() && !SGV->hasInternalLinkage())
540d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
541d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner                                                        SGV->getNameEnd()));
542d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
543ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    // If we found a global with the same name in the dest module, but it has
544ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    // internal linkage, we are really not doing any linkage here.
545ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    if (DGV && DGV->hasInternalLinkage())
546ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner      DGV = 0;
547ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner
548d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // If types don't agree due to opaque types, try to resolve them.
549d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    if (DGV && DGV->getType() != SGV->getType())
550d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      RecursiveResolveTypes(SGV->getType(), DGV->getType());
55101f69399352380532d480f6749daed660f50b15cAnton Korobeynikov
552c318329a1098a19137398af4d880f4d8cdd9cd8dDan Gohman    assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
553c318329a1098a19137398af4d880f4d8cdd9cd8dDan Gohman            SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
5544ad02e726d9b634372b037d4b352d8b63bb9e849Chris Lattner           "Global must either be external or have an initializer!");
5555c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
556b324bd735ff5c99a52cd3c3f5d01c0e1398a2d3aChris Lattner    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
557b324bd735ff5c99a52cd3c3f5d01c0e1398a2d3aChris Lattner    bool LinkFromSrc = false;
558aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner    if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
559aee38ea5698fd770bb41d01d06542cb849e131a4Chris Lattner      return true;
5600fec08eb58dd9fffeb72c584aa61a59d71111c8dChris Lattner
5616157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (DGV == 0) {
5625c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner      // No linking to be performed, simply create an identical version of the
5638d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner      // symbol over in the dest module... the initializer will be filled in
564d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // later by LinkGlobalInits.
5652719bac90525985f4ebb97324b4c087d47b54384Chris Lattner      GlobalVariable *NewDGV =
5662719bac90525985f4ebb97324b4c087d47b54384Chris Lattner        new GlobalVariable(SGV->getType()->getElementType(),
5672719bac90525985f4ebb97324b4c087d47b54384Chris Lattner                           SGV->isConstant(), SGV->getLinkage(), /*init*/0,
568a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           SGV->getName(), Dest, false,
569a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           SGV->getType()->getAddressSpace());
570471feac1b297b9458de18d973af371bf7f10296bReid Spencer      // Propagate alignment, visibility and section info.
571ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      CopyGVAttributes(NewDGV, SGV);
5725dfbaf1fe3fa6914095cc55cde20b1ed25187b56Andrew Lenharth
5732719bac90525985f4ebb97324b4c087d47b54384Chris Lattner      // If the LLVM runtime renamed the global, but it is an externally visible
5742719bac90525985f4ebb97324b4c087d47b54384Chris Lattner      // symbol, DGV must be an existing global with internal linkage.  Rename
5752719bac90525985f4ebb97324b4c087d47b54384Chris Lattner      // it.
5766157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (!NewDGV->hasInternalLinkage() && NewDGV->getName() != SGV->getName())
577c003628a612d3687fb77088a5894314210a65385Chris Lattner        ForceRenaming(NewDGV, SGV->getName());
5785c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
5796157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // Make sure to remember this mapping.
580817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov      ValueMap[SGV] = NewDGV;
581817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov
582d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // Keep track that this is an appending variable.
5838166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      if (SGV->hasAppendingLinkage())
5848166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner        AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
5856157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      continue;
5866157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    }
5876157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
5886157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // If the visibilities of the symbols disagree and the destination is a
5896157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // prototype, take the visibility of its input.
5906157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (DGV->isDeclaration())
5916157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      DGV->setVisibility(SGV->getVisibility());
5926157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
5936157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (DGV->hasAppendingLinkage()) {
5948166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // No linking is performed yet.  Just insert a new copy of the global, and
5958166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // keep track of the fact that it is an appending variable in the
5968166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // AppendingVars map.  The name is cleared out so that no linkage is
5978166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // performed.
5988166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      GlobalVariable *NewDGV =
5998166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner        new GlobalVariable(SGV->getType()->getElementType(),
6008166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner                           SGV->isConstant(), SGV->getLinkage(), /*init*/0,
601a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           "", Dest, false,
602a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           SGV->getType()->getAddressSpace());
6038166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
60475c7915c3a24f8063c274ccffe2dc9b7bc8bce1fAnton Korobeynikov      // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
605ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      NewDGV->setAlignment(DGV->getAlignment());
60675c7915c3a24f8063c274ccffe2dc9b7bc8bce1fAnton Korobeynikov      // Propagate alignment, section and visibility info.
607ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      CopyGVAttributes(NewDGV, SGV);
6085dfbaf1fe3fa6914095cc55cde20b1ed25187b56Andrew Lenharth
6098166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Make sure to remember this mapping...
610817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov      ValueMap[SGV] = NewDGV;
6118166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
6128166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Keep track that this is an appending variable...
6138166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
6146157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      continue;
6156157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    }
6166157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
6176157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (LinkFromSrc) {
6186157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (isa<GlobalAlias>(DGV))
6191438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov        return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
6201438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov                     "': symbol multiple defined");
6216157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
622d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // If the types don't match, and if we are to link from the source, nuke
623d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // DGV and create a new one of the appropriate type.  Note that the thing
624d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // we are replacing may be a function (if a prototype, weak, etc) or a
625d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // global variable.
626d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      GlobalVariable *NewDGV =
6276157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
6286157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner                           NewLinkage, /*init*/0, DGV->getName(), Dest, false,
629d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner                           SGV->getType()->getAddressSpace());
630d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
631d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // Propagate alignment, section, and visibility info.
632d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      CopyGVAttributes(NewDGV, SGV);
633d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
634d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
635d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // DGV will conflict with NewDGV because they both had the same
636d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // name. We must erase this now so ForceRenaming doesn't assert
637d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // because DGV might not have internal linkage.
638d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
639d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner        Var->eraseFromParent();
640d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      else
641d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner        cast<Function>(DGV)->eraseFromParent();
642d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      DGV = NewDGV;
643d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
644d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // If the symbol table renamed the global, but it is an externally visible
645d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      // symbol, DGV must be an existing global with internal linkage.  Rename.
6466157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
647d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner        ForceRenaming(NewDGV, SGV->getName());
648d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
6496157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // Inherit const as appropriate.
650d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      NewDGV->setConstant(SGV->isConstant());
651d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
6526157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // Make sure to remember this mapping.
6536157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      ValueMap[SGV] = NewDGV;
6546157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      continue;
6555c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner    }
6566157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
6576157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Not "link from source", keep the one in the DestModule and remap the
6586157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // input onto it.
6596157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
6606157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Special case for const propagation.
6616157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
6626157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
6636157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        DGVar->setConstant(true);
6646157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
665d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov    // SGV is global, but DGV is alias.
666d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov    if (isa<GlobalAlias>(DGV)) {
667d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      // The only valid mappings are:
668d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      // - SGV is external declaration, which is effectively a no-op.
669d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      // - SGV is weak, when we just need to throw SGV out.
670d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      if (!SGV->isDeclaration() && !SGV->mayBeOverridden())
671d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
672d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov                     "': symbol multiple defined");
673d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov    }
6746157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
6756157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Set calculated linkage
6766157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    DGV->setLinkage(NewLinkage);
6776157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
6786157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Make sure to remember this mapping...
6796157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
6805c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  }
6815c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  return false;
6825c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
6835c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
68458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikovstatic GlobalValue::LinkageTypes
68558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton KorobeynikovCalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
68658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov  if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
68758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    return GlobalValue::ExternalLinkage;
68858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov  else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
68958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    return GlobalValue::WeakLinkage;
69058887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov  else {
69158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
69258887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov           "Unexpected linkage type");
69358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    return GlobalValue::InternalLinkage;
69458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov  }
69558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov}
69658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
69731ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio// LinkAlias - Loop through the alias in the src module and link them into the
69858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov// dest module. We're assuming, that all functions/global variables were already
69958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov// linked in.
7004fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikovstatic bool LinkAlias(Module *Dest, const Module *Src,
7014fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov                      std::map<const Value*, Value*> &ValueMap,
7024fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov                      std::string *Err) {
70331ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio  // Loop over all alias in the src module
70431ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio  for (Module::const_alias_iterator I = Src->alias_begin(),
70531ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio         E = Src->alias_end(); I != E; ++I) {
70658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    const GlobalAlias *SGA = I;
70758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    const GlobalValue *SAliasee = SGA->getAliasedGlobal();
70858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    GlobalAlias *NewGA = NULL;
70958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
71058887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    // Globals were already linked, thus we can just query ValueMap for variant
711caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    // of SAliasee in Dest.
71258d5e051574339106ce4139697ebadd21e34dbc0Ted Kremenek    std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
71358d5e051574339106ce4139697ebadd21e34dbc0Ted Kremenek    assert(VMI != ValueMap.end() && "Aliasee not linked");
71458d5e051574339106ce4139697ebadd21e34dbc0Ted Kremenek    GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
715caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    GlobalValue* DGV = NULL;
71658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
71758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    // Try to find something 'similar' to SGA in destination module.
718caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    if (!DGV && !SGA->hasInternalLinkage()) {
719caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      DGV = Dest->getNamedAlias(SGA->getName());
720caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
721caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      // If types don't agree due to opaque types, try to resolve them.
722caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      if (DGV && DGV->getType() != SGA->getType())
7235ed2ba26680f06846e7602ce65432b0a723b1273Chris Lattner        RecursiveResolveTypes(SGA->getType(), DGV->getType());
724caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    }
725caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
726caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    if (!DGV && !SGA->hasInternalLinkage()) {
727caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      DGV = Dest->getGlobalVariable(SGA->getName());
728caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
72958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      // If types don't agree due to opaque types, try to resolve them.
730caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      if (DGV && DGV->getType() != SGA->getType())
7315ed2ba26680f06846e7602ce65432b0a723b1273Chris Lattner        RecursiveResolveTypes(SGA->getType(), DGV->getType());
732caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    }
73358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
734caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    if (!DGV && !SGA->hasInternalLinkage()) {
735caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      DGV = Dest->getFunction(SGA->getName());
736caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
737caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      // If types don't agree due to opaque types, try to resolve them.
738caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      if (DGV && DGV->getType() != SGA->getType())
7395ed2ba26680f06846e7602ce65432b0a723b1273Chris Lattner        RecursiveResolveTypes(SGA->getType(), DGV->getType());
740caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    }
741caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
742caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    // No linking to be performed on internal stuff.
743caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    if (DGV && DGV->hasInternalLinkage())
744caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      DGV = NULL;
745caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov
746caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
747caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      // Types are known to be the same, check whether aliasees equal. As
74858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      // globals are already linked we just need query ValueMap to find the
74958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      // mapping.
75058887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      if (DAliasee == DGA->getAliasedGlobal()) {
75158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // This is just two copies of the same alias. Propagate linkage, if
75258887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // necessary.
75358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
75458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
75558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        NewGA = DGA;
75658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // Proceed to 'common' steps
75758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      } else
7581438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov        return Error(Err, "Alias Collision on '"  + SGA->getName()+
7591438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov                     "': aliases have different aliasees");
760caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
761f88bc65932e5cf41ba6ca706cd1b1b1f65300248Anton Korobeynikov      // The only allowed way is to link alias with external declaration or weak
762f88bc65932e5cf41ba6ca706cd1b1b1f65300248Anton Korobeynikov      // symbol..
7635df3186f598163258fabf3448d9372843804d1abDuncan Sands      if (DGVar->isDeclaration() || DGVar->mayBeOverridden()) {
764ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov        // But only if aliasee is global too...
765ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov        if (!isa<GlobalVariable>(DAliasee))
766caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov          return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
767caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov                       "': aliasee is not global variable");
768ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov
76958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
77058887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov                                SGA->getName(), DAliasee, Dest);
77158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        CopyGVAttributes(NewGA, SGA);
77258887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
77358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // Any uses of DGV need to change to NewGA, with cast, if needed.
774caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov        if (SGA->getType() != DGVar->getType())
775caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov          DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
776caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov                                                             DGVar->getType()));
77758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        else
778caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov          DGVar->replaceAllUsesWith(NewGA);
77958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
780caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov        // DGVar will conflict with NewGA because they both had the same
78158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // name. We must erase this now so ForceRenaming doesn't assert
78258887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // because DGV might not have internal linkage.
783caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov        DGVar->eraseFromParent();
78458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
78558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        // Proceed to 'common' steps
78658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      } else
7871438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov        return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
7881438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov                     "': symbol multiple defined");
789caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
790f88bc65932e5cf41ba6ca706cd1b1b1f65300248Anton Korobeynikov      // The only allowed way is to link alias with external declaration or weak
791f88bc65932e5cf41ba6ca706cd1b1b1f65300248Anton Korobeynikov      // symbol...
7925df3186f598163258fabf3448d9372843804d1abDuncan Sands      if (DF->isDeclaration() || DF->mayBeOverridden()) {
793ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov        // But only if aliasee is function too...
794ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov        if (!isa<Function>(DAliasee))
795caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov          return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
796caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov                       "': aliasee is not function");
797ed61c0bc76a7b9001d7639a908c955d0fae35bacAnton Korobeynikov
798b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
799b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov                                SGA->getName(), DAliasee, Dest);
800b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        CopyGVAttributes(NewGA, SGA);
801b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov
802b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        // Any uses of DF need to change to NewGA, with cast, if needed.
803b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        if (SGA->getType() != DF->getType())
804b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov          DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
805b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov                                                          DF->getType()));
806b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        else
807b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov          DF->replaceAllUsesWith(NewGA);
808b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov
809b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        // DF will conflict with NewGA because they both had the same
810b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        // name. We must erase this now so ForceRenaming doesn't assert
811b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        // because DF might not have internal linkage.
812b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        DF->eraseFromParent();
813b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov
814b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov        // Proceed to 'common' steps
815b5a4bd86df527c7d164197906861d2ca6f48678dAnton Korobeynikov      } else
8161438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov        return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
8171438b9dd82887b8faa2c4670dca45965609a43c6Anton Korobeynikov                     "': symbol multiple defined");
81858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    } else {
819caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      // No linking to be performed, simply create an identical version of the
820caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov      // alias over in the dest module...
82158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
82258887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
82358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov                              SGA->getName(), DAliasee, Dest);
82458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      CopyGVAttributes(NewGA, SGA);
82558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
82658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      // Proceed to 'common' steps
82758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    }
82858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
82958887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    assert(NewGA && "No alias was created in destination module!");
83058887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
831b8cdaf7099898d7c0eef4769bf6a89f39e7decc2Anton Korobeynikov    // If the symbol table renamed the alias, but it is an externally visible
832caa8ae8125124822b01ac21a8de186c13fcdd8f3Anton Korobeynikov    // symbol, DGA must be an global value with internal linkage. Rename it.
83358887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    if (NewGA->getName() != SGA->getName() &&
83458887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov        !NewGA->hasInternalLinkage())
83558887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov      ForceRenaming(NewGA, SGA->getName());
83658887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
83758887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    // Remember this mapping so uses in the source module get remapped
83858887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov    // later by RemapOperand.
839817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov    ValueMap[SGA] = NewGA;
84031ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio  }
84158887bc59316bcaf0c0675a45ddecd6994f3fbc6Anton Korobeynikov
84231ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio  return false;
84331ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio}
84431ed0fb804dd86fb15093e114701932119914400Lauro Ramos Venancio
8455c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
8468d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner// LinkGlobalInits - Update the initializers in the Dest module now that all
8478d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner// globals that may be referenced are in Dest.
8488d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattnerstatic bool LinkGlobalInits(Module *Dest, const Module *Src,
8495c2d335d86579941b71816196a95a64b277e8963Chris Lattner                            std::map<const Value*, Value*> &ValueMap,
8505c2d335d86579941b71816196a95a64b277e8963Chris Lattner                            std::string *Err) {
8518d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  // Loop over all of the globals in the src module, mapping them over as we go
8521127315562b221010040925980040fd4f65bdb1cChris Lattner  for (Module::const_global_iterator I = Src->global_begin(),
8531127315562b221010040925980040fd4f65bdb1cChris Lattner       E = Src->global_end(); I != E; ++I) {
85418961504fc2b299578dba817900a0696cf3ccc4dChris Lattner    const GlobalVariable *SGV = I;
8558d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner
8568d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner    if (SGV->hasInitializer()) {      // Only process initialized GV's
8578d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner      // Figure out what the initializer looks like in the dest module...
8584ad02e726d9b634372b037d4b352d8b63bb9e849Chris Lattner      Constant *SInit =
8590033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner        cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
860d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      // Grab destination global variable or alias.
861d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
862d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov
863d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      // If dest if global variable, check that initializers match.
864d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov      if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
865d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        if (DGVar->hasInitializer()) {
866d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          if (SGV->hasExternalLinkage()) {
867d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            if (DGVar->getInitializer() != SInit)
868d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov              return Error(Err, "Global Variable Collision on '" +
869d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov                           SGV->getName() +
870d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov                           "': global variables have different initializers");
871d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          } else if (DGVar->mayBeOverridden()) {
872d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            // Nothing is required, mapped values will take the new global
873d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            // automatically.
874d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          } else if (SGV->mayBeOverridden()) {
875d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            // Nothing is required, mapped values will take the new global
876d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            // automatically.
877d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          } else if (DGVar->hasAppendingLinkage()) {
878d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            assert(0 && "Appending linkage unimplemented!");
879d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          } else {
880d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov            assert(0 && "Unknown linkage!");
881d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          }
8824ad02e726d9b634372b037d4b352d8b63bb9e849Chris Lattner        } else {
883d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          // Copy the initializer over now...
884d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov          DGVar->setInitializer(SInit);
8854ad02e726d9b634372b037d4b352d8b63bb9e849Chris Lattner        }
8868d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner      } else {
887d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        // Destination is alias, the only valid situation is when source is
888d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        // weak. Also, note, that we already checked linkage in LinkGlobals(),
889d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        // thus we assert here.
890d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        // FIXME: Should we weaken this assumption, 'dereference' alias and
891d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        // check for initializer of aliasee?
892d13726f1e91218bc3f7103adf6cd98676bc477e2Anton Korobeynikov        assert(SGV->mayBeOverridden());
8938d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner      }
8948d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner    }
8958d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  }
8968d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner  return false;
8978d2de8a82cce67513debee7a3fa5aca0189b4105Chris Lattner}
8985c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
89979df7c0aaa18129e55968c8783ef8346807bd4afChris Lattner// LinkFunctionProtos - Link the functions together between the two modules,
900c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// without doing function bodies... this just adds external function prototypes
901c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// to the Dest function...
9025c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner//
90379df7c0aaa18129e55968c8783ef8346807bd4afChris Lattnerstatic bool LinkFunctionProtos(Module *Dest, const Module *Src,
9045c2d335d86579941b71816196a95a64b277e8963Chris Lattner                               std::map<const Value*, Value*> &ValueMap,
9055c2d335d86579941b71816196a95a64b277e8963Chris Lattner                               std::string *Err) {
906d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner  ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
907d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
908619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer  // Loop over all of the functions in the src module, mapping them over
9095c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
91018961504fc2b299578dba817900a0696cf3ccc4dChris Lattner    const Function *SF = I;   // SrcFunction
911194c2cef8a0036dd4e6295d048f37d6130f92389Anton Korobeynikov    GlobalValue *DGV = 0;
912824684982968244050e56357e736b9940c23e77dChris Lattner
913d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // Check to see if may have to link the function with the global, alias or
914d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // function.
915d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    if (SF->hasName() && !SF->hasInternalLinkage())
916d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
917d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner                                                        SF->getNameEnd()));
918d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner
919ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    // If we found a global with the same name in the dest module, but it has
920ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    // internal linkage, we are really not doing any linkage here.
921ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner    if (DGV && DGV->hasInternalLinkage())
922ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner      DGV = 0;
923ae1132d2b8ae07afd2fe9a7cb434d849f884bfa0Chris Lattner
924d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    // If types don't agree due to opaque types, try to resolve them.
925d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner    if (DGV && DGV->getType() != SF->getType())
926d1ec48c641f76d4c0e5b7cb357a1333d4fb75c4aChris Lattner      RecursiveResolveTypes(SF->getType(), DGV->getType());
927194c2cef8a0036dd4e6295d048f37d6130f92389Anton Korobeynikov
9286157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
9296157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    bool LinkFromSrc = false;
9306157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
9316157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      return true;
9326157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
933824684982968244050e56357e736b9940c23e77dChris Lattner    // If there is no linkage to be performed, just bring over SF without
934824684982968244050e56357e736b9940c23e77dChris Lattner    // modifying it.
935194c2cef8a0036dd4e6295d048f37d6130f92389Anton Korobeynikov    if (DGV == 0) {
936824684982968244050e56357e736b9940c23e77dChris Lattner      // Function does not already exist, simply insert an function signature
937824684982968244050e56357e736b9940c23e77dChris Lattner      // identical to SF into the dest module.
938824684982968244050e56357e736b9940c23e77dChris Lattner      Function *NewDF = Function::Create(SF->getFunctionType(),
939824684982968244050e56357e736b9940c23e77dChris Lattner                                         SF->getLinkage(),
940824684982968244050e56357e736b9940c23e77dChris Lattner                                         SF->getName(), Dest);
941824684982968244050e56357e736b9940c23e77dChris Lattner      CopyGVAttributes(NewDF, SF);
942824684982968244050e56357e736b9940c23e77dChris Lattner
943824684982968244050e56357e736b9940c23e77dChris Lattner      // If the LLVM runtime renamed the function, but it is an externally
944824684982968244050e56357e736b9940c23e77dChris Lattner      // visible symbol, DF must be an existing function with internal linkage.
945824684982968244050e56357e736b9940c23e77dChris Lattner      // Rename it.
946824684982968244050e56357e736b9940c23e77dChris Lattner      if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
947824684982968244050e56357e736b9940c23e77dChris Lattner        ForceRenaming(NewDF, SF->getName());
948824684982968244050e56357e736b9940c23e77dChris Lattner
949824684982968244050e56357e736b9940c23e77dChris Lattner      // ... and remember this mapping...
950824684982968244050e56357e736b9940c23e77dChris Lattner      ValueMap[SF] = NewDF;
951824684982968244050e56357e736b9940c23e77dChris Lattner      continue;
95297f8b0900abddfa72fd59e777399280adb4ca0a6Chris Lattner    }
953ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer
9546157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // If the visibilities of the symbols disagree and the destination is a
9556157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // prototype, take the visibility of its input.
9566157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (DGV->isDeclaration())
9576157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      DGV->setVisibility(SF->getVisibility());
958824684982968244050e56357e736b9940c23e77dChris Lattner
9596157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (LinkFromSrc) {
9606157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (isa<GlobalAlias>(DGV))
9616157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        return Error(Err, "Function-Alias Collision on '" + SF->getName() +
9626157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner                     "': symbol multiple defined");
9636157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
9646157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // We have a definition of the same name but different type in the
9656157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // source module. Copy the prototype to the destination and replace
9666157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // uses of the destination's prototype with the new prototype.
9676157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
9686157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner                                         SF->getName(), Dest);
9696157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      CopyGVAttributes(NewDF, SF);
9706157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
9716157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // Any uses of DF need to change to NewDF, with cast
9726157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
9736157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
9746157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // DF will conflict with NewDF because they both had the same. We must
9756157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // erase this now so ForceRenaming doesn't assert because DF might
9766157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // not have internal linkage.
9776157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
9786157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        Var->eraseFromParent();
9796157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      else
9806157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        cast<Function>(DGV)->eraseFromParent();
9816157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
9826157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // If the symbol table renamed the function, but it is an externally
9836157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // visible symbol, DF must be an existing function with internal
9846157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // linkage.  Rename it.
9856157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
9866157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        ForceRenaming(NewDF, SF->getName());
9876157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
9886157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // Remember this mapping so uses in the source module get remapped
9896157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // later by RemapOperand.
9906157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      ValueMap[SF] = NewDF;
991822143e6f7271c6546434d2d0b3da7a29711020dChris Lattner      continue;
992822143e6f7271c6546434d2d0b3da7a29711020dChris Lattner    }
993822143e6f7271c6546434d2d0b3da7a29711020dChris Lattner
9946157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Not "link from source", keep the one in the DestModule and remap the
9956157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // input onto it.
996822143e6f7271c6546434d2d0b3da7a29711020dChris Lattner
9976157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    if (isa<GlobalAlias>(DGV)) {
9986157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // The only valid mappings are:
9996157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // - SF is external declaration, which is effectively a no-op.
10006157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner      // - SF is weak, when we just need to throw SF out.
1001e655e3703280d001375ffa44093f8f4ec879c77bAnton Korobeynikov      if (!SF->isDeclaration() && !SF->mayBeOverridden())
10026157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner        return Error(Err, "Function-Alias Collision on '" + SF->getName() +
10036157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner                     "': symbol multiple defined");
1004822143e6f7271c6546434d2d0b3da7a29711020dChris Lattner    }
10056157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
10066157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Set calculated linkage
10076157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    DGV->setLinkage(NewLinkage);
10086157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner
10096157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    // Make sure to remember this mapping.
10106157e383c4a15ffb6e7f27cdb153daa9caa15ca5Chris Lattner    ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
10115c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  }
10125c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  return false;
10135c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
10145c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
1015c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// LinkFunctionBody - Copy the source function over into the dest function and
1016c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// fix up references to values.  At this point we know that Dest is an external
1017c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// function, and that Src is not.
10184bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattnerstatic bool LinkFunctionBody(Function *Dest, Function *Src,
1019ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer                             std::map<const Value*, Value*> &ValueMap,
10205c2d335d86579941b71816196a95a64b277e8963Chris Lattner                             std::string *Err) {
10215cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer  assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
10225c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10230033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner  // Go through and convert function arguments over, remembering the mapping.
1024e4d5c441e04bdc00ccf1804744af670655123b07Chris Lattner  Function::arg_iterator DI = Dest->arg_begin();
1025e4d5c441e04bdc00ccf1804744af670655123b07Chris Lattner  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
102669da5cf26143e4542d4bf8c78ffac6d079efe5c9Chris Lattner       I != E; ++I, ++DI) {
10276bc41e8a74d1756da0003641bfebd02a3d6d9586Owen Anderson    DI->setName(I->getName());  // Copy the name information over...
10285c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10295c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner    // Add a mapping to our local map
1030817bf2aeb22db13d03beb15e9bf17c425d0c694dAnton Korobeynikov    ValueMap[I] = DI;
10315c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  }
10325c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10334bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattner  // Splice the body of the source function into the dest function.
10344bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattner  Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
10355c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
1036c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // At this point, all of the instructions and values of the function are now
1037c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // copied over.  The only problem is that they are still referencing values in
1038c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // the Source function as operands.  Loop through all of the operands of the
1039c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // functions and patch them up to point to the local versions...
10405c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  //
104118961504fc2b299578dba817900a0696cf3ccc4dChris Lattner  for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
104218961504fc2b299578dba817900a0696cf3ccc4dChris Lattner    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
104318961504fc2b299578dba817900a0696cf3ccc4dChris Lattner      for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1044221d688a5ef21a22c2368c9fff0e92d7966c95e5Chris Lattner           OI != OE; ++OI)
10454bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattner        if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1046ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer          *OI = RemapOperand(*OI, ValueMap);
10470033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner
10480033baf94e049e075f3ba4700c109779e2d7c131Chris Lattner  // There is no need to map the arguments anymore.
10491127315562b221010040925980040fd4f65bdb1cChris Lattner  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
10501127315562b221010040925980040fd4f65bdb1cChris Lattner       I != E; ++I)
1051ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    ValueMap.erase(I);
10525c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10535c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  return false;
10545c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
10555c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10565c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
1057c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// LinkFunctionBodies - Link in the function bodies that are defined in the
1058c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// source module into the DestModule.  This consists basically of copying the
1059c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner// function over and fixing up references to values.
10604bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattnerstatic bool LinkFunctionBodies(Module *Dest, Module *Src,
10615c2d335d86579941b71816196a95a64b277e8963Chris Lattner                               std::map<const Value*, Value*> &ValueMap,
10625c2d335d86579941b71816196a95a64b277e8963Chris Lattner                               std::string *Err) {
10635c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10648bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer  // Loop over all of the functions in the src module, mapping them over as we
10658bef0373f1b8fab20b9acd277377ca01d72bac7eReid Spencer  // go
10664bbfbff119acab90fc67cd3d01b156bf88832286Chris Lattner  for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1067619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer    if (!SF->isDeclaration()) {               // No body if function is external
1068ec91ccba3ca92d5e1f19fb0cb6e57a7d4a3f3195Chris Lattner      Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1069c2d774b6c1d38421c435b6d3cfaa10402c900aebChris Lattner
107018961504fc2b299578dba817900a0696cf3ccc4dChris Lattner      // DF not external SF external?
1071ec91ccba3ca92d5e1f19fb0cb6e57a7d4a3f3195Chris Lattner      if (DF && DF->isDeclaration())
107235956558e26e655aaa2e8ad6ee405365271869a4Chris Lattner        // Only provide the function body if there isn't one already.
107335956558e26e655aaa2e8ad6ee405365271869a4Chris Lattner        if (LinkFunctionBody(DF, SF, ValueMap, Err))
107435956558e26e655aaa2e8ad6ee405365271869a4Chris Lattner          return true;
1075c2d774b6c1d38421c435b6d3cfaa10402c900aebChris Lattner    }
10765c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  }
10775c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  return false;
10785c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner}
10795c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
10808166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner// LinkAppendingVars - If there were any appending global variables, link them
10818166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner// together now.  Return true on error.
10828166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattnerstatic bool LinkAppendingVars(Module *M,
10838166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner                  std::multimap<std::string, GlobalVariable *> &AppendingVars,
10848166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner                              std::string *ErrorMsg) {
10858166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  if (AppendingVars.empty()) return false; // Nothing to do.
1086f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
10878166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // Loop over the multimap of appending vars, processing any variables with the
10888166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // same name, forming a new appending global variable with both of the
10898166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // initializers merged together, then rewrite references to the old variables
10908166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // and delete them.
10918166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  std::vector<Constant*> Inits;
10928166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  while (AppendingVars.size() > 1) {
10938166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    // Get the first two elements in the map...
10948166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    std::multimap<std::string,
10958166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
10968166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
10978166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    // If the first two elements are for different names, there is no pair...
10988166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    // Otherwise there is a pair, so link them together...
10998166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    if (First->first == Second->first) {
11008166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      GlobalVariable *G1 = First->second, *G2 = Second->second;
11018166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
11028166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1103f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
11048166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Check to see that they two arrays agree on type...
11058166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      if (T1->getElementType() != T2->getElementType())
11068166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner        return Error(ErrorMsg,
11078166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner         "Appending variables with different element types need to be linked!");
11088166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      if (G1->isConstant() != G2->isConstant())
11098166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner        return Error(ErrorMsg,
11108166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner                     "Appending variables linked with different const'ness!");
11118166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11129613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio      if (G1->getAlignment() != G2->getAlignment())
11139613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio        return Error(ErrorMsg,
11149613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio         "Appending variables with different alignment need to be linked!");
11159613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio
11169613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio      if (G1->getVisibility() != G2->getVisibility())
11179613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio        return Error(ErrorMsg,
11189613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio         "Appending variables with different visibility need to be linked!");
11199613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio
11209613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio      if (G1->getSection() != G2->getSection())
11219613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio        return Error(ErrorMsg,
11229613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio         "Appending variables with different section name need to be linked!");
11239613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio
11248166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      unsigned NewSize = T1->getNumElements() + T2->getNumElements();
11258166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
11268166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
1127ed74a4ef3b813bed0c0f4bb5af42229d50133da2Chris Lattner      G1->setName("");   // Clear G1's name in case of a conflict!
1128ed74a4ef3b813bed0c0f4bb5af42229d50133da2Chris Lattner
11298166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Create the new global variable...
11308166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      GlobalVariable *NG =
11318166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner        new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1132a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           /*init*/0, First->first, M, G1->isThreadLocal(),
1133a534b0f7bf0248bf90afe97110a34777e972f325Chris Lattner                           G1->getType()->getAddressSpace());
11348166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11359613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio      // Propagate alignment, visibility and section info.
11369613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio      CopyGVAttributes(NG, G1);
11379613e871d26f123789d98c61879b4dbe944a6d31Lauro Ramos Venancio
11388166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Merge the initializer...
11398166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      Inits.reserve(NewSize);
1140de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1141de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1142cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos          Inits.push_back(I->getOperand(i));
1143de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      } else {
1144de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1145de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        Constant *CV = Constant::getNullValue(T1->getElementType());
1146de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1147de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner          Inits.push_back(CV);
1148de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      }
1149de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1150de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1151cc7ba49d85b66955516ff0d9574a70e1637dea36Alkis Evlogimenos          Inits.push_back(I->getOperand(i));
1152de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      } else {
1153de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1154de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        Constant *CV = Constant::getNullValue(T2->getElementType());
1155de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner        for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1156de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner          Inits.push_back(CV);
1157de512b5b2edebe9c9021a92c7c7a9ae9fbc380d6Chris Lattner      }
11588166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      NG->setInitializer(ConstantArray::get(NewType, Inits));
11598166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      Inits.clear();
11608166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11618166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Replace any uses of the two global variables with uses of the new
11628166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // global...
11638166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11648166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // FIXME: This should rewrite simple/straight-forward uses such as
11658166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // getelementptr instructions to not use the Cast!
11664da49122f3f3c8da68a52723d846b88c72166a68Reid Spencer      G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
11674da49122f3f3c8da68a52723d846b88c72166a68Reid Spencer      G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
11688166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11698166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Remove the two globals from the module now...
11708166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      M->getGlobalList().erase(G1);
11718166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      M->getGlobalList().erase(G2);
11728166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11738166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // Put the new global into the AppendingVars map so that we can handle
11748166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      // linking of more than two vars...
11758166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner      Second->second = NG;
11768166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    }
11778166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner    AppendingVars.erase(First);
11788166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  }
11798166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
11808166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  return false;
11818166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner}
118252f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner
11839f2ee703663d8ca7d91cfdaf773fc70273e9e482Anton Korobeynikovstatic bool ResolveAliases(Module *Dest) {
11849f2ee703663d8ca7d91cfdaf773fc70273e9e482Anton Korobeynikov  for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
11855241957b1f6876452705f94e0ed60dd2c33a5c84Anton Korobeynikov       I != E; ++I)
118619e861a4ffb896f16a691d5ac869e894df3cd464Anton Korobeynikov    if (const GlobalValue *GV = I->resolveAliasedGlobal())
1187832b2a9cd8870211bf2d347d7b435beacbb06c8dAnton Korobeynikov      if (GV != I && !GV->isDeclaration())
11885241957b1f6876452705f94e0ed60dd2c33a5c84Anton Korobeynikov        I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
11899f2ee703663d8ca7d91cfdaf773fc70273e9e482Anton Korobeynikov
11909f2ee703663d8ca7d91cfdaf773fc70273e9e482Anton Korobeynikov  return false;
11919f2ee703663d8ca7d91cfdaf773fc70273e9e482Anton Korobeynikov}
119252f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner
119352f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner// LinkModules - This function links two modules together, with the resulting
119452f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner// left module modified to be the composite of the two input modules.  If an
119552f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
11965c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner// the problem.  Upon failure, the Dest module could be in a modified state, and
11975c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner// shouldn't be relied on to be consistent.
1198f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukmanbool
11990ba9e211bed7813949aaca97e6b15579c8188e05Reid SpencerLinker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
120057a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  assert(Dest != 0 && "Invalid Destination module");
120157a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  assert(Src  != 0 && "Invalid Source Module");
120257a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer
1203c36357c406911ded5a0e2924998d885815370fdbChris Lattner  if (Dest->getDataLayout().empty()) {
1204c36357c406911ded5a0e2924998d885815370fdbChris Lattner    if (!Src->getDataLayout().empty()) {
1205ec9bfdc152a870d3c62377ed6855fb3bff69511cChris Lattner      Dest->setDataLayout(Src->getDataLayout());
1206c36357c406911ded5a0e2924998d885815370fdbChris Lattner    } else {
1207c36357c406911ded5a0e2924998d885815370fdbChris Lattner      std::string DataLayout;
1208c36357c406911ded5a0e2924998d885815370fdbChris Lattner
1209a27694d7aac1bfcec2b776df460719b4a165a79aAnton Korobeynikov      if (Dest->getEndianness() == Module::AnyEndianness) {
1210c36357c406911ded5a0e2924998d885815370fdbChris Lattner        if (Src->getEndianness() == Module::BigEndian)
1211c36357c406911ded5a0e2924998d885815370fdbChris Lattner          DataLayout.append("E");
1212c36357c406911ded5a0e2924998d885815370fdbChris Lattner        else if (Src->getEndianness() == Module::LittleEndian)
1213c36357c406911ded5a0e2924998d885815370fdbChris Lattner          DataLayout.append("e");
1214a27694d7aac1bfcec2b776df460719b4a165a79aAnton Korobeynikov      }
1215a27694d7aac1bfcec2b776df460719b4a165a79aAnton Korobeynikov
1216a27694d7aac1bfcec2b776df460719b4a165a79aAnton Korobeynikov      if (Dest->getPointerSize() == Module::AnyPointerSize) {
1217c36357c406911ded5a0e2924998d885815370fdbChris Lattner        if (Src->getPointerSize() == Module::Pointer64)
1218c36357c406911ded5a0e2924998d885815370fdbChris Lattner          DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1219c36357c406911ded5a0e2924998d885815370fdbChris Lattner        else if (Src->getPointerSize() == Module::Pointer32)
1220c36357c406911ded5a0e2924998d885815370fdbChris Lattner          DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1221a27694d7aac1bfcec2b776df460719b4a165a79aAnton Korobeynikov      }
1222c36357c406911ded5a0e2924998d885815370fdbChris Lattner      Dest->setDataLayout(DataLayout);
1223c36357c406911ded5a0e2924998d885815370fdbChris Lattner    }
1224c36357c406911ded5a0e2924998d885815370fdbChris Lattner  }
1225873c5e7859c1534bf92c9e2747f2b70685059598Chris Lattner
1226f27dfcb210fec571d79bc881f5463e0b405707c0Chris Lattner  // Copy the target triple from the source to dest if the dest's is empty.
1227c36357c406911ded5a0e2924998d885815370fdbChris Lattner  if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1228c36357c406911ded5a0e2924998d885815370fdbChris Lattner    Dest->setTargetTriple(Src->getTargetTriple());
1229c36357c406911ded5a0e2924998d885815370fdbChris Lattner
1230c36357c406911ded5a0e2924998d885815370fdbChris Lattner  if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1231c36357c406911ded5a0e2924998d885815370fdbChris Lattner      Src->getDataLayout() != Dest->getDataLayout())
123226f238589f9bb372d24b6fb2bc32edbf046fd9eeReid Spencer    cerr << "WARNING: Linking two modules of different data layouts!\n";
1233152f19ac6514ec29e183ddcdf2ea71599638dc4cChris Lattner  if (!Src->getTargetTriple().empty() &&
1234152f19ac6514ec29e183ddcdf2ea71599638dc4cChris Lattner      Dest->getTargetTriple() != Src->getTargetTriple())
1235e81561909d128c6e2d8033cb5465a49b2596b26aBill Wendling    cerr << "WARNING: Linking two modules of different target triples!\n";
1236f976c856fcc5055f3fc7d9f070d72c2d027c1d9dMisha Brukman
1237f27dfcb210fec571d79bc881f5463e0b405707c0Chris Lattner  // Append the module inline asm string.
12386631601eeda2300abdce11fbd7a7a3daa2694d39Chris Lattner  if (!Src->getModuleInlineAsm().empty()) {
12396631601eeda2300abdce11fbd7a7a3daa2694d39Chris Lattner    if (Dest->getModuleInlineAsm().empty())
12406631601eeda2300abdce11fbd7a7a3daa2694d39Chris Lattner      Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1241e1b2e14f92e8e9da1eb4854511a881cf9c22af3cChris Lattner    else
12426631601eeda2300abdce11fbd7a7a3daa2694d39Chris Lattner      Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
12436631601eeda2300abdce11fbd7a7a3daa2694d39Chris Lattner                               Src->getModuleInlineAsm());
1244e1b2e14f92e8e9da1eb4854511a881cf9c22af3cChris Lattner  }
1245e1b2e14f92e8e9da1eb4854511a881cf9c22af3cChris Lattner
1246719012d6254ee425464f034250176283fb96793bReid Spencer  // Update the destination module's dependent libraries list with the libraries
124757a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  // from the source module. There's no opportunity for duplicates here as the
124857a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  // Module ensures that duplicate insertions are discarded.
1249f27dfcb210fec571d79bc881f5463e0b405707c0Chris Lattner  for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1250f27dfcb210fec571d79bc881f5463e0b405707c0Chris Lattner       SI != SE; ++SI)
125157a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer    Dest->addLibrary(*SI);
125257a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer
12532c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  // LinkTypes - Go through the symbol table of the Src module and see if any
12542c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  // types are named in the src module that are not named in the Dst module.
12552c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner  // Make sure there are no type name conflicts.
1256619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer  if (LinkTypes(Dest, Src, ErrorMsg))
1257619f024cc315b9edcc6bc71ebea68fd44d85aeafReid Spencer    return true;
12582c236f3e20a0fb84b5948efa6bb7bb60d759cb32Chris Lattner
12595c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  // ValueMap - Mapping of values from what they used to be in Src, to what they
12605c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner  // are now in Dest.
12615c2d335d86579941b71816196a95a64b277e8963Chris Lattner  std::map<const Value*, Value*> ValueMap;
12625c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
12638166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // AppendingVars - Keep track of global variables in the destination module
12648166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // with appending linkage.  After the module is linked together, they are
12658166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // appended and the module is rewritten.
12668166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  std::multimap<std::string, GlobalVariable *> AppendingVars;
12671127315562b221010040925980040fd4f65bdb1cChris Lattner  for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
12681127315562b221010040925980040fd4f65bdb1cChris Lattner       I != E; ++I) {
12695a837defff581accc09048bea1cd839009e374a7Chris Lattner    // Add all of the appending globals already in the Dest module to
12705a837defff581accc09048bea1cd839009e374a7Chris Lattner    // AppendingVars.
1271f41464618f41b92cf0a0bd14ccc57bce727fb33dChris Lattner    if (I->hasAppendingLinkage())
1272f41464618f41b92cf0a0bd14ccc57bce727fb33dChris Lattner      AppendingVars.insert(std::make_pair(I->getName(), I));
12735a837defff581accc09048bea1cd839009e374a7Chris Lattner  }
12745a837defff581accc09048bea1cd839009e374a7Chris Lattner
12758166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // Insert all of the globals in src into the Dest module... without linking
12768166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // initializers (which could refer to functions not yet mapped over).
1277ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer  if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
12785a837defff581accc09048bea1cd839009e374a7Chris Lattner    return true;
12795c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
1280c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // Link the functions together between the two modules, without doing function
1281c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // bodies... this just adds external function prototypes to the Dest
1282c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // function...  We do this so that when we begin processing function bodies,
1283c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // all of the global values that may be referenced are available in our
1284c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // ValueMap.
1285ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer  if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
12865a837defff581accc09048bea1cd839009e374a7Chris Lattner    return true;
12875c377c524a6929cdaa683f3f034b3fc01526b264Chris Lattner
12884fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov  // If there were any alias, link them now. We really need to do this now,
12894fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov  // because all of the aliases that may be referenced need to be available in
12904fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov  // ValueMap
12914fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov  if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
12924fb2873bb46330da18f413cec661ce2fd0f9f37cAnton Korobeynikov
12936cdf1971bdf88ddd9a7d46b5f5f975497d68c38eChris Lattner  // Update the initializers in the Dest module now that all globals that may
12946cdf1971bdf88ddd9a7d46b5f5f975497d68c38eChris Lattner  // be referenced are in Dest.
12956cdf1971bdf88ddd9a7d46b5f5f975497d68c38eChris Lattner  if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
12966cdf1971bdf88ddd9a7d46b5f5f975497d68c38eChris Lattner
1297c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // Link in the function bodies that are defined in the source module into the
1298c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // DestModule.  This consists basically of copying the function over and
1299c8cc4cb03bd90f89be7fe1649542a2d5ae689632Chris Lattner  // fixing up references to values.
130079df7c0aaa18129e55968c8783ef8346807bd4afChris Lattner  if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
130152f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner
13028166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  // If there were any appending global variables, link them together now.
13038166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner  if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
13048166e6eef6518da6f1f805e0d5e2bb22c15dd49cChris Lattner
13053db9191baf5f5229a2f4d204c6332ba27fff81d0Anton Korobeynikov  // Resolve all uses of aliases with aliasees
13063db9191baf5f5229a2f4d204c6332ba27fff81d0Anton Korobeynikov  if (ResolveAliases(Dest)) return true;
13073db9191baf5f5229a2f4d204c6332ba27fff81d0Anton Korobeynikov
130857a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  // If the source library's module id is in the dependent library list of the
130957a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  // destination library, remove it since that module is now linked in.
131057a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer  sys::Path modId;
1311dd04df0ec33a903ee7fc747701bafde622f77d8bReid Spencer  modId.set(Src->getModuleIdentifier());
131207adb2836b8aa7a3872e33c285958f5937662b50Reid Spencer  if (!modId.isEmpty())
131307adb2836b8aa7a3872e33c285958f5937662b50Reid Spencer    Dest->removeLibrary(modId.getBasename());
131457a0efa32240ef03ea318f9ba7680fd2b8609c6eReid Spencer
131552f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner  return false;
131652f7e908cb634f9b9b539d5c6670b8a065478915Chris Lattner}
13179466f5113ba859677a28887c3c7143065e702019Vikram S. Adve
1318567bc2cc1ed4d610daceecbb4ff7f92ebde1b530Reid Spencer// vim: sw=2
1319