1361e513dSReid Spencer //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7361e513dSReid Spencer // 8361e513dSReid Spencer //===----------------------------------------------------------------------===// 9361e513dSReid Spencer // 10361e513dSReid Spencer // This file implements the LLVM module linker. 11361e513dSReid Spencer // 12361e513dSReid Spencer // Specifically, this: 13361e513dSReid Spencer // * Merges global variables between the two modules 14361e513dSReid Spencer // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if != 15361e513dSReid Spencer // * Merges functions between two modules 16361e513dSReid Spencer // 17361e513dSReid Spencer //===----------------------------------------------------------------------===// 18361e513dSReid Spencer 199b0ddbbeSReid Spencer #include "llvm/Linker.h" 20361e513dSReid Spencer #include "llvm/Constants.h" 21361e513dSReid Spencer #include "llvm/DerivedTypes.h" 22361e513dSReid Spencer #include "llvm/Module.h" 2332af9e8cSReid Spencer #include "llvm/TypeSymbolTable.h" 243aaaa0b2SReid Spencer #include "llvm/ValueSymbolTable.h" 25361e513dSReid Spencer #include "llvm/Instructions.h" 26361e513dSReid Spencer #include "llvm/Assembly/Writer.h" 277339b8dbSBill Wendling #include "llvm/Support/Streams.h" 28361e513dSReid Spencer #include "llvm/System/Path.h" 29eee6f995SChris Lattner #include "llvm/ADT/DenseMap.h" 3030c0f336SBill Wendling #include <sstream> 31361e513dSReid Spencer using namespace llvm; 32361e513dSReid Spencer 33361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true. 34361e513dSReid Spencer // This just makes error return conditions a little bit simpler... 35361e513dSReid Spencer static inline bool Error(std::string *E, const std::string &Message) { 36361e513dSReid Spencer if (E) *E = Message; 37361e513dSReid Spencer return true; 38361e513dSReid Spencer } 39361e513dSReid Spencer 40361e513dSReid Spencer // Function: ResolveTypes() 41361e513dSReid Spencer // 42361e513dSReid Spencer // Description: 43361e513dSReid Spencer // Attempt to link the two specified types together. 44361e513dSReid Spencer // 45361e513dSReid Spencer // Inputs: 46361e513dSReid Spencer // DestTy - The type to which we wish to resolve. 47361e513dSReid Spencer // SrcTy - The original type which we want to resolve. 48361e513dSReid Spencer // 49361e513dSReid Spencer // Outputs: 50361e513dSReid Spencer // DestST - The symbol table in which the new type should be placed. 51361e513dSReid Spencer // 52361e513dSReid Spencer // Return value: 53361e513dSReid Spencer // true - There is an error and the types cannot yet be linked. 54361e513dSReid Spencer // false - No errors. 55361e513dSReid Spencer // 568aa89e41SChris Lattner static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) { 57361e513dSReid Spencer if (DestTy == SrcTy) return false; // If already equal, noop 588aa89e41SChris Lattner assert(DestTy && SrcTy && "Can't handle null types"); 59361e513dSReid Spencer 608aa89e41SChris Lattner if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) { 618aa89e41SChris Lattner // Type _is_ in module, just opaque... 628aa89e41SChris Lattner const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy); 638aa89e41SChris Lattner } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) { 64361e513dSReid Spencer const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy); 65361e513dSReid Spencer } else { 668aa89e41SChris Lattner return true; // Cannot link types... not-equal and neither is opaque. 67361e513dSReid Spencer } 68361e513dSReid Spencer return false; 69361e513dSReid Spencer } 70361e513dSReid Spencer 71eee6f995SChris Lattner /// LinkerTypeMap - This implements a map of types that is stable 72eee6f995SChris Lattner /// even if types are resolved/refined to other types. This is not a general 73eee6f995SChris Lattner /// purpose map, it is specific to the linker's use. 74eee6f995SChris Lattner namespace { 75eee6f995SChris Lattner class LinkerTypeMap : public AbstractTypeUser { 76eee6f995SChris Lattner typedef DenseMap<const Type*, PATypeHolder> TheMapTy; 77eee6f995SChris Lattner TheMapTy TheMap; 78eee6f995SChris Lattner 7956cdea6bSChris Lattner LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT 8056cdea6bSChris Lattner void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT 8156cdea6bSChris Lattner public: 8256cdea6bSChris Lattner LinkerTypeMap() {} 8356cdea6bSChris Lattner ~LinkerTypeMap() { 84eee6f995SChris Lattner for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(), 85eee6f995SChris Lattner E = TheMap.end(); I != E; ++I) 86eee6f995SChris Lattner I->first->removeAbstractTypeUser(this); 87eee6f995SChris Lattner } 88eee6f995SChris Lattner 89eee6f995SChris Lattner /// lookup - Return the value for the specified type or null if it doesn't 90eee6f995SChris Lattner /// exist. 91eee6f995SChris Lattner const Type *lookup(const Type *Ty) const { 92eee6f995SChris Lattner TheMapTy::const_iterator I = TheMap.find(Ty); 93eee6f995SChris Lattner if (I != TheMap.end()) return I->second; 94eee6f995SChris Lattner return 0; 95eee6f995SChris Lattner } 96eee6f995SChris Lattner 97eee6f995SChris Lattner /// erase - Remove the specified type, returning true if it was in the set. 98eee6f995SChris Lattner bool erase(const Type *Ty) { 99eee6f995SChris Lattner if (!TheMap.erase(Ty)) 100eee6f995SChris Lattner return false; 101eee6f995SChris Lattner if (Ty->isAbstract()) 102eee6f995SChris Lattner Ty->removeAbstractTypeUser(this); 103eee6f995SChris Lattner return true; 104eee6f995SChris Lattner } 105eee6f995SChris Lattner 106eee6f995SChris Lattner /// insert - This returns true if the pointer was new to the set, false if it 107eee6f995SChris Lattner /// was already in the set. 108eee6f995SChris Lattner bool insert(const Type *Src, const Type *Dst) { 10938740a98SDan Gohman if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second) 110eee6f995SChris Lattner return false; // Already in map. 111eee6f995SChris Lattner if (Src->isAbstract()) 112eee6f995SChris Lattner Src->addAbstractTypeUser(this); 113eee6f995SChris Lattner return true; 114eee6f995SChris Lattner } 115eee6f995SChris Lattner 116eee6f995SChris Lattner protected: 117eee6f995SChris Lattner /// refineAbstractType - The callback method invoked when an abstract type is 118eee6f995SChris Lattner /// resolved to another type. An object must override this method to update 119eee6f995SChris Lattner /// its internal state to reference NewType instead of OldType. 120eee6f995SChris Lattner /// 121eee6f995SChris Lattner virtual void refineAbstractType(const DerivedType *OldTy, 122eee6f995SChris Lattner const Type *NewTy) { 123eee6f995SChris Lattner TheMapTy::iterator I = TheMap.find(OldTy); 124eee6f995SChris Lattner const Type *DstTy = I->second; 125eee6f995SChris Lattner 126eee6f995SChris Lattner TheMap.erase(I); 127eee6f995SChris Lattner if (OldTy->isAbstract()) 128eee6f995SChris Lattner OldTy->removeAbstractTypeUser(this); 129eee6f995SChris Lattner 130eee6f995SChris Lattner // Don't reinsert into the map if the key is concrete now. 131eee6f995SChris Lattner if (NewTy->isAbstract()) 132eee6f995SChris Lattner insert(NewTy, DstTy); 133eee6f995SChris Lattner } 134eee6f995SChris Lattner 135eee6f995SChris Lattner /// The other case which AbstractTypeUsers must be aware of is when a type 136eee6f995SChris Lattner /// makes the transition from being abstract (where it has clients on it's 137eee6f995SChris Lattner /// AbstractTypeUsers list) to concrete (where it does not). This method 138eee6f995SChris Lattner /// notifies ATU's when this occurs for a type. 139eee6f995SChris Lattner virtual void typeBecameConcrete(const DerivedType *AbsTy) { 140eee6f995SChris Lattner TheMap.erase(AbsTy); 141eee6f995SChris Lattner AbsTy->removeAbstractTypeUser(this); 142eee6f995SChris Lattner } 143eee6f995SChris Lattner 144eee6f995SChris Lattner // for debugging... 145eee6f995SChris Lattner virtual void dump() const { 146eee6f995SChris Lattner cerr << "AbstractTypeSet!\n"; 147eee6f995SChris Lattner } 148eee6f995SChris Lattner }; 149eee6f995SChris Lattner } 150eee6f995SChris Lattner 151eee6f995SChris Lattner 152361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it 153361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types 154361e513dSReid Spencer // are compatible. 1559be15893SChris Lattner static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy, 156eee6f995SChris Lattner LinkerTypeMap &Pointers) { 1579be15893SChris Lattner if (DstTy == SrcTy) return false; // If already equal, noop 158361e513dSReid Spencer 159361e513dSReid Spencer // If we found our opaque type, resolve it now! 1609be15893SChris Lattner if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy)) 1619be15893SChris Lattner return ResolveTypes(DstTy, SrcTy); 162361e513dSReid Spencer 163361e513dSReid Spencer // Two types cannot be resolved together if they are of different primitive 164361e513dSReid Spencer // type. For example, we cannot resolve an int to a float. 1659be15893SChris Lattner if (DstTy->getTypeID() != SrcTy->getTypeID()) return true; 166361e513dSReid Spencer 167fe677e95SChris Lattner // If neither type is abstract, then they really are just different types. 1689be15893SChris Lattner if (!DstTy->isAbstract() && !SrcTy->isAbstract()) 169fe677e95SChris Lattner return true; 170fe677e95SChris Lattner 171361e513dSReid Spencer // Otherwise, resolve the used type used by this derived type... 1729be15893SChris Lattner switch (DstTy->getTypeID()) { 1739995302bSChris Lattner default: 1747a9c62baSReid Spencer return true; 175361e513dSReid Spencer case Type::FunctionTyID: { 1769be15893SChris Lattner const FunctionType *DstFT = cast<FunctionType>(DstTy); 1779be15893SChris Lattner const FunctionType *SrcFT = cast<FunctionType>(SrcTy); 17885b66d18SChris Lattner if (DstFT->isVarArg() != SrcFT->isVarArg() || 17985b66d18SChris Lattner DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes()) 180361e513dSReid Spencer return true; 1819be15893SChris Lattner 1829be15893SChris Lattner // Use TypeHolder's so recursive resolution won't break us. 1839be15893SChris Lattner PATypeHolder ST(SrcFT), DT(DstFT); 1849be15893SChris Lattner for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) { 1859be15893SChris Lattner const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i); 1869be15893SChris Lattner if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers)) 187361e513dSReid Spencer return true; 1889be15893SChris Lattner } 189361e513dSReid Spencer return false; 190361e513dSReid Spencer } 191361e513dSReid Spencer case Type::StructTyID: { 1929be15893SChris Lattner const StructType *DstST = cast<StructType>(DstTy); 1939be15893SChris Lattner const StructType *SrcST = cast<StructType>(SrcTy); 19485b66d18SChris Lattner if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes()) 1959995302bSChris Lattner return true; 1969be15893SChris Lattner 1979be15893SChris Lattner PATypeHolder ST(SrcST), DT(DstST); 1989be15893SChris Lattner for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) { 1999be15893SChris Lattner const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i); 2009be15893SChris Lattner if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers)) 201361e513dSReid Spencer return true; 2029be15893SChris Lattner } 203361e513dSReid Spencer return false; 204361e513dSReid Spencer } 205361e513dSReid Spencer case Type::ArrayTyID: { 2069be15893SChris Lattner const ArrayType *DAT = cast<ArrayType>(DstTy); 2079be15893SChris Lattner const ArrayType *SAT = cast<ArrayType>(SrcTy); 208361e513dSReid Spencer if (DAT->getNumElements() != SAT->getNumElements()) return true; 209361e513dSReid Spencer return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(), 2108aa89e41SChris Lattner Pointers); 211361e513dSReid Spencer } 2129995302bSChris Lattner case Type::VectorTyID: { 2139be15893SChris Lattner const VectorType *DVT = cast<VectorType>(DstTy); 2149be15893SChris Lattner const VectorType *SVT = cast<VectorType>(SrcTy); 2159995302bSChris Lattner if (DVT->getNumElements() != SVT->getNumElements()) return true; 2169995302bSChris Lattner return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(), 2179995302bSChris Lattner Pointers); 2189995302bSChris Lattner } 219361e513dSReid Spencer case Type::PointerTyID: { 2209be15893SChris Lattner const PointerType *DstPT = cast<PointerType>(DstTy); 2219be15893SChris Lattner const PointerType *SrcPT = cast<PointerType>(SrcTy); 22285b66d18SChris Lattner 22385b66d18SChris Lattner if (DstPT->getAddressSpace() != SrcPT->getAddressSpace()) 22485b66d18SChris Lattner return true; 22585b66d18SChris Lattner 226361e513dSReid Spencer // If this is a pointer type, check to see if we have already seen it. If 227361e513dSReid Spencer // so, we are in a recursive branch. Cut off the search now. We cannot use 228361e513dSReid Spencer // an associative container for this search, because the type pointers (keys 229eee6f995SChris Lattner // in the container) change whenever types get resolved. 230eee6f995SChris Lattner if (SrcPT->isAbstract()) 231eee6f995SChris Lattner if (const Type *ExistingDestTy = Pointers.lookup(SrcPT)) 232eee6f995SChris Lattner return ExistingDestTy != DstPT; 233eee6f995SChris Lattner 234eee6f995SChris Lattner if (DstPT->isAbstract()) 235eee6f995SChris Lattner if (const Type *ExistingSrcTy = Pointers.lookup(DstPT)) 236eee6f995SChris Lattner return ExistingSrcTy != SrcPT; 237361e513dSReid Spencer // Otherwise, add the current pointers to the vector to stop recursion on 238361e513dSReid Spencer // this pair. 239eee6f995SChris Lattner if (DstPT->isAbstract()) 240eee6f995SChris Lattner Pointers.insert(DstPT, SrcPT); 241eee6f995SChris Lattner if (SrcPT->isAbstract()) 242eee6f995SChris Lattner Pointers.insert(SrcPT, DstPT); 2439be15893SChris Lattner 24485b66d18SChris Lattner return RecursiveResolveTypesI(DstPT->getElementType(), 24585b66d18SChris Lattner SrcPT->getElementType(), Pointers); 246361e513dSReid Spencer } 247361e513dSReid Spencer } 248361e513dSReid Spencer } 249361e513dSReid Spencer 2509be15893SChris Lattner static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) { 251eee6f995SChris Lattner LinkerTypeMap PointerTypes; 2528aa89e41SChris Lattner return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes); 253361e513dSReid Spencer } 254361e513dSReid Spencer 255361e513dSReid Spencer 256361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 257361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 258361e513dSReid Spencer // Make sure there are no type name conflicts. 259361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) { 26032af9e8cSReid Spencer TypeSymbolTable *DestST = &Dest->getTypeSymbolTable(); 26132af9e8cSReid Spencer const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable(); 262361e513dSReid Spencer 263361e513dSReid Spencer // Look for a type plane for Type's... 26432af9e8cSReid Spencer TypeSymbolTable::const_iterator TI = SrcST->begin(); 26532af9e8cSReid Spencer TypeSymbolTable::const_iterator TE = SrcST->end(); 266361e513dSReid Spencer if (TI == TE) return false; // No named types, do nothing. 267361e513dSReid Spencer 268361e513dSReid Spencer // Some types cannot be resolved immediately because they depend on other 269361e513dSReid Spencer // types being resolved to each other first. This contains a list of types we 270361e513dSReid Spencer // are waiting to recheck. 271361e513dSReid Spencer std::vector<std::string> DelayedTypesToResolve; 272361e513dSReid Spencer 273361e513dSReid Spencer for ( ; TI != TE; ++TI ) { 274361e513dSReid Spencer const std::string &Name = TI->first; 275361e513dSReid Spencer const Type *RHS = TI->second; 276361e513dSReid Spencer 2778aa89e41SChris Lattner // Check to see if this type name is already in the dest module. 27832af9e8cSReid Spencer Type *Entry = DestST->lookup(Name); 279361e513dSReid Spencer 2808aa89e41SChris Lattner // If the name is just in the source module, bring it over to the dest. 2818aa89e41SChris Lattner if (Entry == 0) { 2828aa89e41SChris Lattner if (!Name.empty()) 283e9bb8552SChris Lattner DestST->insert(Name, const_cast<Type*>(RHS)); 2848aa89e41SChris Lattner } else if (ResolveTypes(Entry, RHS)) { 285361e513dSReid Spencer // They look different, save the types 'till later to resolve. 286361e513dSReid Spencer DelayedTypesToResolve.push_back(Name); 287361e513dSReid Spencer } 288361e513dSReid Spencer } 289361e513dSReid Spencer 290361e513dSReid Spencer // Iteratively resolve types while we can... 291361e513dSReid Spencer while (!DelayedTypesToResolve.empty()) { 292361e513dSReid Spencer // Loop over all of the types, attempting to resolve them if possible... 293361e513dSReid Spencer unsigned OldSize = DelayedTypesToResolve.size(); 294361e513dSReid Spencer 295361e513dSReid Spencer // Try direct resolution by name... 296361e513dSReid Spencer for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) { 297361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 29832af9e8cSReid Spencer Type *T1 = SrcST->lookup(Name); 29932af9e8cSReid Spencer Type *T2 = DestST->lookup(Name); 3008aa89e41SChris Lattner if (!ResolveTypes(T2, T1)) { 301361e513dSReid Spencer // We are making progress! 302361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 303361e513dSReid Spencer --i; 304361e513dSReid Spencer } 305361e513dSReid Spencer } 306361e513dSReid Spencer 307361e513dSReid Spencer // Did we not eliminate any types? 308361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 309361e513dSReid Spencer // Attempt to resolve subelements of types. This allows us to merge these 310361e513dSReid Spencer // two types: { int* } and { opaque* } 311361e513dSReid Spencer for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) { 312361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 3139be15893SChris Lattner if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) { 314361e513dSReid Spencer // We are making progress! 315361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 316361e513dSReid Spencer 317361e513dSReid Spencer // Go back to the main loop, perhaps we can resolve directly by name 318361e513dSReid Spencer // now... 319361e513dSReid Spencer break; 320361e513dSReid Spencer } 321361e513dSReid Spencer } 322361e513dSReid Spencer 323361e513dSReid Spencer // If we STILL cannot resolve the types, then there is something wrong. 324361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 325361e513dSReid Spencer // Remove the symbol name from the destination. 326361e513dSReid Spencer DelayedTypesToResolve.pop_back(); 327361e513dSReid Spencer } 328361e513dSReid Spencer } 329361e513dSReid Spencer } 330361e513dSReid Spencer 331361e513dSReid Spencer 332361e513dSReid Spencer return false; 333361e513dSReid Spencer } 334361e513dSReid Spencer 335177a3008SChris Lattner #ifndef NDEBUG 336361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) { 337361e513dSReid Spencer for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end(); 338361e513dSReid Spencer I != E; ++I) { 339f3baad3eSBill Wendling cerr << " Fr: " << (void*)I->first << " "; 340361e513dSReid Spencer I->first->dump(); 341f3baad3eSBill Wendling cerr << " To: " << (void*)I->second << " "; 342361e513dSReid Spencer I->second->dump(); 343f3baad3eSBill Wendling cerr << "\n"; 344361e513dSReid Spencer } 345361e513dSReid Spencer } 346177a3008SChris Lattner #endif 347361e513dSReid Spencer 348361e513dSReid Spencer 349d3ba7d9bSReid Spencer // RemapOperand - Use ValueMap to convert constants from one module to another. 350361e513dSReid Spencer static Value *RemapOperand(const Value *In, 3517391dde1SChris Lattner std::map<const Value*, Value*> &ValueMap) { 3527391dde1SChris Lattner std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In); 3533aaaa0b2SReid Spencer if (I != ValueMap.end()) 3543aaaa0b2SReid Spencer return I->second; 355361e513dSReid Spencer 356d3ba7d9bSReid Spencer // Check to see if it's a constant that we are interested in transforming. 357c7745926SChris Lattner Value *Result = 0; 358361e513dSReid Spencer if (const Constant *CPV = dyn_cast<Constant>(In)) { 359361e513dSReid Spencer if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) || 3607a9c62baSReid Spencer isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV)) 3617391dde1SChris Lattner return const_cast<Constant*>(CPV); // Simple constants stay identical. 362361e513dSReid Spencer 363361e513dSReid Spencer if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) { 364361e513dSReid Spencer std::vector<Constant*> Operands(CPA->getNumOperands()); 365361e513dSReid Spencer for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 3667391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap)); 367361e513dSReid Spencer Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands); 368361e513dSReid Spencer } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) { 369361e513dSReid Spencer std::vector<Constant*> Operands(CPS->getNumOperands()); 370361e513dSReid Spencer for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 3717391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap)); 372361e513dSReid Spencer Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands); 373361e513dSReid Spencer } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) { 374361e513dSReid Spencer Result = const_cast<Constant*>(CPV); 375d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) { 37693bde9cbSChris Lattner std::vector<Constant*> Operands(CP->getNumOperands()); 37793bde9cbSChris Lattner for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 37893bde9cbSChris Lattner Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap)); 379d84d35baSReid Spencer Result = ConstantVector::get(Operands); 380361e513dSReid Spencer } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) { 38119247f36SChris Lattner std::vector<Constant*> Ops; 38219247f36SChris Lattner for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) 38319247f36SChris Lattner Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap))); 38419247f36SChris Lattner Result = CE->getWithOperands(Ops); 385361e513dSReid Spencer } else { 386177a3008SChris Lattner assert(!isa<GlobalValue>(CPV) && "Unmapped global?"); 387361e513dSReid Spencer assert(0 && "Unknown type of derived type constant value!"); 388361e513dSReid Spencer } 389c7745926SChris Lattner } else if (isa<InlineAsm>(In)) { 390c7745926SChris Lattner Result = const_cast<Value*>(In); 391c7745926SChris Lattner } 392361e513dSReid Spencer 393d3ba7d9bSReid Spencer // Cache the mapping in our local map structure 394c7745926SChris Lattner if (Result) { 39566a6271cSAnton Korobeynikov ValueMap[In] = Result; 396361e513dSReid Spencer return Result; 397361e513dSReid Spencer } 398361e513dSReid Spencer 399177a3008SChris Lattner #ifndef NDEBUG 400f3baad3eSBill Wendling cerr << "LinkModules ValueMap: \n"; 4017391dde1SChris Lattner PrintMap(ValueMap); 402361e513dSReid Spencer 403f3baad3eSBill Wendling cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n"; 404361e513dSReid Spencer assert(0 && "Couldn't remap value!"); 405177a3008SChris Lattner #endif 406361e513dSReid Spencer return 0; 407361e513dSReid Spencer } 408361e513dSReid Spencer 40990246aa7SReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict 41090246aa7SReid Spencer /// in the symbol table. This is good for all clients except for us. Go 41190246aa7SReid Spencer /// through the trouble to force this back. 412361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) { 413361e513dSReid Spencer assert(GV->getName() != Name && "Can't force rename to self"); 4143aaaa0b2SReid Spencer ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable(); 415361e513dSReid Spencer 416361e513dSReid Spencer // If there is a conflict, rename the conflict. 4172a8d2e0eSChris Lattner if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) { 418*6de96a1bSRafael Espindola assert(ConflictGV->hasLocalLinkage() && 41990246aa7SReid Spencer "Not conflicting with a static global, should link instead!"); 4202a8d2e0eSChris Lattner GV->takeName(ConflictGV); 421361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 4223aaaa0b2SReid Spencer assert(ConflictGV->getName() != Name && "ForceRenaming didn't work"); 4232a8d2e0eSChris Lattner } else { 4242a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 4253aaaa0b2SReid Spencer } 4263aaaa0b2SReid Spencer } 4273aaaa0b2SReid Spencer 4283aaaa0b2SReid Spencer /// CopyGVAttributes - copy additional attributes (those not needed to construct 4293aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV. 4303aaaa0b2SReid Spencer static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 431dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 432dd7daee8SDuncan Sands unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment()); 433dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 434dd7daee8SDuncan Sands DestGV->setAlignment(Alignment); 435361e513dSReid Spencer } 436361e513dSReid Spencer 437fc61de39SChris Lattner /// GetLinkageResult - This analyzes the two global values and determines what 438fc61de39SChris Lattner /// the result will look like in the destination module. In particular, it 439fc61de39SChris Lattner /// computes the resultant linkage type, computes whether the global in the 440fc61de39SChris Lattner /// source should be copied over to the destination (replacing the existing 44131fc4f95SAnton Korobeynikov /// one), and computes whether this linkage is an error or not. It also performs 44231fc4f95SAnton Korobeynikov /// visibility checks: we cannot link together two symbols with different 44331fc4f95SAnton Korobeynikov /// visibilities. 444f6439246SAnton Korobeynikov static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 445fc61de39SChris Lattner GlobalValue::LinkageTypes <, bool &LinkFromSrc, 446fc61de39SChris Lattner std::string *Err) { 447*6de96a1bSRafael Espindola assert((!Dest || !Src->hasLocalLinkage()) && 448fc61de39SChris Lattner "If Src has internal linkage, Dest shouldn't be set!"); 449fc61de39SChris Lattner if (!Dest) { 450fc61de39SChris Lattner // Linking something to nothing. 451fc61de39SChris Lattner LinkFromSrc = true; 452fc61de39SChris Lattner LT = Src->getLinkage(); 4535301e7c6SReid Spencer } else if (Src->isDeclaration()) { 4541f93c50aSAnton Korobeynikov // If Src is external or if both Src & Dest are external.. Just link the 455fc61de39SChris Lattner // external globals, we aren't adding anything. 456d61d39ecSAnton Korobeynikov if (Src->hasDLLImportLinkage()) { 45712c94949SAnton Korobeynikov // If one of GVs has DLLImport linkage, result should be dllimport'ed. 4585301e7c6SReid Spencer if (Dest->isDeclaration()) { 459d61d39ecSAnton Korobeynikov LinkFromSrc = true; 460d61d39ecSAnton Korobeynikov LT = Src->getLinkage(); 461d61d39ecSAnton Korobeynikov } 462e06036d2SAndrew Lenharth } else if (Dest->hasExternalWeakLinkage()) { 463e06036d2SAndrew Lenharth //If the Dest is weak, use the source linkage 464e06036d2SAndrew Lenharth LinkFromSrc = true; 465e06036d2SAndrew Lenharth LT = Src->getLinkage(); 466d61d39ecSAnton Korobeynikov } else { 467fc61de39SChris Lattner LinkFromSrc = false; 468fc61de39SChris Lattner LT = Dest->getLinkage(); 469d61d39ecSAnton Korobeynikov } 4705301e7c6SReid Spencer } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) { 471fc61de39SChris Lattner // If Dest is external but Src is not: 472fc61de39SChris Lattner LinkFromSrc = true; 473fc61de39SChris Lattner LT = Src->getLinkage(); 474fc61de39SChris Lattner } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) { 475fc61de39SChris Lattner if (Src->getLinkage() != Dest->getLinkage()) 476fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 477fc61de39SChris Lattner "': can only link appending global with another appending global!"); 478fc61de39SChris Lattner LinkFromSrc = true; // Special cased. 479fc61de39SChris Lattner LT = Src->getLinkage(); 48008d91178SDuncan Sands } else if (Src->mayBeOverridden()) { 481ce4396bcSDale Johannesen // At this point we know that Dest has LinkOnce, External*, Weak, Common, 482ce4396bcSDale Johannesen // or DLL* linkage. 483ce4396bcSDale Johannesen if ((Dest->hasLinkOnceLinkage() && 484ce4396bcSDale Johannesen (Src->hasWeakLinkage() || Src->hasCommonLinkage())) || 48512c94949SAnton Korobeynikov Dest->hasExternalWeakLinkage()) { 486fc61de39SChris Lattner LinkFromSrc = true; 487fc61de39SChris Lattner LT = Src->getLinkage(); 488fc61de39SChris Lattner } else { 489fc61de39SChris Lattner LinkFromSrc = false; 490fc61de39SChris Lattner LT = Dest->getLinkage(); 491fc61de39SChris Lattner } 49208d91178SDuncan Sands } else if (Dest->mayBeOverridden()) { 49312c94949SAnton Korobeynikov // At this point we know that Src has External* or DLL* linkage. 49412c94949SAnton Korobeynikov if (Src->hasExternalWeakLinkage()) { 49512c94949SAnton Korobeynikov LinkFromSrc = false; 49612c94949SAnton Korobeynikov LT = Dest->getLinkage(); 49712c94949SAnton Korobeynikov } else { 498fc61de39SChris Lattner LinkFromSrc = true; 499fc61de39SChris Lattner LT = GlobalValue::ExternalLinkage; 50012c94949SAnton Korobeynikov } 501fc61de39SChris Lattner } else { 502d61d39ecSAnton Korobeynikov assert((Dest->hasExternalLinkage() || 503d61d39ecSAnton Korobeynikov Dest->hasDLLImportLinkage() || 50412c94949SAnton Korobeynikov Dest->hasDLLExportLinkage() || 50512c94949SAnton Korobeynikov Dest->hasExternalWeakLinkage()) && 506d61d39ecSAnton Korobeynikov (Src->hasExternalLinkage() || 507d61d39ecSAnton Korobeynikov Src->hasDLLImportLinkage() || 50812c94949SAnton Korobeynikov Src->hasDLLExportLinkage() || 50912c94949SAnton Korobeynikov Src->hasExternalWeakLinkage()) && 510fc61de39SChris Lattner "Unexpected linkage type!"); 511fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 512fc61de39SChris Lattner "': symbol multiply defined!"); 513fc61de39SChris Lattner } 51431fc4f95SAnton Korobeynikov 51531fc4f95SAnton Korobeynikov // Check visibility 51631fc4f95SAnton Korobeynikov if (Dest && Src->getVisibility() != Dest->getVisibility()) 5171cc79985SChris Lattner if (!Src->isDeclaration() && !Dest->isDeclaration()) 51831fc4f95SAnton Korobeynikov return Error(Err, "Linking globals named '" + Src->getName() + 51931fc4f95SAnton Korobeynikov "': symbols have different visibilities!"); 520fc61de39SChris Lattner return false; 521fc61de39SChris Lattner } 522361e513dSReid Spencer 523361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge 524361e513dSReid Spencer // them into the dest module. 525f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src, 526361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 527361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 528361e513dSReid Spencer std::string *Err) { 52934fc5a0eSChris Lattner ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable(); 53034fc5a0eSChris Lattner 531361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 532177a3008SChris Lattner for (Module::const_global_iterator I = Src->global_begin(), 533177a3008SChris Lattner E = Src->global_end(); I != E; ++I) { 534f6439246SAnton Korobeynikov const GlobalVariable *SGV = I; 535e79f4c77SAnton Korobeynikov GlobalValue *DGV = 0; 536e79f4c77SAnton Korobeynikov 53734fc5a0eSChris Lattner // Check to see if may have to link the global with the global, alias or 53834fc5a0eSChris Lattner // function. 539*6de96a1bSRafael Espindola if (SGV->hasName() && !SGV->hasLocalLinkage()) 54034fc5a0eSChris Lattner DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(), 54134fc5a0eSChris Lattner SGV->getNameEnd())); 542361e513dSReid Spencer 543c08e7a00SChris Lattner // If we found a global with the same name in the dest module, but it has 544c08e7a00SChris Lattner // internal linkage, we are really not doing any linkage here. 545*6de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 546c08e7a00SChris Lattner DGV = 0; 547c08e7a00SChris Lattner 548e79f4c77SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 54934fc5a0eSChris Lattner if (DGV && DGV->getType() != SGV->getType()) 5508aa89e41SChris Lattner RecursiveResolveTypes(SGV->getType(), DGV->getType()); 551e79f4c77SAnton Korobeynikov 5525e79a610SDan Gohman assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() || 5535e79a610SDan Gohman SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) && 554361e513dSReid Spencer "Global must either be external or have an initializer!"); 555361e513dSReid Spencer 5561b9633d7SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 5571b9633d7SChris Lattner bool LinkFromSrc = false; 558fc61de39SChris Lattner if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err)) 559fc61de39SChris Lattner return true; 560361e513dSReid Spencer 5610ead7a50SChris Lattner if (DGV == 0) { 562361e513dSReid Spencer // No linking to be performed, simply create an identical version of the 563361e513dSReid Spencer // symbol over in the dest module... the initializer will be filled in 56434fc5a0eSChris Lattner // later by LinkGlobalInits. 565361e513dSReid Spencer GlobalVariable *NewDGV = 566361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 567361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 568b32a9ef0SChris Lattner SGV->getName(), Dest, false, 569b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 5702dc36535SReid Spencer // Propagate alignment, visibility and section info. 5713aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 572dd924e4eSAndrew Lenharth 573361e513dSReid Spencer // If the LLVM runtime renamed the global, but it is an externally visible 574361e513dSReid Spencer // symbol, DGV must be an existing global with internal linkage. Rename 575361e513dSReid Spencer // it. 576*6de96a1bSRafael Espindola if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName()) 577361e513dSReid Spencer ForceRenaming(NewDGV, SGV->getName()); 578361e513dSReid Spencer 5790ead7a50SChris Lattner // Make sure to remember this mapping. 58066a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 58166a6271cSAnton Korobeynikov 58234fc5a0eSChris Lattner // Keep track that this is an appending variable. 583361e513dSReid Spencer if (SGV->hasAppendingLinkage()) 584361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 5850ead7a50SChris Lattner continue; 5860ead7a50SChris Lattner } 5870ead7a50SChris Lattner 5880ead7a50SChris Lattner // If the visibilities of the symbols disagree and the destination is a 5890ead7a50SChris Lattner // prototype, take the visibility of its input. 5900ead7a50SChris Lattner if (DGV->isDeclaration()) 5910ead7a50SChris Lattner DGV->setVisibility(SGV->getVisibility()); 5920ead7a50SChris Lattner 5930ead7a50SChris Lattner if (DGV->hasAppendingLinkage()) { 594361e513dSReid Spencer // No linking is performed yet. Just insert a new copy of the global, and 595361e513dSReid Spencer // keep track of the fact that it is an appending variable in the 596361e513dSReid Spencer // AppendingVars map. The name is cleared out so that no linkage is 597361e513dSReid Spencer // performed. 598361e513dSReid Spencer GlobalVariable *NewDGV = 599361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 600361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 601b32a9ef0SChris Lattner "", Dest, false, 602b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 603361e513dSReid Spencer 604e8a3e74bSAnton Korobeynikov // Set alignment allowing CopyGVAttributes merge it with alignment of SGV. 6053aaaa0b2SReid Spencer NewDGV->setAlignment(DGV->getAlignment()); 606e8a3e74bSAnton Korobeynikov // Propagate alignment, section and visibility info. 6073aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 608dd924e4eSAndrew Lenharth 609361e513dSReid Spencer // Make sure to remember this mapping... 61066a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 611361e513dSReid Spencer 612361e513dSReid Spencer // Keep track that this is an appending variable... 613361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 6140ead7a50SChris Lattner continue; 6150ead7a50SChris Lattner } 6160ead7a50SChris Lattner 6170ead7a50SChris Lattner if (LinkFromSrc) { 6180ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) 619eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGV->getName() + 620eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 621dd924e4eSAndrew Lenharth 6220074ea3aSAnton Korobeynikov // If the types don't match, and if we are to link from the source, nuke 62334fc5a0eSChris Lattner // DGV and create a new one of the appropriate type. Note that the thing 62434fc5a0eSChris Lattner // we are replacing may be a function (if a prototype, weak, etc) or a 62534fc5a0eSChris Lattner // global variable. 626fc61de39SChris Lattner GlobalVariable *NewDGV = 6270ead7a50SChris Lattner new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(), 6280ead7a50SChris Lattner NewLinkage, /*init*/0, DGV->getName(), Dest, false, 629b32a9ef0SChris Lattner SGV->getType()->getAddressSpace()); 63034fc5a0eSChris Lattner 63134fc5a0eSChris Lattner // Propagate alignment, section, and visibility info. 63234fc5a0eSChris Lattner CopyGVAttributes(NewDGV, SGV); 63334fc5a0eSChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType())); 63434fc5a0eSChris Lattner 63534fc5a0eSChris Lattner // DGV will conflict with NewDGV because they both had the same 636f6439246SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 637f6439246SAnton Korobeynikov // because DGV might not have internal linkage. 63834fc5a0eSChris Lattner if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV)) 63934fc5a0eSChris Lattner Var->eraseFromParent(); 64034fc5a0eSChris Lattner else 64134fc5a0eSChris Lattner cast<Function>(DGV)->eraseFromParent(); 64234fc5a0eSChris Lattner DGV = NewDGV; 643f6439246SAnton Korobeynikov 64434fc5a0eSChris Lattner // If the symbol table renamed the global, but it is an externally visible 64534fc5a0eSChris Lattner // symbol, DGV must be an existing global with internal linkage. Rename. 646*6de96a1bSRafael Espindola if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage()) 647f6439246SAnton Korobeynikov ForceRenaming(NewDGV, SGV->getName()); 648f6439246SAnton Korobeynikov 6490ead7a50SChris Lattner // Inherit const as appropriate. 65034fc5a0eSChris Lattner NewDGV->setConstant(SGV->isConstant()); 651fc61de39SChris Lattner 6520ead7a50SChris Lattner // Make sure to remember this mapping. 6530ead7a50SChris Lattner ValueMap[SGV] = NewDGV; 6540ead7a50SChris Lattner continue; 6550ead7a50SChris Lattner } 656f6439246SAnton Korobeynikov 65734fc5a0eSChris Lattner // Not "link from source", keep the one in the DestModule and remap the 65834fc5a0eSChris Lattner // input onto it. 65934fc5a0eSChris Lattner 66034fc5a0eSChris Lattner // Special case for const propagation. 66134fc5a0eSChris Lattner if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) 66234fc5a0eSChris Lattner if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant()) 66334fc5a0eSChris Lattner DGVar->setConstant(true); 66434fc5a0eSChris Lattner 665006659f0SAnton Korobeynikov // SGV is global, but DGV is alias. 666006659f0SAnton Korobeynikov if (isa<GlobalAlias>(DGV)) { 667006659f0SAnton Korobeynikov // The only valid mappings are: 668006659f0SAnton Korobeynikov // - SGV is external declaration, which is effectively a no-op. 669006659f0SAnton Korobeynikov // - SGV is weak, when we just need to throw SGV out. 670006659f0SAnton Korobeynikov if (!SGV->isDeclaration() && !SGV->mayBeOverridden()) 6710ead7a50SChris Lattner return Error(Err, "Global-Alias Collision on '" + SGV->getName() + 6720ead7a50SChris Lattner "': symbol multiple defined"); 673006659f0SAnton Korobeynikov } 6740ead7a50SChris Lattner 67534fc5a0eSChris Lattner // Set calculated linkage 67634fc5a0eSChris Lattner DGV->setLinkage(NewLinkage); 67734fc5a0eSChris Lattner 67834fc5a0eSChris Lattner // Make sure to remember this mapping... 67934fc5a0eSChris Lattner ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType()); 680361e513dSReid Spencer } 681361e513dSReid Spencer return false; 682361e513dSReid Spencer } 683361e513dSReid Spencer 684dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes 685dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) { 686dac5fa94SAnton Korobeynikov if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage()) 687dac5fa94SAnton Korobeynikov return GlobalValue::ExternalLinkage; 688dac5fa94SAnton Korobeynikov else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage()) 689dac5fa94SAnton Korobeynikov return GlobalValue::WeakLinkage; 690*6de96a1bSRafael Espindola else if (SGV->hasInternalLinkage() && DGV->hasInternalLinkage()) 691dac5fa94SAnton Korobeynikov return GlobalValue::InternalLinkage; 692*6de96a1bSRafael Espindola else { 693*6de96a1bSRafael Espindola assert (SGV->hasPrivateLinkage() && DGV->hasPrivateLinkage() && 694*6de96a1bSRafael Espindola "Unexpected linkage type"); 695*6de96a1bSRafael Espindola return GlobalValue::PrivateLinkage; 696dac5fa94SAnton Korobeynikov } 697dac5fa94SAnton Korobeynikov } 698dac5fa94SAnton Korobeynikov 699b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the 700dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already 701dac5fa94SAnton Korobeynikov // linked in. 7022e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src, 7032e13597fSAnton Korobeynikov std::map<const Value*, Value*> &ValueMap, 7042e13597fSAnton Korobeynikov std::string *Err) { 705b00c9c0dSLauro Ramos Venancio // Loop over all alias in the src module 706b00c9c0dSLauro Ramos Venancio for (Module::const_alias_iterator I = Src->alias_begin(), 707b00c9c0dSLauro Ramos Venancio E = Src->alias_end(); I != E; ++I) { 708dac5fa94SAnton Korobeynikov const GlobalAlias *SGA = I; 709dac5fa94SAnton Korobeynikov const GlobalValue *SAliasee = SGA->getAliasedGlobal(); 710dac5fa94SAnton Korobeynikov GlobalAlias *NewGA = NULL; 711b00c9c0dSLauro Ramos Venancio 712dac5fa94SAnton Korobeynikov // Globals were already linked, thus we can just query ValueMap for variant 713acbdaa24SAnton Korobeynikov // of SAliasee in Dest. 714d48ed17dSTed Kremenek std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee); 715d48ed17dSTed Kremenek assert(VMI != ValueMap.end() && "Aliasee not linked"); 716d48ed17dSTed Kremenek GlobalValue* DAliasee = cast<GlobalValue>(VMI->second); 717acbdaa24SAnton Korobeynikov GlobalValue* DGV = NULL; 718b00c9c0dSLauro Ramos Venancio 719dac5fa94SAnton Korobeynikov // Try to find something 'similar' to SGA in destination module. 720*6de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 721acbdaa24SAnton Korobeynikov DGV = Dest->getNamedAlias(SGA->getName()); 722acbdaa24SAnton Korobeynikov 723dac5fa94SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 724acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 725683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 726acbdaa24SAnton Korobeynikov } 7272e13597fSAnton Korobeynikov 728*6de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 729acbdaa24SAnton Korobeynikov DGV = Dest->getGlobalVariable(SGA->getName()); 730acbdaa24SAnton Korobeynikov 731acbdaa24SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 732acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 733683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 734acbdaa24SAnton Korobeynikov } 735acbdaa24SAnton Korobeynikov 736*6de96a1bSRafael Espindola if (!DGV && !SGA->hasLocalLinkage()) { 737acbdaa24SAnton Korobeynikov DGV = Dest->getFunction(SGA->getName()); 738acbdaa24SAnton Korobeynikov 739acbdaa24SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 740acbdaa24SAnton Korobeynikov if (DGV && DGV->getType() != SGA->getType()) 741683ed3d9SChris Lattner RecursiveResolveTypes(SGA->getType(), DGV->getType()); 742acbdaa24SAnton Korobeynikov } 743acbdaa24SAnton Korobeynikov 744acbdaa24SAnton Korobeynikov // No linking to be performed on internal stuff. 745*6de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 746acbdaa24SAnton Korobeynikov DGV = NULL; 747acbdaa24SAnton Korobeynikov 748acbdaa24SAnton Korobeynikov if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) { 749acbdaa24SAnton Korobeynikov // Types are known to be the same, check whether aliasees equal. As 750dac5fa94SAnton Korobeynikov // globals are already linked we just need query ValueMap to find the 751dac5fa94SAnton Korobeynikov // mapping. 752dac5fa94SAnton Korobeynikov if (DAliasee == DGA->getAliasedGlobal()) { 753dac5fa94SAnton Korobeynikov // This is just two copies of the same alias. Propagate linkage, if 754dac5fa94SAnton Korobeynikov // necessary. 755dac5fa94SAnton Korobeynikov DGA->setLinkage(CalculateAliasLinkage(SGA, DGA)); 756dac5fa94SAnton Korobeynikov 757dac5fa94SAnton Korobeynikov NewGA = DGA; 758dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 759dac5fa94SAnton Korobeynikov } else 760eeb5ca6fSAnton Korobeynikov return Error(Err, "Alias Collision on '" + SGA->getName()+ 761eeb5ca6fSAnton Korobeynikov "': aliases have different aliasees"); 762acbdaa24SAnton Korobeynikov } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) { 7639cd0b50fSAnton Korobeynikov // The only allowed way is to link alias with external declaration or weak 7649cd0b50fSAnton Korobeynikov // symbol.. 76508d91178SDuncan Sands if (DGVar->isDeclaration() || DGVar->mayBeOverridden()) { 766510fc32dSAnton Korobeynikov // But only if aliasee is global too... 767510fc32dSAnton Korobeynikov if (!isa<GlobalVariable>(DAliasee)) 768510fc32dSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 769510fc32dSAnton Korobeynikov "': aliasee is not global variable"); 770510fc32dSAnton Korobeynikov 771dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 772dac5fa94SAnton Korobeynikov SGA->getName(), DAliasee, Dest); 773dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 774dac5fa94SAnton Korobeynikov 775dac5fa94SAnton Korobeynikov // Any uses of DGV need to change to NewGA, with cast, if needed. 776acbdaa24SAnton Korobeynikov if (SGA->getType() != DGVar->getType()) 777acbdaa24SAnton Korobeynikov DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 778acbdaa24SAnton Korobeynikov DGVar->getType())); 779dac5fa94SAnton Korobeynikov else 780acbdaa24SAnton Korobeynikov DGVar->replaceAllUsesWith(NewGA); 781dac5fa94SAnton Korobeynikov 782acbdaa24SAnton Korobeynikov // DGVar will conflict with NewGA because they both had the same 783dac5fa94SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 784dac5fa94SAnton Korobeynikov // because DGV might not have internal linkage. 785acbdaa24SAnton Korobeynikov DGVar->eraseFromParent(); 786dac5fa94SAnton Korobeynikov 787dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 788dac5fa94SAnton Korobeynikov } else 789eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 790eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 791acbdaa24SAnton Korobeynikov } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) { 7929cd0b50fSAnton Korobeynikov // The only allowed way is to link alias with external declaration or weak 7939cd0b50fSAnton Korobeynikov // symbol... 79408d91178SDuncan Sands if (DF->isDeclaration() || DF->mayBeOverridden()) { 795510fc32dSAnton Korobeynikov // But only if aliasee is function too... 796510fc32dSAnton Korobeynikov if (!isa<Function>(DAliasee)) 797510fc32dSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 798510fc32dSAnton Korobeynikov "': aliasee is not function"); 799510fc32dSAnton Korobeynikov 80024f65c3aSAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 80124f65c3aSAnton Korobeynikov SGA->getName(), DAliasee, Dest); 80224f65c3aSAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 80324f65c3aSAnton Korobeynikov 80424f65c3aSAnton Korobeynikov // Any uses of DF need to change to NewGA, with cast, if needed. 80524f65c3aSAnton Korobeynikov if (SGA->getType() != DF->getType()) 80624f65c3aSAnton Korobeynikov DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 80724f65c3aSAnton Korobeynikov DF->getType())); 80824f65c3aSAnton Korobeynikov else 80924f65c3aSAnton Korobeynikov DF->replaceAllUsesWith(NewGA); 81024f65c3aSAnton Korobeynikov 81124f65c3aSAnton Korobeynikov // DF will conflict with NewGA because they both had the same 81224f65c3aSAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 81324f65c3aSAnton Korobeynikov // because DF might not have internal linkage. 81424f65c3aSAnton Korobeynikov DF->eraseFromParent(); 81524f65c3aSAnton Korobeynikov 81624f65c3aSAnton Korobeynikov // Proceed to 'common' steps 81724f65c3aSAnton Korobeynikov } else 818eeb5ca6fSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 819eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 820dac5fa94SAnton Korobeynikov } else { 821acbdaa24SAnton Korobeynikov // No linking to be performed, simply create an identical version of the 822acbdaa24SAnton Korobeynikov // alias over in the dest module... 823dac5fa94SAnton Korobeynikov 824dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 825dac5fa94SAnton Korobeynikov SGA->getName(), DAliasee, Dest); 826dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 827dac5fa94SAnton Korobeynikov 828dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 829b00c9c0dSLauro Ramos Venancio } 830dac5fa94SAnton Korobeynikov 831dac5fa94SAnton Korobeynikov assert(NewGA && "No alias was created in destination module!"); 832dac5fa94SAnton Korobeynikov 833d5160da5SAnton Korobeynikov // If the symbol table renamed the alias, but it is an externally visible 834acbdaa24SAnton Korobeynikov // symbol, DGA must be an global value with internal linkage. Rename it. 835dac5fa94SAnton Korobeynikov if (NewGA->getName() != SGA->getName() && 836*6de96a1bSRafael Espindola !NewGA->hasLocalLinkage()) 837dac5fa94SAnton Korobeynikov ForceRenaming(NewGA, SGA->getName()); 838dac5fa94SAnton Korobeynikov 839dac5fa94SAnton Korobeynikov // Remember this mapping so uses in the source module get remapped 840dac5fa94SAnton Korobeynikov // later by RemapOperand. 84166a6271cSAnton Korobeynikov ValueMap[SGA] = NewGA; 842dac5fa94SAnton Korobeynikov } 843dac5fa94SAnton Korobeynikov 844b00c9c0dSLauro Ramos Venancio return false; 845b00c9c0dSLauro Ramos Venancio } 846b00c9c0dSLauro Ramos Venancio 847361e513dSReid Spencer 848361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all 849361e513dSReid Spencer // globals that may be referenced are in Dest. 850361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src, 851361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 852361e513dSReid Spencer std::string *Err) { 853361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 85444ab8aefSChris Lattner for (Module::const_global_iterator I = Src->global_begin(), 85544ab8aefSChris Lattner E = Src->global_end(); I != E; ++I) { 856361e513dSReid Spencer const GlobalVariable *SGV = I; 857361e513dSReid Spencer 858361e513dSReid Spencer if (SGV->hasInitializer()) { // Only process initialized GV's 859361e513dSReid Spencer // Figure out what the initializer looks like in the dest module... 860361e513dSReid Spencer Constant *SInit = 8617391dde1SChris Lattner cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap)); 862006659f0SAnton Korobeynikov // Grab destination global variable or alias. 863006659f0SAnton Korobeynikov GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts()); 864361e513dSReid Spencer 865006659f0SAnton Korobeynikov // If dest if global variable, check that initializers match. 866006659f0SAnton Korobeynikov if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) { 867006659f0SAnton Korobeynikov if (DGVar->hasInitializer()) { 868361e513dSReid Spencer if (SGV->hasExternalLinkage()) { 869006659f0SAnton Korobeynikov if (DGVar->getInitializer() != SInit) 870006659f0SAnton Korobeynikov return Error(Err, "Global Variable Collision on '" + 871006659f0SAnton Korobeynikov SGV->getName() + 872eeb5ca6fSAnton Korobeynikov "': global variables have different initializers"); 873006659f0SAnton Korobeynikov } else if (DGVar->mayBeOverridden()) { 874361e513dSReid Spencer // Nothing is required, mapped values will take the new global 875361e513dSReid Spencer // automatically. 87608d91178SDuncan Sands } else if (SGV->mayBeOverridden()) { 877361e513dSReid Spencer // Nothing is required, mapped values will take the new global 878361e513dSReid Spencer // automatically. 879006659f0SAnton Korobeynikov } else if (DGVar->hasAppendingLinkage()) { 880361e513dSReid Spencer assert(0 && "Appending linkage unimplemented!"); 881361e513dSReid Spencer } else { 882361e513dSReid Spencer assert(0 && "Unknown linkage!"); 883361e513dSReid Spencer } 884361e513dSReid Spencer } else { 885361e513dSReid Spencer // Copy the initializer over now... 886006659f0SAnton Korobeynikov DGVar->setInitializer(SInit); 887006659f0SAnton Korobeynikov } 888006659f0SAnton Korobeynikov } else { 889006659f0SAnton Korobeynikov // Destination is alias, the only valid situation is when source is 890006659f0SAnton Korobeynikov // weak. Also, note, that we already checked linkage in LinkGlobals(), 891006659f0SAnton Korobeynikov // thus we assert here. 892006659f0SAnton Korobeynikov // FIXME: Should we weaken this assumption, 'dereference' alias and 893006659f0SAnton Korobeynikov // check for initializer of aliasee? 894006659f0SAnton Korobeynikov assert(SGV->mayBeOverridden()); 895361e513dSReid Spencer } 896361e513dSReid Spencer } 897361e513dSReid Spencer } 898361e513dSReid Spencer return false; 899361e513dSReid Spencer } 900361e513dSReid Spencer 901361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules, 902361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes 903361e513dSReid Spencer // to the Dest function... 904361e513dSReid Spencer // 905361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src, 906361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 907361e513dSReid Spencer std::string *Err) { 90834fc5a0eSChris Lattner ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable(); 90934fc5a0eSChris Lattner 910d3ba7d9bSReid Spencer // Loop over all of the functions in the src module, mapping them over 911361e513dSReid Spencer for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) { 912361e513dSReid Spencer const Function *SF = I; // SrcFunction 9131bb56dedSAnton Korobeynikov GlobalValue *DGV = 0; 914228a5f18SChris Lattner 91534fc5a0eSChris Lattner // Check to see if may have to link the function with the global, alias or 91634fc5a0eSChris Lattner // function. 917*6de96a1bSRafael Espindola if (SF->hasName() && !SF->hasLocalLinkage()) 91834fc5a0eSChris Lattner DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(), 91934fc5a0eSChris Lattner SF->getNameEnd())); 920361e513dSReid Spencer 921c08e7a00SChris Lattner // If we found a global with the same name in the dest module, but it has 922c08e7a00SChris Lattner // internal linkage, we are really not doing any linkage here. 923*6de96a1bSRafael Espindola if (DGV && DGV->hasLocalLinkage()) 924c08e7a00SChris Lattner DGV = 0; 925c08e7a00SChris Lattner 9261bb56dedSAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 92734fc5a0eSChris Lattner if (DGV && DGV->getType() != SF->getType()) 9281bb56dedSAnton Korobeynikov RecursiveResolveTypes(SF->getType(), DGV->getType()); 9291bb56dedSAnton Korobeynikov 9300ead7a50SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 9310ead7a50SChris Lattner bool LinkFromSrc = false; 9320ead7a50SChris Lattner if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err)) 9330ead7a50SChris Lattner return true; 9340ead7a50SChris Lattner 935228a5f18SChris Lattner // If there is no linkage to be performed, just bring over SF without 936228a5f18SChris Lattner // modifying it. 9371bb56dedSAnton Korobeynikov if (DGV == 0) { 938228a5f18SChris Lattner // Function does not already exist, simply insert an function signature 939228a5f18SChris Lattner // identical to SF into the dest module. 940228a5f18SChris Lattner Function *NewDF = Function::Create(SF->getFunctionType(), 941228a5f18SChris Lattner SF->getLinkage(), 942228a5f18SChris Lattner SF->getName(), Dest); 943228a5f18SChris Lattner CopyGVAttributes(NewDF, SF); 944ec7441b3SChris Lattner 945228a5f18SChris Lattner // If the LLVM runtime renamed the function, but it is an externally 946228a5f18SChris Lattner // visible symbol, DF must be an existing function with internal linkage. 947228a5f18SChris Lattner // Rename it. 948*6de96a1bSRafael Espindola if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName()) 949228a5f18SChris Lattner ForceRenaming(NewDF, SF->getName()); 950228a5f18SChris Lattner 951228a5f18SChris Lattner // ... and remember this mapping... 952228a5f18SChris Lattner ValueMap[SF] = NewDF; 953228a5f18SChris Lattner continue; 9540ead7a50SChris Lattner } 9550ead7a50SChris Lattner 9560ead7a50SChris Lattner // If the visibilities of the symbols disagree and the destination is a 9570ead7a50SChris Lattner // prototype, take the visibility of its input. 9580ead7a50SChris Lattner if (DGV->isDeclaration()) 9590ead7a50SChris Lattner DGV->setVisibility(SF->getVisibility()); 9600ead7a50SChris Lattner 9610ead7a50SChris Lattner if (LinkFromSrc) { 9620ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) 9631bb56dedSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SF->getName() + 9641bb56dedSAnton Korobeynikov "': symbol multiple defined"); 9651bb56dedSAnton Korobeynikov 9663aaaa0b2SReid Spencer // We have a definition of the same name but different type in the 9673aaaa0b2SReid Spencer // source module. Copy the prototype to the destination and replace 9683aaaa0b2SReid Spencer // uses of the destination's prototype with the new prototype. 9690ead7a50SChris Lattner Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage, 9703aaaa0b2SReid Spencer SF->getName(), Dest); 9713aaaa0b2SReid Spencer CopyGVAttributes(NewDF, SF); 9723aaaa0b2SReid Spencer 9733aaaa0b2SReid Spencer // Any uses of DF need to change to NewDF, with cast 9740ead7a50SChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType())); 9753aaaa0b2SReid Spencer 9763aaaa0b2SReid Spencer // DF will conflict with NewDF because they both had the same. We must 9773aaaa0b2SReid Spencer // erase this now so ForceRenaming doesn't assert because DF might 9783aaaa0b2SReid Spencer // not have internal linkage. 9790ead7a50SChris Lattner if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV)) 9800ead7a50SChris Lattner Var->eraseFromParent(); 9810ead7a50SChris Lattner else 9820ead7a50SChris Lattner cast<Function>(DGV)->eraseFromParent(); 9833aaaa0b2SReid Spencer 9843aaaa0b2SReid Spencer // If the symbol table renamed the function, but it is an externally 9853aaaa0b2SReid Spencer // visible symbol, DF must be an existing function with internal 9863aaaa0b2SReid Spencer // linkage. Rename it. 987*6de96a1bSRafael Espindola if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage()) 9883aaaa0b2SReid Spencer ForceRenaming(NewDF, SF->getName()); 9893aaaa0b2SReid Spencer 9903aaaa0b2SReid Spencer // Remember this mapping so uses in the source module get remapped 9913aaaa0b2SReid Spencer // later by RemapOperand. 9923aaaa0b2SReid Spencer ValueMap[SF] = NewDF; 993228a5f18SChris Lattner continue; 994228a5f18SChris Lattner } 995361e513dSReid Spencer 9960ead7a50SChris Lattner // Not "link from source", keep the one in the DestModule and remap the 9970ead7a50SChris Lattner // input onto it. 9980ead7a50SChris Lattner 9990ead7a50SChris Lattner if (isa<GlobalAlias>(DGV)) { 10000ead7a50SChris Lattner // The only valid mappings are: 10010ead7a50SChris Lattner // - SF is external declaration, which is effectively a no-op. 10020ead7a50SChris Lattner // - SF is weak, when we just need to throw SF out. 100382dd6111SAnton Korobeynikov if (!SF->isDeclaration() && !SF->mayBeOverridden()) 10040ead7a50SChris Lattner return Error(Err, "Function-Alias Collision on '" + SF->getName() + 10050ead7a50SChris Lattner "': symbol multiple defined"); 100677e8ac4dSChris Lattner } 100777e8ac4dSChris Lattner 10080ead7a50SChris Lattner // Set calculated linkage 10090ead7a50SChris Lattner DGV->setLinkage(NewLinkage); 101077e8ac4dSChris Lattner 10110ead7a50SChris Lattner // Make sure to remember this mapping. 10120ead7a50SChris Lattner ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType()); 1013361e513dSReid Spencer } 1014361e513dSReid Spencer return false; 1015361e513dSReid Spencer } 1016361e513dSReid Spencer 1017361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and 1018361e513dSReid Spencer // fix up references to values. At this point we know that Dest is an external 1019361e513dSReid Spencer // function, and that Src is not. 10202f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src, 10213aaaa0b2SReid Spencer std::map<const Value*, Value*> &ValueMap, 1022361e513dSReid Spencer std::string *Err) { 10235301e7c6SReid Spencer assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration()); 1024361e513dSReid Spencer 10257391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1026531f9e92SChris Lattner Function::arg_iterator DI = Dest->arg_begin(); 1027531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1028361e513dSReid Spencer I != E; ++I, ++DI) { 10297629b71dSOwen Anderson DI->setName(I->getName()); // Copy the name information over... 1030361e513dSReid Spencer 1031361e513dSReid Spencer // Add a mapping to our local map 103266a6271cSAnton Korobeynikov ValueMap[I] = DI; 1033361e513dSReid Spencer } 1034361e513dSReid Spencer 10352f0557d0SChris Lattner // Splice the body of the source function into the dest function. 10362f0557d0SChris Lattner Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList()); 1037361e513dSReid Spencer 1038361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1039361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1040361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 1041361e513dSReid Spencer // functions and patch them up to point to the local versions... 1042361e513dSReid Spencer // 1043361e513dSReid Spencer for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB) 1044361e513dSReid Spencer for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1045361e513dSReid Spencer for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 1046361e513dSReid Spencer OI != OE; ++OI) 10472f0557d0SChris Lattner if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI)) 10483aaaa0b2SReid Spencer *OI = RemapOperand(*OI, ValueMap); 10497391dde1SChris Lattner 10507391dde1SChris Lattner // There is no need to map the arguments anymore. 105144ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 105244ab8aefSChris Lattner I != E; ++I) 10533aaaa0b2SReid Spencer ValueMap.erase(I); 1054361e513dSReid Spencer 1055361e513dSReid Spencer return false; 1056361e513dSReid Spencer } 1057361e513dSReid Spencer 1058361e513dSReid Spencer 1059361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the 1060361e513dSReid Spencer // source module into the DestModule. This consists basically of copying the 1061361e513dSReid Spencer // function over and fixing up references to values. 10622f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src, 1063361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 1064361e513dSReid Spencer std::string *Err) { 1065361e513dSReid Spencer 106690246aa7SReid Spencer // Loop over all of the functions in the src module, mapping them over as we 106790246aa7SReid Spencer // go 10682f0557d0SChris Lattner for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) { 10695301e7c6SReid Spencer if (!SF->isDeclaration()) { // No body if function is external 1070d53bd2daSChris Lattner Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function 1071361e513dSReid Spencer 1072361e513dSReid Spencer // DF not external SF external? 1073d53bd2daSChris Lattner if (DF && DF->isDeclaration()) 1074361e513dSReid Spencer // Only provide the function body if there isn't one already. 1075361e513dSReid Spencer if (LinkFunctionBody(DF, SF, ValueMap, Err)) 1076361e513dSReid Spencer return true; 107790246aa7SReid Spencer } 1078361e513dSReid Spencer } 1079361e513dSReid Spencer return false; 1080361e513dSReid Spencer } 1081361e513dSReid Spencer 1082361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them 1083361e513dSReid Spencer // together now. Return true on error. 1084361e513dSReid Spencer static bool LinkAppendingVars(Module *M, 1085361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 1086361e513dSReid Spencer std::string *ErrorMsg) { 1087361e513dSReid Spencer if (AppendingVars.empty()) return false; // Nothing to do. 1088361e513dSReid Spencer 1089361e513dSReid Spencer // Loop over the multimap of appending vars, processing any variables with the 1090361e513dSReid Spencer // same name, forming a new appending global variable with both of the 1091361e513dSReid Spencer // initializers merged together, then rewrite references to the old variables 1092361e513dSReid Spencer // and delete them. 1093361e513dSReid Spencer std::vector<Constant*> Inits; 1094361e513dSReid Spencer while (AppendingVars.size() > 1) { 1095361e513dSReid Spencer // Get the first two elements in the map... 1096361e513dSReid Spencer std::multimap<std::string, 1097361e513dSReid Spencer GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++; 1098361e513dSReid Spencer 1099361e513dSReid Spencer // If the first two elements are for different names, there is no pair... 1100361e513dSReid Spencer // Otherwise there is a pair, so link them together... 1101361e513dSReid Spencer if (First->first == Second->first) { 1102361e513dSReid Spencer GlobalVariable *G1 = First->second, *G2 = Second->second; 1103361e513dSReid Spencer const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType()); 1104361e513dSReid Spencer const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType()); 1105361e513dSReid Spencer 1106361e513dSReid Spencer // Check to see that they two arrays agree on type... 1107361e513dSReid Spencer if (T1->getElementType() != T2->getElementType()) 1108361e513dSReid Spencer return Error(ErrorMsg, 1109361e513dSReid Spencer "Appending variables with different element types need to be linked!"); 1110361e513dSReid Spencer if (G1->isConstant() != G2->isConstant()) 1111361e513dSReid Spencer return Error(ErrorMsg, 1112361e513dSReid Spencer "Appending variables linked with different const'ness!"); 1113361e513dSReid Spencer 111485703e37SLauro Ramos Venancio if (G1->getAlignment() != G2->getAlignment()) 111585703e37SLauro Ramos Venancio return Error(ErrorMsg, 111685703e37SLauro Ramos Venancio "Appending variables with different alignment need to be linked!"); 111785703e37SLauro Ramos Venancio 111885703e37SLauro Ramos Venancio if (G1->getVisibility() != G2->getVisibility()) 111985703e37SLauro Ramos Venancio return Error(ErrorMsg, 112085703e37SLauro Ramos Venancio "Appending variables with different visibility need to be linked!"); 112185703e37SLauro Ramos Venancio 112285703e37SLauro Ramos Venancio if (G1->getSection() != G2->getSection()) 112385703e37SLauro Ramos Venancio return Error(ErrorMsg, 112485703e37SLauro Ramos Venancio "Appending variables with different section name need to be linked!"); 112585703e37SLauro Ramos Venancio 1126361e513dSReid Spencer unsigned NewSize = T1->getNumElements() + T2->getNumElements(); 1127361e513dSReid Spencer ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize); 1128361e513dSReid Spencer 1129d490d4f0SChris Lattner G1->setName(""); // Clear G1's name in case of a conflict! 1130d490d4f0SChris Lattner 1131361e513dSReid Spencer // Create the new global variable... 1132361e513dSReid Spencer GlobalVariable *NG = 1133361e513dSReid Spencer new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(), 1134b32a9ef0SChris Lattner /*init*/0, First->first, M, G1->isThreadLocal(), 1135b32a9ef0SChris Lattner G1->getType()->getAddressSpace()); 1136361e513dSReid Spencer 113785703e37SLauro Ramos Venancio // Propagate alignment, visibility and section info. 113885703e37SLauro Ramos Venancio CopyGVAttributes(NG, G1); 113985703e37SLauro Ramos Venancio 1140361e513dSReid Spencer // Merge the initializer... 1141361e513dSReid Spencer Inits.reserve(NewSize); 1142361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) { 1143361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1144361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1145361e513dSReid Spencer } else { 1146361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G1->getInitializer())); 1147361e513dSReid Spencer Constant *CV = Constant::getNullValue(T1->getElementType()); 1148361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1149361e513dSReid Spencer Inits.push_back(CV); 1150361e513dSReid Spencer } 1151361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) { 1152361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1153361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1154361e513dSReid Spencer } else { 1155361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G2->getInitializer())); 1156361e513dSReid Spencer Constant *CV = Constant::getNullValue(T2->getElementType()); 1157361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1158361e513dSReid Spencer Inits.push_back(CV); 1159361e513dSReid Spencer } 1160361e513dSReid Spencer NG->setInitializer(ConstantArray::get(NewType, Inits)); 1161361e513dSReid Spencer Inits.clear(); 1162361e513dSReid Spencer 1163361e513dSReid Spencer // Replace any uses of the two global variables with uses of the new 1164361e513dSReid Spencer // global... 1165361e513dSReid Spencer 1166361e513dSReid Spencer // FIXME: This should rewrite simple/straight-forward uses such as 1167361e513dSReid Spencer // getelementptr instructions to not use the Cast! 1168b341b086SReid Spencer G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType())); 1169b341b086SReid Spencer G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType())); 1170361e513dSReid Spencer 1171361e513dSReid Spencer // Remove the two globals from the module now... 1172361e513dSReid Spencer M->getGlobalList().erase(G1); 1173361e513dSReid Spencer M->getGlobalList().erase(G2); 1174361e513dSReid Spencer 1175361e513dSReid Spencer // Put the new global into the AppendingVars map so that we can handle 1176361e513dSReid Spencer // linking of more than two vars... 1177361e513dSReid Spencer Second->second = NG; 1178361e513dSReid Spencer } 1179361e513dSReid Spencer AppendingVars.erase(First); 1180361e513dSReid Spencer } 1181361e513dSReid Spencer 1182361e513dSReid Spencer return false; 1183361e513dSReid Spencer } 1184361e513dSReid Spencer 11852609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) { 11862609888fSAnton Korobeynikov for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end(); 1187e6d90f5aSAnton Korobeynikov I != E; ++I) 11881a114042SAnton Korobeynikov if (const GlobalValue *GV = I->resolveAliasedGlobal()) 1189ac2c6558SAnton Korobeynikov if (GV != I && !GV->isDeclaration()) 1190e6d90f5aSAnton Korobeynikov I->replaceAllUsesWith(const_cast<GlobalValue*>(GV)); 11912609888fSAnton Korobeynikov 11922609888fSAnton Korobeynikov return false; 11932609888fSAnton Korobeynikov } 1194361e513dSReid Spencer 1195361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting 1196361e513dSReid Spencer // left module modified to be the composite of the two input modules. If an 1197361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate 1198361e513dSReid Spencer // the problem. Upon failure, the Dest module could be in a modified state, and 1199361e513dSReid Spencer // shouldn't be relied on to be consistent. 1200c4e31534SReid Spencer bool 1201c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) { 1202361e513dSReid Spencer assert(Dest != 0 && "Invalid Destination module"); 1203361e513dSReid Spencer assert(Src != 0 && "Invalid Source Module"); 1204361e513dSReid Spencer 12057f3bd82aSChris Lattner if (Dest->getDataLayout().empty()) { 12067f3bd82aSChris Lattner if (!Src->getDataLayout().empty()) { 120778bddc38SChris Lattner Dest->setDataLayout(Src->getDataLayout()); 12087f3bd82aSChris Lattner } else { 12093ac38e99SReid Spencer std::string DataLayout; 12103ac38e99SReid Spencer 1211bddf51bcSAnton Korobeynikov if (Dest->getEndianness() == Module::AnyEndianness) { 12123ac38e99SReid Spencer if (Src->getEndianness() == Module::BigEndian) 12133ac38e99SReid Spencer DataLayout.append("E"); 12143ac38e99SReid Spencer else if (Src->getEndianness() == Module::LittleEndian) 12153ac38e99SReid Spencer DataLayout.append("e"); 1216bddf51bcSAnton Korobeynikov } 1217bddf51bcSAnton Korobeynikov 1218bddf51bcSAnton Korobeynikov if (Dest->getPointerSize() == Module::AnyPointerSize) { 12193ac38e99SReid Spencer if (Src->getPointerSize() == Module::Pointer64) 12203ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64"); 12213ac38e99SReid Spencer else if (Src->getPointerSize() == Module::Pointer32) 12223ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32"); 1223bddf51bcSAnton Korobeynikov } 12243ac38e99SReid Spencer Dest->setDataLayout(DataLayout); 12257f3bd82aSChris Lattner } 12267f3bd82aSChris Lattner } 1227361e513dSReid Spencer 122890c2df5bSChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 12297f3bd82aSChris Lattner if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty()) 12307f3bd82aSChris Lattner Dest->setTargetTriple(Src->getTargetTriple()); 12317f3bd82aSChris Lattner 12327f3bd82aSChris Lattner if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() && 12337f3bd82aSChris Lattner Src->getDataLayout() != Dest->getDataLayout()) 12343ac38e99SReid Spencer cerr << "WARNING: Linking two modules of different data layouts!\n"; 1235b7f5916eSChris Lattner if (!Src->getTargetTriple().empty() && 1236b7f5916eSChris Lattner Dest->getTargetTriple() != Src->getTargetTriple()) 1237f3baad3eSBill Wendling cerr << "WARNING: Linking two modules of different target triples!\n"; 1238361e513dSReid Spencer 123990c2df5bSChris Lattner // Append the module inline asm string. 12408ebd2164SChris Lattner if (!Src->getModuleInlineAsm().empty()) { 12418ebd2164SChris Lattner if (Dest->getModuleInlineAsm().empty()) 12428ebd2164SChris Lattner Dest->setModuleInlineAsm(Src->getModuleInlineAsm()); 1243dd2d3fafSChris Lattner else 12448ebd2164SChris Lattner Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+ 12458ebd2164SChris Lattner Src->getModuleInlineAsm()); 1246dd2d3fafSChris Lattner } 1247dd2d3fafSChris Lattner 1248361e513dSReid Spencer // Update the destination module's dependent libraries list with the libraries 1249361e513dSReid Spencer // from the source module. There's no opportunity for duplicates here as the 1250361e513dSReid Spencer // Module ensures that duplicate insertions are discarded. 125190c2df5bSChris Lattner for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end(); 125290c2df5bSChris Lattner SI != SE; ++SI) 1253361e513dSReid Spencer Dest->addLibrary(*SI); 1254361e513dSReid Spencer 1255361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 1256361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 1257361e513dSReid Spencer // Make sure there are no type name conflicts. 1258d3ba7d9bSReid Spencer if (LinkTypes(Dest, Src, ErrorMsg)) 1259d3ba7d9bSReid Spencer return true; 1260361e513dSReid Spencer 1261361e513dSReid Spencer // ValueMap - Mapping of values from what they used to be in Src, to what they 1262361e513dSReid Spencer // are now in Dest. 1263361e513dSReid Spencer std::map<const Value*, Value*> ValueMap; 1264361e513dSReid Spencer 1265361e513dSReid Spencer // AppendingVars - Keep track of global variables in the destination module 1266361e513dSReid Spencer // with appending linkage. After the module is linked together, they are 1267361e513dSReid Spencer // appended and the module is rewritten. 1268361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> AppendingVars; 126944ab8aefSChris Lattner for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end(); 127044ab8aefSChris Lattner I != E; ++I) { 1271361e513dSReid Spencer // Add all of the appending globals already in the Dest module to 1272361e513dSReid Spencer // AppendingVars. 1273361e513dSReid Spencer if (I->hasAppendingLinkage()) 1274361e513dSReid Spencer AppendingVars.insert(std::make_pair(I->getName(), I)); 1275361e513dSReid Spencer } 1276361e513dSReid Spencer 1277361e513dSReid Spencer // Insert all of the globals in src into the Dest module... without linking 1278361e513dSReid Spencer // initializers (which could refer to functions not yet mapped over). 12793aaaa0b2SReid Spencer if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) 1280361e513dSReid Spencer return true; 1281361e513dSReid Spencer 1282361e513dSReid Spencer // Link the functions together between the two modules, without doing function 1283361e513dSReid Spencer // bodies... this just adds external function prototypes to the Dest 1284361e513dSReid Spencer // function... We do this so that when we begin processing function bodies, 1285361e513dSReid Spencer // all of the global values that may be referenced are available in our 1286361e513dSReid Spencer // ValueMap. 12873aaaa0b2SReid Spencer if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) 1288361e513dSReid Spencer return true; 1289361e513dSReid Spencer 12902e13597fSAnton Korobeynikov // If there were any alias, link them now. We really need to do this now, 12912e13597fSAnton Korobeynikov // because all of the aliases that may be referenced need to be available in 12922e13597fSAnton Korobeynikov // ValueMap 12932e13597fSAnton Korobeynikov if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true; 12942e13597fSAnton Korobeynikov 1295361e513dSReid Spencer // Update the initializers in the Dest module now that all globals that may 1296361e513dSReid Spencer // be referenced are in Dest. 1297361e513dSReid Spencer if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true; 1298361e513dSReid Spencer 1299361e513dSReid Spencer // Link in the function bodies that are defined in the source module into the 1300361e513dSReid Spencer // DestModule. This consists basically of copying the function over and 1301361e513dSReid Spencer // fixing up references to values. 1302361e513dSReid Spencer if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true; 1303361e513dSReid Spencer 1304361e513dSReid Spencer // If there were any appending global variables, link them together now. 1305361e513dSReid Spencer if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true; 1306361e513dSReid Spencer 1307e43711d3SAnton Korobeynikov // Resolve all uses of aliases with aliasees 1308e43711d3SAnton Korobeynikov if (ResolveAliases(Dest)) return true; 1309e43711d3SAnton Korobeynikov 1310361e513dSReid Spencer // If the source library's module id is in the dependent library list of the 1311361e513dSReid Spencer // destination library, remove it since that module is now linked in. 1312361e513dSReid Spencer sys::Path modId; 1313c9c0473fSReid Spencer modId.set(Src->getModuleIdentifier()); 1314361e513dSReid Spencer if (!modId.isEmpty()) 1315361e513dSReid Spencer Dest->removeLibrary(modId.getBasename()); 1316361e513dSReid Spencer 1317361e513dSReid Spencer return false; 1318361e513dSReid Spencer } 1319361e513dSReid Spencer 1320361e513dSReid Spencer // vim: sw=2 1321