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" 2930c0f336SBill Wendling #include <sstream> 30361e513dSReid Spencer using namespace llvm; 31361e513dSReid Spencer 32361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true. 33361e513dSReid Spencer // This just makes error return conditions a little bit simpler... 34361e513dSReid Spencer static inline bool Error(std::string *E, const std::string &Message) { 35361e513dSReid Spencer if (E) *E = Message; 36361e513dSReid Spencer return true; 37361e513dSReid Spencer } 38361e513dSReid Spencer 392c4f9a48SReid Spencer // ToStr - Simple wrapper function to convert a type to a string. 40361e513dSReid Spencer static std::string ToStr(const Type *Ty, const Module *M) { 41361e513dSReid Spencer std::ostringstream OS; 42361e513dSReid Spencer WriteTypeSymbolic(OS, Ty, M); 43361e513dSReid Spencer return OS.str(); 44361e513dSReid Spencer } 45361e513dSReid Spencer 46361e513dSReid Spencer // 47361e513dSReid Spencer // Function: ResolveTypes() 48361e513dSReid Spencer // 49361e513dSReid Spencer // Description: 50361e513dSReid Spencer // Attempt to link the two specified types together. 51361e513dSReid Spencer // 52361e513dSReid Spencer // Inputs: 53361e513dSReid Spencer // DestTy - The type to which we wish to resolve. 54361e513dSReid Spencer // SrcTy - The original type which we want to resolve. 55361e513dSReid Spencer // Name - The name of the type. 56361e513dSReid Spencer // 57361e513dSReid Spencer // Outputs: 58361e513dSReid Spencer // DestST - The symbol table in which the new type should be placed. 59361e513dSReid Spencer // 60361e513dSReid Spencer // Return value: 61361e513dSReid Spencer // true - There is an error and the types cannot yet be linked. 62361e513dSReid Spencer // false - No errors. 63361e513dSReid Spencer // 64361e513dSReid Spencer static bool ResolveTypes(const Type *DestTy, const Type *SrcTy, 6532af9e8cSReid Spencer TypeSymbolTable *DestST, const std::string &Name) { 66361e513dSReid Spencer if (DestTy == SrcTy) return false; // If already equal, noop 67361e513dSReid Spencer 68361e513dSReid Spencer // Does the type already exist in the module? 69361e513dSReid Spencer if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists... 70361e513dSReid Spencer if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) { 71361e513dSReid Spencer const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy); 72361e513dSReid Spencer } else { 73361e513dSReid Spencer return true; // Cannot link types... neither is opaque and not-equal 74361e513dSReid Spencer } 75361e513dSReid Spencer } else { // Type not in dest module. Add it now. 76361e513dSReid Spencer if (DestTy) // Type _is_ in module, just opaque... 77361e513dSReid Spencer const_cast<OpaqueType*>(cast<OpaqueType>(DestTy)) 78361e513dSReid Spencer ->refineAbstractTypeTo(SrcTy); 79361e513dSReid Spencer else if (!Name.empty()) 80361e513dSReid Spencer DestST->insert(Name, const_cast<Type*>(SrcTy)); 81361e513dSReid Spencer } 82361e513dSReid Spencer return false; 83361e513dSReid Spencer } 84361e513dSReid Spencer 85361e513dSReid Spencer static const FunctionType *getFT(const PATypeHolder &TH) { 86361e513dSReid Spencer return cast<FunctionType>(TH.get()); 87361e513dSReid Spencer } 88361e513dSReid Spencer static const StructType *getST(const PATypeHolder &TH) { 89361e513dSReid Spencer return cast<StructType>(TH.get()); 90361e513dSReid Spencer } 91361e513dSReid Spencer 92361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it 93361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types 94361e513dSReid Spencer // are compatible. 95361e513dSReid Spencer static bool RecursiveResolveTypesI(const PATypeHolder &DestTy, 96361e513dSReid Spencer const PATypeHolder &SrcTy, 9732af9e8cSReid Spencer TypeSymbolTable *DestST, 9832af9e8cSReid Spencer const std::string &Name, 99361e513dSReid Spencer std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) { 100361e513dSReid Spencer const Type *SrcTyT = SrcTy.get(); 101361e513dSReid Spencer const Type *DestTyT = DestTy.get(); 102361e513dSReid Spencer if (DestTyT == SrcTyT) return false; // If already equal, noop 103361e513dSReid Spencer 104361e513dSReid Spencer // If we found our opaque type, resolve it now! 105361e513dSReid Spencer if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT)) 106361e513dSReid Spencer return ResolveTypes(DestTyT, SrcTyT, DestST, Name); 107361e513dSReid Spencer 108361e513dSReid Spencer // Two types cannot be resolved together if they are of different primitive 109361e513dSReid Spencer // type. For example, we cannot resolve an int to a float. 110361e513dSReid Spencer if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true; 111361e513dSReid Spencer 112361e513dSReid Spencer // Otherwise, resolve the used type used by this derived type... 113361e513dSReid Spencer switch (DestTyT->getTypeID()) { 1147a9c62baSReid Spencer case Type::IntegerTyID: { 1157a9c62baSReid Spencer if (cast<IntegerType>(DestTyT)->getBitWidth() != 1167a9c62baSReid Spencer cast<IntegerType>(SrcTyT)->getBitWidth()) 1177a9c62baSReid Spencer return true; 1187a9c62baSReid Spencer return false; 1197a9c62baSReid Spencer } 120361e513dSReid Spencer case Type::FunctionTyID: { 121361e513dSReid Spencer if (cast<FunctionType>(DestTyT)->isVarArg() != 122361e513dSReid Spencer cast<FunctionType>(SrcTyT)->isVarArg() || 123361e513dSReid Spencer cast<FunctionType>(DestTyT)->getNumContainedTypes() != 124361e513dSReid Spencer cast<FunctionType>(SrcTyT)->getNumContainedTypes()) 125361e513dSReid Spencer return true; 126361e513dSReid Spencer for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i) 127361e513dSReid Spencer if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i), 128361e513dSReid Spencer getFT(SrcTy)->getContainedType(i), DestST, "", 129361e513dSReid Spencer Pointers)) 130361e513dSReid Spencer return true; 131361e513dSReid Spencer return false; 132361e513dSReid Spencer } 133361e513dSReid Spencer case Type::StructTyID: { 134361e513dSReid Spencer if (getST(DestTy)->getNumContainedTypes() != 135361e513dSReid Spencer getST(SrcTy)->getNumContainedTypes()) return 1; 136361e513dSReid Spencer for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i) 137361e513dSReid Spencer if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i), 138361e513dSReid Spencer getST(SrcTy)->getContainedType(i), DestST, "", 139361e513dSReid Spencer Pointers)) 140361e513dSReid Spencer return true; 141361e513dSReid Spencer return false; 142361e513dSReid Spencer } 143361e513dSReid Spencer case Type::ArrayTyID: { 144361e513dSReid Spencer const ArrayType *DAT = cast<ArrayType>(DestTy.get()); 145361e513dSReid Spencer const ArrayType *SAT = cast<ArrayType>(SrcTy.get()); 146361e513dSReid Spencer if (DAT->getNumElements() != SAT->getNumElements()) return true; 147361e513dSReid Spencer return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(), 148361e513dSReid Spencer DestST, "", Pointers); 149361e513dSReid Spencer } 150361e513dSReid Spencer case Type::PointerTyID: { 151361e513dSReid Spencer // If this is a pointer type, check to see if we have already seen it. If 152361e513dSReid Spencer // so, we are in a recursive branch. Cut off the search now. We cannot use 153361e513dSReid Spencer // an associative container for this search, because the type pointers (keys 154361e513dSReid Spencer // in the container) change whenever types get resolved... 155361e513dSReid Spencer for (unsigned i = 0, e = Pointers.size(); i != e; ++i) 156361e513dSReid Spencer if (Pointers[i].first == DestTy) 157361e513dSReid Spencer return Pointers[i].second != SrcTy; 158361e513dSReid Spencer 159361e513dSReid Spencer // Otherwise, add the current pointers to the vector to stop recursion on 160361e513dSReid Spencer // this pair. 161361e513dSReid Spencer Pointers.push_back(std::make_pair(DestTyT, SrcTyT)); 162361e513dSReid Spencer bool Result = 163361e513dSReid Spencer RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(), 164361e513dSReid Spencer cast<PointerType>(SrcTy.get())->getElementType(), 165361e513dSReid Spencer DestST, "", Pointers); 166361e513dSReid Spencer Pointers.pop_back(); 167361e513dSReid Spencer return Result; 168361e513dSReid Spencer } 169361e513dSReid Spencer default: assert(0 && "Unexpected type!"); return true; 170361e513dSReid Spencer } 171361e513dSReid Spencer } 172361e513dSReid Spencer 173361e513dSReid Spencer static bool RecursiveResolveTypes(const PATypeHolder &DestTy, 174361e513dSReid Spencer const PATypeHolder &SrcTy, 17532af9e8cSReid Spencer TypeSymbolTable *DestST, 17632af9e8cSReid Spencer const std::string &Name){ 177361e513dSReid Spencer std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes; 178361e513dSReid Spencer return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes); 179361e513dSReid Spencer } 180361e513dSReid Spencer 181361e513dSReid Spencer 182361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 183361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 184361e513dSReid Spencer // Make sure there are no type name conflicts. 185361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) { 18632af9e8cSReid Spencer TypeSymbolTable *DestST = &Dest->getTypeSymbolTable(); 18732af9e8cSReid Spencer const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable(); 188361e513dSReid Spencer 189361e513dSReid Spencer // Look for a type plane for Type's... 19032af9e8cSReid Spencer TypeSymbolTable::const_iterator TI = SrcST->begin(); 19132af9e8cSReid Spencer TypeSymbolTable::const_iterator TE = SrcST->end(); 192361e513dSReid Spencer if (TI == TE) return false; // No named types, do nothing. 193361e513dSReid Spencer 194361e513dSReid Spencer // Some types cannot be resolved immediately because they depend on other 195361e513dSReid Spencer // types being resolved to each other first. This contains a list of types we 196361e513dSReid Spencer // are waiting to recheck. 197361e513dSReid Spencer std::vector<std::string> DelayedTypesToResolve; 198361e513dSReid Spencer 199361e513dSReid Spencer for ( ; TI != TE; ++TI ) { 200361e513dSReid Spencer const std::string &Name = TI->first; 201361e513dSReid Spencer const Type *RHS = TI->second; 202361e513dSReid Spencer 203361e513dSReid Spencer // Check to see if this type name is already in the dest module... 20432af9e8cSReid Spencer Type *Entry = DestST->lookup(Name); 205361e513dSReid Spencer 206361e513dSReid Spencer if (ResolveTypes(Entry, RHS, DestST, Name)) { 207361e513dSReid Spencer // They look different, save the types 'till later to resolve. 208361e513dSReid Spencer DelayedTypesToResolve.push_back(Name); 209361e513dSReid Spencer } 210361e513dSReid Spencer } 211361e513dSReid Spencer 212361e513dSReid Spencer // Iteratively resolve types while we can... 213361e513dSReid Spencer while (!DelayedTypesToResolve.empty()) { 214361e513dSReid Spencer // Loop over all of the types, attempting to resolve them if possible... 215361e513dSReid Spencer unsigned OldSize = DelayedTypesToResolve.size(); 216361e513dSReid Spencer 217361e513dSReid Spencer // Try direct resolution by name... 218361e513dSReid Spencer for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) { 219361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 22032af9e8cSReid Spencer Type *T1 = SrcST->lookup(Name); 22132af9e8cSReid Spencer Type *T2 = DestST->lookup(Name); 222361e513dSReid Spencer if (!ResolveTypes(T2, T1, DestST, Name)) { 223361e513dSReid Spencer // We are making progress! 224361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 225361e513dSReid Spencer --i; 226361e513dSReid Spencer } 227361e513dSReid Spencer } 228361e513dSReid Spencer 229361e513dSReid Spencer // Did we not eliminate any types? 230361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 231361e513dSReid Spencer // Attempt to resolve subelements of types. This allows us to merge these 232361e513dSReid Spencer // two types: { int* } and { opaque* } 233361e513dSReid Spencer for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) { 234361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 23532af9e8cSReid Spencer PATypeHolder T1(SrcST->lookup(Name)); 23632af9e8cSReid Spencer PATypeHolder T2(DestST->lookup(Name)); 237361e513dSReid Spencer 238361e513dSReid Spencer if (!RecursiveResolveTypes(T2, T1, DestST, Name)) { 239361e513dSReid Spencer // We are making progress! 240361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 241361e513dSReid Spencer 242361e513dSReid Spencer // Go back to the main loop, perhaps we can resolve directly by name 243361e513dSReid Spencer // now... 244361e513dSReid Spencer break; 245361e513dSReid Spencer } 246361e513dSReid Spencer } 247361e513dSReid Spencer 248361e513dSReid Spencer // If we STILL cannot resolve the types, then there is something wrong. 249361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 250361e513dSReid Spencer // Remove the symbol name from the destination. 251361e513dSReid Spencer DelayedTypesToResolve.pop_back(); 252361e513dSReid Spencer } 253361e513dSReid Spencer } 254361e513dSReid Spencer } 255361e513dSReid Spencer 256361e513dSReid Spencer 257361e513dSReid Spencer return false; 258361e513dSReid Spencer } 259361e513dSReid Spencer 260361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) { 261361e513dSReid Spencer for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end(); 262361e513dSReid Spencer I != E; ++I) { 263f3baad3eSBill Wendling cerr << " Fr: " << (void*)I->first << " "; 264361e513dSReid Spencer I->first->dump(); 265f3baad3eSBill Wendling cerr << " To: " << (void*)I->second << " "; 266361e513dSReid Spencer I->second->dump(); 267f3baad3eSBill Wendling cerr << "\n"; 268361e513dSReid Spencer } 269361e513dSReid Spencer } 270361e513dSReid Spencer 271361e513dSReid Spencer 272d3ba7d9bSReid Spencer // RemapOperand - Use ValueMap to convert constants from one module to another. 273361e513dSReid Spencer static Value *RemapOperand(const Value *In, 2747391dde1SChris Lattner std::map<const Value*, Value*> &ValueMap) { 2757391dde1SChris Lattner std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In); 2763aaaa0b2SReid Spencer if (I != ValueMap.end()) 2773aaaa0b2SReid Spencer return I->second; 278361e513dSReid Spencer 279d3ba7d9bSReid Spencer // Check to see if it's a constant that we are interested in transforming. 280c7745926SChris Lattner Value *Result = 0; 281361e513dSReid Spencer if (const Constant *CPV = dyn_cast<Constant>(In)) { 282361e513dSReid Spencer if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) || 2837a9c62baSReid Spencer isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV)) 2847391dde1SChris Lattner return const_cast<Constant*>(CPV); // Simple constants stay identical. 285361e513dSReid Spencer 286361e513dSReid Spencer if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) { 287361e513dSReid Spencer std::vector<Constant*> Operands(CPA->getNumOperands()); 288361e513dSReid Spencer for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 2897391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap)); 290361e513dSReid Spencer Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands); 291361e513dSReid Spencer } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) { 292361e513dSReid Spencer std::vector<Constant*> Operands(CPS->getNumOperands()); 293361e513dSReid Spencer for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 2947391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap)); 295361e513dSReid Spencer Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands); 296361e513dSReid Spencer } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) { 297361e513dSReid Spencer Result = const_cast<Constant*>(CPV); 298d84d35baSReid Spencer } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) { 29993bde9cbSChris Lattner std::vector<Constant*> Operands(CP->getNumOperands()); 30093bde9cbSChris Lattner for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 30193bde9cbSChris Lattner Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap)); 302d84d35baSReid Spencer Result = ConstantVector::get(Operands); 303361e513dSReid Spencer } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) { 30419247f36SChris Lattner std::vector<Constant*> Ops; 30519247f36SChris Lattner for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) 30619247f36SChris Lattner Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap))); 30719247f36SChris Lattner Result = CE->getWithOperands(Ops); 308d3ba7d9bSReid Spencer } else if (isa<GlobalValue>(CPV)) { 309d3ba7d9bSReid Spencer assert(0 && "Unmapped global?"); 310361e513dSReid Spencer } else { 311361e513dSReid Spencer assert(0 && "Unknown type of derived type constant value!"); 312361e513dSReid Spencer } 313c7745926SChris Lattner } else if (isa<InlineAsm>(In)) { 314c7745926SChris Lattner Result = const_cast<Value*>(In); 315c7745926SChris Lattner } 316361e513dSReid Spencer 317d3ba7d9bSReid Spencer // Cache the mapping in our local map structure 318c7745926SChris Lattner if (Result) { 31966a6271cSAnton Korobeynikov ValueMap[In] = Result; 320361e513dSReid Spencer return Result; 321361e513dSReid Spencer } 322361e513dSReid Spencer 32390246aa7SReid Spencer 324f3baad3eSBill Wendling cerr << "LinkModules ValueMap: \n"; 3257391dde1SChris Lattner PrintMap(ValueMap); 326361e513dSReid Spencer 327f3baad3eSBill Wendling cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n"; 328361e513dSReid Spencer assert(0 && "Couldn't remap value!"); 329361e513dSReid Spencer return 0; 330361e513dSReid Spencer } 331361e513dSReid Spencer 33290246aa7SReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict 33390246aa7SReid Spencer /// in the symbol table. This is good for all clients except for us. Go 33490246aa7SReid Spencer /// through the trouble to force this back. 335361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) { 336361e513dSReid Spencer assert(GV->getName() != Name && "Can't force rename to self"); 3373aaaa0b2SReid Spencer ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable(); 338361e513dSReid Spencer 339361e513dSReid Spencer // If there is a conflict, rename the conflict. 3402a8d2e0eSChris Lattner if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) { 34190246aa7SReid Spencer assert(ConflictGV->hasInternalLinkage() && 34290246aa7SReid Spencer "Not conflicting with a static global, should link instead!"); 3432a8d2e0eSChris Lattner GV->takeName(ConflictGV); 344361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 3453aaaa0b2SReid Spencer assert(ConflictGV->getName() != Name && "ForceRenaming didn't work"); 3462a8d2e0eSChris Lattner } else { 3472a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 3483aaaa0b2SReid Spencer } 3493aaaa0b2SReid Spencer } 3503aaaa0b2SReid Spencer 3513aaaa0b2SReid Spencer /// CopyGVAttributes - copy additional attributes (those not needed to construct 3523aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV. 3533aaaa0b2SReid Spencer static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 3543aaaa0b2SReid Spencer // Propagate alignment, visibility and section info. 3553aaaa0b2SReid Spencer DestGV->setAlignment(std::max(DestGV->getAlignment(), SrcGV->getAlignment())); 3563aaaa0b2SReid Spencer DestGV->setSection(SrcGV->getSection()); 3573aaaa0b2SReid Spencer DestGV->setVisibility(SrcGV->getVisibility()); 3583aaaa0b2SReid Spencer if (const Function *SrcF = dyn_cast<Function>(SrcGV)) { 3593aaaa0b2SReid Spencer Function *DestF = cast<Function>(DestGV); 3603aaaa0b2SReid Spencer DestF->setCallingConv(SrcF->getCallingConv()); 361ad0ea2d4SDuncan Sands DestF->setParamAttrs(SrcF->getParamAttrs()); 362520e64c0SGordon Henriksen if (SrcF->hasCollector()) 363520e64c0SGordon Henriksen DestF->setCollector(SrcF->getCollector()); 3640074ea3aSAnton Korobeynikov } else if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(SrcGV)) { 3650074ea3aSAnton Korobeynikov GlobalVariable *DestVar = cast<GlobalVariable>(DestGV); 3660074ea3aSAnton Korobeynikov DestVar->setThreadLocal(SrcVar->isThreadLocal()); 3673aaaa0b2SReid Spencer } 368361e513dSReid Spencer } 369361e513dSReid Spencer 370fc61de39SChris Lattner /// GetLinkageResult - This analyzes the two global values and determines what 371fc61de39SChris Lattner /// the result will look like in the destination module. In particular, it 372fc61de39SChris Lattner /// computes the resultant linkage type, computes whether the global in the 373fc61de39SChris Lattner /// source should be copied over to the destination (replacing the existing 37431fc4f95SAnton Korobeynikov /// one), and computes whether this linkage is an error or not. It also performs 37531fc4f95SAnton Korobeynikov /// visibility checks: we cannot link together two symbols with different 37631fc4f95SAnton Korobeynikov /// visibilities. 377f6439246SAnton Korobeynikov static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 378fc61de39SChris Lattner GlobalValue::LinkageTypes <, bool &LinkFromSrc, 379fc61de39SChris Lattner std::string *Err) { 380fc61de39SChris Lattner assert((!Dest || !Src->hasInternalLinkage()) && 381fc61de39SChris Lattner "If Src has internal linkage, Dest shouldn't be set!"); 382fc61de39SChris Lattner if (!Dest) { 383fc61de39SChris Lattner // Linking something to nothing. 384fc61de39SChris Lattner LinkFromSrc = true; 385fc61de39SChris Lattner LT = Src->getLinkage(); 3865301e7c6SReid Spencer } else if (Src->isDeclaration()) { 3871f93c50aSAnton Korobeynikov // If Src is external or if both Src & Dest are external.. Just link the 388fc61de39SChris Lattner // external globals, we aren't adding anything. 389d61d39ecSAnton Korobeynikov if (Src->hasDLLImportLinkage()) { 39012c94949SAnton Korobeynikov // If one of GVs has DLLImport linkage, result should be dllimport'ed. 3915301e7c6SReid Spencer if (Dest->isDeclaration()) { 392d61d39ecSAnton Korobeynikov LinkFromSrc = true; 393d61d39ecSAnton Korobeynikov LT = Src->getLinkage(); 394d61d39ecSAnton Korobeynikov } 395e06036d2SAndrew Lenharth } else if (Dest->hasExternalWeakLinkage()) { 396e06036d2SAndrew Lenharth //If the Dest is weak, use the source linkage 397e06036d2SAndrew Lenharth LinkFromSrc = true; 398e06036d2SAndrew Lenharth LT = Src->getLinkage(); 399d61d39ecSAnton Korobeynikov } else { 400fc61de39SChris Lattner LinkFromSrc = false; 401fc61de39SChris Lattner LT = Dest->getLinkage(); 402d61d39ecSAnton Korobeynikov } 4035301e7c6SReid Spencer } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) { 404fc61de39SChris Lattner // If Dest is external but Src is not: 405fc61de39SChris Lattner LinkFromSrc = true; 406fc61de39SChris Lattner LT = Src->getLinkage(); 407fc61de39SChris Lattner } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) { 408fc61de39SChris Lattner if (Src->getLinkage() != Dest->getLinkage()) 409fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 410fc61de39SChris Lattner "': can only link appending global with another appending global!"); 411fc61de39SChris Lattner LinkFromSrc = true; // Special cased. 412fc61de39SChris Lattner LT = Src->getLinkage(); 413fc61de39SChris Lattner } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) { 414d3ba7d9bSReid Spencer // At this point we know that Dest has LinkOnce, External*, Weak, or 415d3ba7d9bSReid Spencer // DLL* linkage. 41612c94949SAnton Korobeynikov if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) || 41712c94949SAnton Korobeynikov Dest->hasExternalWeakLinkage()) { 418fc61de39SChris Lattner LinkFromSrc = true; 419fc61de39SChris Lattner LT = Src->getLinkage(); 420fc61de39SChris Lattner } else { 421fc61de39SChris Lattner LinkFromSrc = false; 422fc61de39SChris Lattner LT = Dest->getLinkage(); 423fc61de39SChris Lattner } 424fc61de39SChris Lattner } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) { 42512c94949SAnton Korobeynikov // At this point we know that Src has External* or DLL* linkage. 42612c94949SAnton Korobeynikov if (Src->hasExternalWeakLinkage()) { 42712c94949SAnton Korobeynikov LinkFromSrc = false; 42812c94949SAnton Korobeynikov LT = Dest->getLinkage(); 42912c94949SAnton Korobeynikov } else { 430fc61de39SChris Lattner LinkFromSrc = true; 431fc61de39SChris Lattner LT = GlobalValue::ExternalLinkage; 43212c94949SAnton Korobeynikov } 433fc61de39SChris Lattner } else { 434d61d39ecSAnton Korobeynikov assert((Dest->hasExternalLinkage() || 435d61d39ecSAnton Korobeynikov Dest->hasDLLImportLinkage() || 43612c94949SAnton Korobeynikov Dest->hasDLLExportLinkage() || 43712c94949SAnton Korobeynikov Dest->hasExternalWeakLinkage()) && 438d61d39ecSAnton Korobeynikov (Src->hasExternalLinkage() || 439d61d39ecSAnton Korobeynikov Src->hasDLLImportLinkage() || 44012c94949SAnton Korobeynikov Src->hasDLLExportLinkage() || 44112c94949SAnton Korobeynikov Src->hasExternalWeakLinkage()) && 442fc61de39SChris Lattner "Unexpected linkage type!"); 443fc61de39SChris Lattner return Error(Err, "Linking globals named '" + Src->getName() + 444fc61de39SChris Lattner "': symbol multiply defined!"); 445fc61de39SChris Lattner } 44631fc4f95SAnton Korobeynikov 44731fc4f95SAnton Korobeynikov // Check visibility 44831fc4f95SAnton Korobeynikov if (Dest && Src->getVisibility() != Dest->getVisibility()) 4491cc79985SChris Lattner if (!Src->isDeclaration() && !Dest->isDeclaration()) 45031fc4f95SAnton Korobeynikov return Error(Err, "Linking globals named '" + Src->getName() + 45131fc4f95SAnton Korobeynikov "': symbols have different visibilities!"); 452fc61de39SChris Lattner return false; 453fc61de39SChris Lattner } 454361e513dSReid Spencer 455361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge 456361e513dSReid Spencer // them into the dest module. 457f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src, 458361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 459361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 460361e513dSReid Spencer std::string *Err) { 461361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 462f6439246SAnton Korobeynikov for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end(); 46344ab8aefSChris Lattner I != E; ++I) { 464f6439246SAnton Korobeynikov const GlobalVariable *SGV = I; 465e79f4c77SAnton Korobeynikov GlobalValue *DGV = 0; 466e79f4c77SAnton Korobeynikov 467e79f4c77SAnton Korobeynikov // Check to see if may have to link the global with the global 4683aaaa0b2SReid Spencer if (SGV->hasName() && !SGV->hasInternalLinkage()) { 4693aaaa0b2SReid Spencer DGV = Dest->getGlobalVariable(SGV->getName()); 4703aaaa0b2SReid Spencer if (DGV && DGV->getType() != SGV->getType()) 471fc61de39SChris Lattner // If types don't agree due to opaque types, try to resolve them. 4723aaaa0b2SReid Spencer RecursiveResolveTypes(SGV->getType(), DGV->getType(), 4733aaaa0b2SReid Spencer &Dest->getTypeSymbolTable(), ""); 474361e513dSReid Spencer } 475361e513dSReid Spencer 476e79f4c77SAnton Korobeynikov // Check to see if may have to link the global with the alias 477715ef43cSAnton Korobeynikov if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) { 478e79f4c77SAnton Korobeynikov DGV = Dest->getNamedAlias(SGV->getName()); 479e79f4c77SAnton Korobeynikov if (DGV && DGV->getType() != SGV->getType()) 480e79f4c77SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 481e79f4c77SAnton Korobeynikov RecursiveResolveTypes(SGV->getType(), DGV->getType(), 482e79f4c77SAnton Korobeynikov &Dest->getTypeSymbolTable(), ""); 483e79f4c77SAnton Korobeynikov } 484e79f4c77SAnton Korobeynikov 485fc61de39SChris Lattner if (DGV && DGV->hasInternalLinkage()) 486fc61de39SChris Lattner DGV = 0; 487fc61de39SChris Lattner 4885e79a610SDan Gohman assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() || 4895e79a610SDan Gohman SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) && 490361e513dSReid Spencer "Global must either be external or have an initializer!"); 491361e513dSReid Spencer 4921b9633d7SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 4931b9633d7SChris Lattner bool LinkFromSrc = false; 494fc61de39SChris Lattner if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err)) 495fc61de39SChris Lattner return true; 496361e513dSReid Spencer 497fc61de39SChris Lattner if (!DGV) { 498361e513dSReid Spencer // No linking to be performed, simply create an identical version of the 499361e513dSReid Spencer // symbol over in the dest module... the initializer will be filled in 500361e513dSReid Spencer // later by LinkGlobalInits... 501361e513dSReid Spencer GlobalVariable *NewDGV = 502361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 503361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 5040074ea3aSAnton Korobeynikov SGV->getName(), Dest); 5052dc36535SReid Spencer // Propagate alignment, visibility and section info. 5063aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 507dd924e4eSAndrew Lenharth 508361e513dSReid Spencer // If the LLVM runtime renamed the global, but it is an externally visible 509361e513dSReid Spencer // symbol, DGV must be an existing global with internal linkage. Rename 510361e513dSReid Spencer // it. 511361e513dSReid Spencer if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()) 512361e513dSReid Spencer ForceRenaming(NewDGV, SGV->getName()); 513361e513dSReid Spencer 514361e513dSReid Spencer // Make sure to remember this mapping... 51566a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 51666a6271cSAnton Korobeynikov 517361e513dSReid Spencer if (SGV->hasAppendingLinkage()) 518361e513dSReid Spencer // Keep track that this is an appending variable... 519361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 520fc61de39SChris Lattner } else if (DGV->hasAppendingLinkage()) { 521361e513dSReid Spencer // No linking is performed yet. Just insert a new copy of the global, and 522361e513dSReid Spencer // keep track of the fact that it is an appending variable in the 523361e513dSReid Spencer // AppendingVars map. The name is cleared out so that no linkage is 524361e513dSReid Spencer // performed. 525361e513dSReid Spencer GlobalVariable *NewDGV = 526361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 527361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 5280074ea3aSAnton Korobeynikov "", Dest); 529361e513dSReid Spencer 530e8a3e74bSAnton Korobeynikov // Set alignment allowing CopyGVAttributes merge it with alignment of SGV. 5313aaaa0b2SReid Spencer NewDGV->setAlignment(DGV->getAlignment()); 532e8a3e74bSAnton Korobeynikov // Propagate alignment, section and visibility info. 5333aaaa0b2SReid Spencer CopyGVAttributes(NewDGV, SGV); 534dd924e4eSAndrew Lenharth 535361e513dSReid Spencer // Make sure to remember this mapping... 53666a6271cSAnton Korobeynikov ValueMap[SGV] = NewDGV; 537361e513dSReid Spencer 538361e513dSReid Spencer // Keep track that this is an appending variable... 539361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 540e79f4c77SAnton Korobeynikov } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) { 541e79f4c77SAnton Korobeynikov // SGV is global, but DGV is alias. The only valid mapping is when SGV is 542e79f4c77SAnton Korobeynikov // external declaration, which is effectively a no-op. Also make sure 54366a6271cSAnton Korobeynikov // linkage calculation was correct. 544e79f4c77SAnton Korobeynikov if (SGV->isDeclaration() && !LinkFromSrc) { 545e79f4c77SAnton Korobeynikov // Make sure to remember this mapping... 54666a6271cSAnton Korobeynikov ValueMap[SGV] = DGA; 547e79f4c77SAnton Korobeynikov } else 548eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGV->getName() + 549eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 550e79f4c77SAnton Korobeynikov } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) { 55166a6271cSAnton Korobeynikov // Otherwise, perform the global-global mapping as instructed by 55266a6271cSAnton Korobeynikov // GetLinkageResult. 553f6439246SAnton Korobeynikov if (LinkFromSrc) { 5542dc36535SReid Spencer // Propagate alignment, section, and visibility info. 555e79f4c77SAnton Korobeynikov CopyGVAttributes(DGVar, SGV); 556dd924e4eSAndrew Lenharth 5570074ea3aSAnton Korobeynikov // If the types don't match, and if we are to link from the source, nuke 5580074ea3aSAnton Korobeynikov // DGV and create a new one of the appropriate type. 559e79f4c77SAnton Korobeynikov if (SGV->getType() != DGVar->getType()) { 560fc61de39SChris Lattner GlobalVariable *NewDGV = 561fc61de39SChris Lattner new GlobalVariable(SGV->getType()->getElementType(), 562e79f4c77SAnton Korobeynikov DGVar->isConstant(), DGVar->getLinkage(), 563e79f4c77SAnton Korobeynikov /*init*/0, DGVar->getName(), Dest); 564e79f4c77SAnton Korobeynikov CopyGVAttributes(NewDGV, DGVar); 565f6439246SAnton Korobeynikov DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 566e79f4c77SAnton Korobeynikov DGVar->getType())); 567e79f4c77SAnton Korobeynikov // DGVar will conflict with NewDGV because they both had the same 568f6439246SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 569f6439246SAnton Korobeynikov // because DGV might not have internal linkage. 570e79f4c77SAnton Korobeynikov DGVar->eraseFromParent(); 571f6439246SAnton Korobeynikov 572f6439246SAnton Korobeynikov // If the symbol table renamed the global, but it is an externally 573f6439246SAnton Korobeynikov // visible symbol, DGV must be an existing global with internal 574f6439246SAnton Korobeynikov // linkage. Rename it. 575f6439246SAnton Korobeynikov if (NewDGV->getName() != SGV->getName() && 576f6439246SAnton Korobeynikov !NewDGV->hasInternalLinkage()) 577f6439246SAnton Korobeynikov ForceRenaming(NewDGV, SGV->getName()); 578f6439246SAnton Korobeynikov 579e79f4c77SAnton Korobeynikov DGVar = NewDGV; 580fc61de39SChris Lattner } 581fc61de39SChris Lattner 582fc61de39SChris Lattner // Inherit const as appropriate 583e79f4c77SAnton Korobeynikov DGVar->setConstant(SGV->isConstant()); 584f6439246SAnton Korobeynikov 585f6439246SAnton Korobeynikov // Set initializer to zero, so we can link the stuff later 586e79f4c77SAnton Korobeynikov DGVar->setInitializer(0); 587fc61de39SChris Lattner } else { 588f6439246SAnton Korobeynikov // Special case for const propagation 589e79f4c77SAnton Korobeynikov if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant()) 590e79f4c77SAnton Korobeynikov DGVar->setConstant(true); 591fc61de39SChris Lattner } 592fc61de39SChris Lattner 593f6439246SAnton Korobeynikov // Set calculated linkage 594e79f4c77SAnton Korobeynikov DGVar->setLinkage(NewLinkage); 595f6439246SAnton Korobeynikov 596f6439246SAnton Korobeynikov // Make sure to remember this mapping... 59766a6271cSAnton Korobeynikov ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType()); 598361e513dSReid Spencer } 599361e513dSReid Spencer } 600361e513dSReid Spencer return false; 601361e513dSReid Spencer } 602361e513dSReid Spencer 603dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes 604dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) { 605dac5fa94SAnton Korobeynikov if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage()) 606dac5fa94SAnton Korobeynikov return GlobalValue::ExternalLinkage; 607dac5fa94SAnton Korobeynikov else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage()) 608dac5fa94SAnton Korobeynikov return GlobalValue::WeakLinkage; 609dac5fa94SAnton Korobeynikov else { 610dac5fa94SAnton Korobeynikov assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() && 611dac5fa94SAnton Korobeynikov "Unexpected linkage type"); 612dac5fa94SAnton Korobeynikov return GlobalValue::InternalLinkage; 613dac5fa94SAnton Korobeynikov } 614dac5fa94SAnton Korobeynikov } 615dac5fa94SAnton Korobeynikov 616b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the 617dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already 618dac5fa94SAnton Korobeynikov // linked in. 6192e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src, 6202e13597fSAnton Korobeynikov std::map<const Value*, Value*> &ValueMap, 6212e13597fSAnton Korobeynikov std::string *Err) { 622b00c9c0dSLauro Ramos Venancio // Loop over all alias in the src module 623b00c9c0dSLauro Ramos Venancio for (Module::const_alias_iterator I = Src->alias_begin(), 624b00c9c0dSLauro Ramos Venancio E = Src->alias_end(); I != E; ++I) { 625dac5fa94SAnton Korobeynikov const GlobalAlias *SGA = I; 626dac5fa94SAnton Korobeynikov const GlobalValue *SAliasee = SGA->getAliasedGlobal(); 627dac5fa94SAnton Korobeynikov GlobalAlias *NewGA = NULL; 628b00c9c0dSLauro Ramos Venancio 629dac5fa94SAnton Korobeynikov // Globals were already linked, thus we can just query ValueMap for variant 630dac5fa94SAnton Korobeynikov // of SAliasee in Dest 631d48ed17dSTed Kremenek std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee); 632d48ed17dSTed Kremenek assert(VMI != ValueMap.end() && "Aliasee not linked"); 633d48ed17dSTed Kremenek GlobalValue* DAliasee = cast<GlobalValue>(VMI->second); 634b00c9c0dSLauro Ramos Venancio 635dac5fa94SAnton Korobeynikov // Try to find something 'similar' to SGA in destination module. 636dac5fa94SAnton Korobeynikov if (GlobalAlias *DGA = Dest->getNamedAlias(SGA->getName())) { 637dac5fa94SAnton Korobeynikov // If types don't agree due to opaque types, try to resolve them. 638dac5fa94SAnton Korobeynikov if (RecursiveResolveTypes(SGA->getType(), DGA->getType(), 639dac5fa94SAnton Korobeynikov &Dest->getTypeSymbolTable(), "")) 640eeb5ca6fSAnton Korobeynikov return Error(Err, "Alias Collision on '" + SGA->getName()+ 641eeb5ca6fSAnton Korobeynikov "': aliases have different types"); 6422e13597fSAnton Korobeynikov 643dac5fa94SAnton Korobeynikov // Now types are known to be the same, check whether aliasees equal. As 644dac5fa94SAnton Korobeynikov // globals are already linked we just need query ValueMap to find the 645dac5fa94SAnton Korobeynikov // mapping. 646dac5fa94SAnton Korobeynikov if (DAliasee == DGA->getAliasedGlobal()) { 647dac5fa94SAnton Korobeynikov // This is just two copies of the same alias. Propagate linkage, if 648dac5fa94SAnton Korobeynikov // necessary. 649dac5fa94SAnton Korobeynikov DGA->setLinkage(CalculateAliasLinkage(SGA, DGA)); 650dac5fa94SAnton Korobeynikov 651dac5fa94SAnton Korobeynikov NewGA = DGA; 652dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 653dac5fa94SAnton Korobeynikov } else 654eeb5ca6fSAnton Korobeynikov return Error(Err, "Alias Collision on '" + SGA->getName()+ 655eeb5ca6fSAnton Korobeynikov "': aliases have different aliasees"); 656dac5fa94SAnton Korobeynikov } else if (GlobalVariable *DGV = Dest->getGlobalVariable(SGA->getName())) { 657dac5fa94SAnton Korobeynikov RecursiveResolveTypes(SGA->getType(), DGV->getType(), 658dac5fa94SAnton Korobeynikov &Dest->getTypeSymbolTable(), ""); 65924f65c3aSAnton Korobeynikov 660dac5fa94SAnton Korobeynikov // The only allowed way is to link alias with external declaration. 661dac5fa94SAnton Korobeynikov if (DGV->isDeclaration()) { 662510fc32dSAnton Korobeynikov // But only if aliasee is global too... 663510fc32dSAnton Korobeynikov if (!isa<GlobalVariable>(DAliasee)) 664510fc32dSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 665510fc32dSAnton Korobeynikov "': aliasee is not global variable"); 666510fc32dSAnton Korobeynikov 667dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 668dac5fa94SAnton Korobeynikov SGA->getName(), DAliasee, Dest); 669dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 670dac5fa94SAnton Korobeynikov 671dac5fa94SAnton Korobeynikov // Any uses of DGV need to change to NewGA, with cast, if needed. 672dac5fa94SAnton Korobeynikov if (SGA->getType() != DGV->getType()) 673dac5fa94SAnton Korobeynikov DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 674dac5fa94SAnton Korobeynikov DGV->getType())); 675dac5fa94SAnton Korobeynikov else 676dac5fa94SAnton Korobeynikov DGV->replaceAllUsesWith(NewGA); 677dac5fa94SAnton Korobeynikov 678dac5fa94SAnton Korobeynikov // DGV will conflict with NewGA because they both had the same 679dac5fa94SAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 680dac5fa94SAnton Korobeynikov // because DGV might not have internal linkage. 681dac5fa94SAnton Korobeynikov DGV->eraseFromParent(); 682dac5fa94SAnton Korobeynikov 683dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 684dac5fa94SAnton Korobeynikov } else 685eeb5ca6fSAnton Korobeynikov return Error(Err, "Global-Alias Collision on '" + SGA->getName() + 686eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 687dac5fa94SAnton Korobeynikov } else if (Function *DF = Dest->getFunction(SGA->getName())) { 688dac5fa94SAnton Korobeynikov RecursiveResolveTypes(SGA->getType(), DF->getType(), 689dac5fa94SAnton Korobeynikov &Dest->getTypeSymbolTable(), ""); 69024f65c3aSAnton Korobeynikov 69124f65c3aSAnton Korobeynikov // The only allowed way is to link alias with external declaration. 69224f65c3aSAnton Korobeynikov if (DF->isDeclaration()) { 693510fc32dSAnton Korobeynikov // But only if aliasee is function too... 694510fc32dSAnton Korobeynikov if (!isa<Function>(DAliasee)) 695510fc32dSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 696510fc32dSAnton Korobeynikov "': aliasee is not function"); 697510fc32dSAnton Korobeynikov 69824f65c3aSAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 69924f65c3aSAnton Korobeynikov SGA->getName(), DAliasee, Dest); 70024f65c3aSAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 70124f65c3aSAnton Korobeynikov 70224f65c3aSAnton Korobeynikov // Any uses of DF need to change to NewGA, with cast, if needed. 70324f65c3aSAnton Korobeynikov if (SGA->getType() != DF->getType()) 70424f65c3aSAnton Korobeynikov DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA, 70524f65c3aSAnton Korobeynikov DF->getType())); 70624f65c3aSAnton Korobeynikov else 70724f65c3aSAnton Korobeynikov DF->replaceAllUsesWith(NewGA); 70824f65c3aSAnton Korobeynikov 70924f65c3aSAnton Korobeynikov // DF will conflict with NewGA because they both had the same 71024f65c3aSAnton Korobeynikov // name. We must erase this now so ForceRenaming doesn't assert 71124f65c3aSAnton Korobeynikov // because DF might not have internal linkage. 71224f65c3aSAnton Korobeynikov DF->eraseFromParent(); 71324f65c3aSAnton Korobeynikov 71424f65c3aSAnton Korobeynikov // Proceed to 'common' steps 71524f65c3aSAnton Korobeynikov } else 716eeb5ca6fSAnton Korobeynikov return Error(Err, "Function-Alias Collision on '" + SGA->getName() + 717eeb5ca6fSAnton Korobeynikov "': symbol multiple defined"); 718dac5fa94SAnton Korobeynikov } else { 719dac5fa94SAnton Korobeynikov // Nothing similar found, just copy alias into destination module. 720dac5fa94SAnton Korobeynikov 721dac5fa94SAnton Korobeynikov NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(), 722dac5fa94SAnton Korobeynikov SGA->getName(), DAliasee, Dest); 723dac5fa94SAnton Korobeynikov CopyGVAttributes(NewGA, SGA); 724dac5fa94SAnton Korobeynikov 725dac5fa94SAnton Korobeynikov // Proceed to 'common' steps 726b00c9c0dSLauro Ramos Venancio } 727dac5fa94SAnton Korobeynikov 728dac5fa94SAnton Korobeynikov assert(NewGA && "No alias was created in destination module!"); 729dac5fa94SAnton Korobeynikov 730d5160da5SAnton Korobeynikov // If the symbol table renamed the alias, but it is an externally visible 731d5160da5SAnton Korobeynikov // symbol, DGV must be an global value with internal linkage. Rename it. 732dac5fa94SAnton Korobeynikov if (NewGA->getName() != SGA->getName() && 733dac5fa94SAnton Korobeynikov !NewGA->hasInternalLinkage()) 734dac5fa94SAnton Korobeynikov ForceRenaming(NewGA, SGA->getName()); 735dac5fa94SAnton Korobeynikov 736dac5fa94SAnton Korobeynikov // Remember this mapping so uses in the source module get remapped 737dac5fa94SAnton Korobeynikov // later by RemapOperand. 73866a6271cSAnton Korobeynikov ValueMap[SGA] = NewGA; 739dac5fa94SAnton Korobeynikov } 740dac5fa94SAnton Korobeynikov 741b00c9c0dSLauro Ramos Venancio return false; 742b00c9c0dSLauro Ramos Venancio } 743b00c9c0dSLauro Ramos Venancio 744361e513dSReid Spencer 745361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all 746361e513dSReid Spencer // globals that may be referenced are in Dest. 747361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src, 748361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 749361e513dSReid Spencer std::string *Err) { 750361e513dSReid Spencer 751361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 75244ab8aefSChris Lattner for (Module::const_global_iterator I = Src->global_begin(), 75344ab8aefSChris Lattner E = Src->global_end(); I != E; ++I) { 754361e513dSReid Spencer const GlobalVariable *SGV = I; 755361e513dSReid Spencer 756361e513dSReid Spencer if (SGV->hasInitializer()) { // Only process initialized GV's 757361e513dSReid Spencer // Figure out what the initializer looks like in the dest module... 758361e513dSReid Spencer Constant *SInit = 7597391dde1SChris Lattner cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap)); 760361e513dSReid Spencer 761361e513dSReid Spencer GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]); 762361e513dSReid Spencer if (DGV->hasInitializer()) { 763361e513dSReid Spencer if (SGV->hasExternalLinkage()) { 764361e513dSReid Spencer if (DGV->getInitializer() != SInit) 765eeb5ca6fSAnton Korobeynikov return Error(Err, "Global Variable Collision on '" + SGV->getName() + 766eeb5ca6fSAnton Korobeynikov "': global variables have different initializers"); 767361e513dSReid Spencer } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) { 768361e513dSReid Spencer // Nothing is required, mapped values will take the new global 769361e513dSReid Spencer // automatically. 770361e513dSReid Spencer } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) { 771361e513dSReid Spencer // Nothing is required, mapped values will take the new global 772361e513dSReid Spencer // automatically. 773361e513dSReid Spencer } else if (DGV->hasAppendingLinkage()) { 774361e513dSReid Spencer assert(0 && "Appending linkage unimplemented!"); 775361e513dSReid Spencer } else { 776361e513dSReid Spencer assert(0 && "Unknown linkage!"); 777361e513dSReid Spencer } 778361e513dSReid Spencer } else { 779361e513dSReid Spencer // Copy the initializer over now... 780361e513dSReid Spencer DGV->setInitializer(SInit); 781361e513dSReid Spencer } 782361e513dSReid Spencer } 783361e513dSReid Spencer } 784361e513dSReid Spencer return false; 785361e513dSReid Spencer } 786361e513dSReid Spencer 787361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules, 788361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes 789361e513dSReid Spencer // to the Dest function... 790361e513dSReid Spencer // 791361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src, 792361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 793361e513dSReid Spencer std::string *Err) { 794d3ba7d9bSReid Spencer // Loop over all of the functions in the src module, mapping them over 795361e513dSReid Spencer for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) { 796361e513dSReid Spencer const Function *SF = I; // SrcFunction 797361e513dSReid Spencer Function *DF = 0; 79890246aa7SReid Spencer if (SF->hasName() && !SF->hasInternalLinkage()) { 79990246aa7SReid Spencer // Check to see if may have to link the function. 8003aaaa0b2SReid Spencer DF = Dest->getFunction(SF->getName()); 8013aaaa0b2SReid Spencer if (DF && SF->getType() != DF->getType()) 8023aaaa0b2SReid Spencer // If types don't agree because of opaque, try to resolve them 8033aaaa0b2SReid Spencer RecursiveResolveTypes(SF->getType(), DF->getType(), 8043aaaa0b2SReid Spencer &Dest->getTypeSymbolTable(), ""); 805361e513dSReid Spencer } 806361e513dSReid Spencer 80731fc4f95SAnton Korobeynikov // Check visibility 80831fc4f95SAnton Korobeynikov if (DF && !DF->hasInternalLinkage() && 8091cc79985SChris Lattner SF->getVisibility() != DF->getVisibility()) { 8101cc79985SChris Lattner // If one is a prototype, ignore its visibility. Prototypes are always 8111cc79985SChris Lattner // overridden by the definition. 8121cc79985SChris Lattner if (!SF->isDeclaration() && !DF->isDeclaration()) 81331fc4f95SAnton Korobeynikov return Error(Err, "Linking functions named '" + SF->getName() + 81431fc4f95SAnton Korobeynikov "': symbols have different visibilities!"); 8151cc79985SChris Lattner } 81631fc4f95SAnton Korobeynikov 8174f00f531SAnton Korobeynikov if (DF && DF->hasInternalLinkage()) 8184f00f531SAnton Korobeynikov DF = NULL; 8194f00f531SAnton Korobeynikov 8203aaaa0b2SReid Spencer if (DF && DF->getType() != SF->getType()) { 8213aaaa0b2SReid Spencer if (DF->isDeclaration() && !SF->isDeclaration()) { 8223aaaa0b2SReid Spencer // We have a definition of the same name but different type in the 8233aaaa0b2SReid Spencer // source module. Copy the prototype to the destination and replace 8243aaaa0b2SReid Spencer // uses of the destination's prototype with the new prototype. 825e9ecc68dSGabor Greif Function *NewDF = Function::Create(SF->getFunctionType(), SF->getLinkage(), 8263aaaa0b2SReid Spencer SF->getName(), Dest); 8273aaaa0b2SReid Spencer CopyGVAttributes(NewDF, SF); 8283aaaa0b2SReid Spencer 8293aaaa0b2SReid Spencer // Any uses of DF need to change to NewDF, with cast 8303aaaa0b2SReid Spencer DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType())); 8313aaaa0b2SReid Spencer 8323aaaa0b2SReid Spencer // DF will conflict with NewDF because they both had the same. We must 8333aaaa0b2SReid Spencer // erase this now so ForceRenaming doesn't assert because DF might 8343aaaa0b2SReid Spencer // not have internal linkage. 8353aaaa0b2SReid Spencer DF->eraseFromParent(); 8363aaaa0b2SReid Spencer 8373aaaa0b2SReid Spencer // If the symbol table renamed the function, but it is an externally 8383aaaa0b2SReid Spencer // visible symbol, DF must be an existing function with internal 8393aaaa0b2SReid Spencer // linkage. Rename it. 8403aaaa0b2SReid Spencer if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) 8413aaaa0b2SReid Spencer ForceRenaming(NewDF, SF->getName()); 8423aaaa0b2SReid Spencer 8433aaaa0b2SReid Spencer // Remember this mapping so uses in the source module get remapped 8443aaaa0b2SReid Spencer // later by RemapOperand. 8453aaaa0b2SReid Spencer ValueMap[SF] = NewDF; 8463aaaa0b2SReid Spencer } else if (SF->isDeclaration()) { 8473aaaa0b2SReid Spencer // We have two functions of the same name but different type and the 8483aaaa0b2SReid Spencer // source is a declaration while the destination is not. Any use of 8493aaaa0b2SReid Spencer // the source must be mapped to the destination, with a cast. 8503aaaa0b2SReid Spencer ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType()); 8513aaaa0b2SReid Spencer } else { 8523aaaa0b2SReid Spencer // We have two functions of the same name but different types and they 8533aaaa0b2SReid Spencer // are both definitions. This is an error. 8543aaaa0b2SReid Spencer return Error(Err, "Function '" + DF->getName() + "' defined as both '" + 8553aaaa0b2SReid Spencer ToStr(SF->getFunctionType(), Src) + "' and '" + 8563aaaa0b2SReid Spencer ToStr(DF->getFunctionType(), Dest) + "'"); 8573aaaa0b2SReid Spencer } 8583aaaa0b2SReid Spencer } else if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) { 859361e513dSReid Spencer // Function does not already exist, simply insert an function signature 8601cc79985SChris Lattner // identical to SF into the dest module. 861e9ecc68dSGabor Greif Function *NewDF = Function::Create(SF->getFunctionType(), SF->getLinkage(), 862361e513dSReid Spencer SF->getName(), Dest); 8633aaaa0b2SReid Spencer CopyGVAttributes(NewDF, SF); 864361e513dSReid Spencer 865361e513dSReid Spencer // If the LLVM runtime renamed the function, but it is an externally 866361e513dSReid Spencer // visible symbol, DF must be an existing function with internal linkage. 867361e513dSReid Spencer // Rename it. 868361e513dSReid Spencer if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) 869361e513dSReid Spencer ForceRenaming(NewDF, SF->getName()); 870361e513dSReid Spencer 871361e513dSReid Spencer // ... and remember this mapping... 87266a6271cSAnton Korobeynikov ValueMap[SF] = NewDF; 8735301e7c6SReid Spencer } else if (SF->isDeclaration()) { 8743aaaa0b2SReid Spencer // If SF is a declaration or if both SF & DF are declarations, just link 8753aaaa0b2SReid Spencer // the declarations, we aren't adding anything. 876d61d39ecSAnton Korobeynikov if (SF->hasDLLImportLinkage()) { 8775301e7c6SReid Spencer if (DF->isDeclaration()) { 878361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 879d61d39ecSAnton Korobeynikov DF->setLinkage(SF->getLinkage()); 880d61d39ecSAnton Korobeynikov } 881d61d39ecSAnton Korobeynikov } else { 88266a6271cSAnton Korobeynikov ValueMap[SF] = DF; 883d61d39ecSAnton Korobeynikov } 8845301e7c6SReid Spencer } else if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) { 885d61d39ecSAnton Korobeynikov // If DF is external but SF is not... 886361e513dSReid Spencer // Link the external functions, update linkage qualifiers 887361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 888361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 8891cc79985SChris Lattner // Visibility of prototype is overridden by vis of definition. 8901cc79985SChris Lattner DF->setVisibility(SF->getVisibility()); 891361e513dSReid Spencer } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) { 89212c94949SAnton Korobeynikov // At this point we know that DF has LinkOnce, Weak, or External* linkage. 89366a6271cSAnton Korobeynikov ValueMap[SF] = DF; 894361e513dSReid Spencer 895361e513dSReid Spencer // Linkonce+Weak = Weak 89612c94949SAnton Korobeynikov // *+External Weak = * 89712c94949SAnton Korobeynikov if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) || 89812c94949SAnton Korobeynikov DF->hasExternalWeakLinkage()) 899361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 900361e513dSReid Spencer } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) { 90112c94949SAnton Korobeynikov // At this point we know that SF has LinkOnce or External* linkage. 90266a6271cSAnton Korobeynikov ValueMap[SF] = DF; 90312c94949SAnton Korobeynikov if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) 90412c94949SAnton Korobeynikov // Don't inherit linkonce & external weak linkage 905361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 906361e513dSReid Spencer } else if (SF->getLinkage() != DF->getLinkage()) { 907361e513dSReid Spencer return Error(Err, "Functions named '" + SF->getName() + 908361e513dSReid Spencer "' have different linkage specifiers!"); 909361e513dSReid Spencer } else if (SF->hasExternalLinkage()) { 9103aaaa0b2SReid Spencer // The function is defined identically in both modules!! 911361e513dSReid Spencer return Error(Err, "Function '" + 912361e513dSReid Spencer ToStr(SF->getFunctionType(), Src) + "':\"" + 913361e513dSReid Spencer SF->getName() + "\" - Function is already defined!"); 914361e513dSReid Spencer } else { 915361e513dSReid Spencer assert(0 && "Unknown linkage configuration found!"); 916361e513dSReid Spencer } 917361e513dSReid Spencer } 918361e513dSReid Spencer return false; 919361e513dSReid Spencer } 920361e513dSReid Spencer 921361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and 922361e513dSReid Spencer // fix up references to values. At this point we know that Dest is an external 923361e513dSReid Spencer // function, and that Src is not. 9242f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src, 9253aaaa0b2SReid Spencer std::map<const Value*, Value*> &ValueMap, 926361e513dSReid Spencer std::string *Err) { 9275301e7c6SReid Spencer assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration()); 928361e513dSReid Spencer 9297391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 930531f9e92SChris Lattner Function::arg_iterator DI = Dest->arg_begin(); 931531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 932361e513dSReid Spencer I != E; ++I, ++DI) { 933*7629b71dSOwen Anderson DI->setName(I->getName()); // Copy the name information over... 934361e513dSReid Spencer 935361e513dSReid Spencer // Add a mapping to our local map 93666a6271cSAnton Korobeynikov ValueMap[I] = DI; 937361e513dSReid Spencer } 938361e513dSReid Spencer 9392f0557d0SChris Lattner // Splice the body of the source function into the dest function. 9402f0557d0SChris Lattner Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList()); 941361e513dSReid Spencer 942361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 943361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 944361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 945361e513dSReid Spencer // functions and patch them up to point to the local versions... 946361e513dSReid Spencer // 947361e513dSReid Spencer for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB) 948361e513dSReid Spencer for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 949361e513dSReid Spencer for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 950361e513dSReid Spencer OI != OE; ++OI) 9512f0557d0SChris Lattner if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI)) 9523aaaa0b2SReid Spencer *OI = RemapOperand(*OI, ValueMap); 9537391dde1SChris Lattner 9547391dde1SChris Lattner // There is no need to map the arguments anymore. 95544ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 95644ab8aefSChris Lattner I != E; ++I) 9573aaaa0b2SReid Spencer ValueMap.erase(I); 958361e513dSReid Spencer 959361e513dSReid Spencer return false; 960361e513dSReid Spencer } 961361e513dSReid Spencer 962361e513dSReid Spencer 963361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the 964361e513dSReid Spencer // source module into the DestModule. This consists basically of copying the 965361e513dSReid Spencer // function over and fixing up references to values. 9662f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src, 967361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 968361e513dSReid Spencer std::string *Err) { 969361e513dSReid Spencer 97090246aa7SReid Spencer // Loop over all of the functions in the src module, mapping them over as we 97190246aa7SReid Spencer // go 9722f0557d0SChris Lattner for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) { 9735301e7c6SReid Spencer if (!SF->isDeclaration()) { // No body if function is external 974361e513dSReid Spencer Function *DF = cast<Function>(ValueMap[SF]); // Destination function 975361e513dSReid Spencer 976361e513dSReid Spencer // DF not external SF external? 9773aaaa0b2SReid Spencer if (DF->isDeclaration()) 978361e513dSReid Spencer // Only provide the function body if there isn't one already. 979361e513dSReid Spencer if (LinkFunctionBody(DF, SF, ValueMap, Err)) 980361e513dSReid Spencer return true; 98190246aa7SReid Spencer } 982361e513dSReid Spencer } 983361e513dSReid Spencer return false; 984361e513dSReid Spencer } 985361e513dSReid Spencer 986361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them 987361e513dSReid Spencer // together now. Return true on error. 988361e513dSReid Spencer static bool LinkAppendingVars(Module *M, 989361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 990361e513dSReid Spencer std::string *ErrorMsg) { 991361e513dSReid Spencer if (AppendingVars.empty()) return false; // Nothing to do. 992361e513dSReid Spencer 993361e513dSReid Spencer // Loop over the multimap of appending vars, processing any variables with the 994361e513dSReid Spencer // same name, forming a new appending global variable with both of the 995361e513dSReid Spencer // initializers merged together, then rewrite references to the old variables 996361e513dSReid Spencer // and delete them. 997361e513dSReid Spencer std::vector<Constant*> Inits; 998361e513dSReid Spencer while (AppendingVars.size() > 1) { 999361e513dSReid Spencer // Get the first two elements in the map... 1000361e513dSReid Spencer std::multimap<std::string, 1001361e513dSReid Spencer GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++; 1002361e513dSReid Spencer 1003361e513dSReid Spencer // If the first two elements are for different names, there is no pair... 1004361e513dSReid Spencer // Otherwise there is a pair, so link them together... 1005361e513dSReid Spencer if (First->first == Second->first) { 1006361e513dSReid Spencer GlobalVariable *G1 = First->second, *G2 = Second->second; 1007361e513dSReid Spencer const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType()); 1008361e513dSReid Spencer const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType()); 1009361e513dSReid Spencer 1010361e513dSReid Spencer // Check to see that they two arrays agree on type... 1011361e513dSReid Spencer if (T1->getElementType() != T2->getElementType()) 1012361e513dSReid Spencer return Error(ErrorMsg, 1013361e513dSReid Spencer "Appending variables with different element types need to be linked!"); 1014361e513dSReid Spencer if (G1->isConstant() != G2->isConstant()) 1015361e513dSReid Spencer return Error(ErrorMsg, 1016361e513dSReid Spencer "Appending variables linked with different const'ness!"); 1017361e513dSReid Spencer 101885703e37SLauro Ramos Venancio if (G1->getAlignment() != G2->getAlignment()) 101985703e37SLauro Ramos Venancio return Error(ErrorMsg, 102085703e37SLauro Ramos Venancio "Appending variables with different alignment need to be linked!"); 102185703e37SLauro Ramos Venancio 102285703e37SLauro Ramos Venancio if (G1->getVisibility() != G2->getVisibility()) 102385703e37SLauro Ramos Venancio return Error(ErrorMsg, 102485703e37SLauro Ramos Venancio "Appending variables with different visibility need to be linked!"); 102585703e37SLauro Ramos Venancio 102685703e37SLauro Ramos Venancio if (G1->getSection() != G2->getSection()) 102785703e37SLauro Ramos Venancio return Error(ErrorMsg, 102885703e37SLauro Ramos Venancio "Appending variables with different section name need to be linked!"); 102985703e37SLauro Ramos Venancio 1030361e513dSReid Spencer unsigned NewSize = T1->getNumElements() + T2->getNumElements(); 1031361e513dSReid Spencer ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize); 1032361e513dSReid Spencer 1033d490d4f0SChris Lattner G1->setName(""); // Clear G1's name in case of a conflict! 1034d490d4f0SChris Lattner 1035361e513dSReid Spencer // Create the new global variable... 1036361e513dSReid Spencer GlobalVariable *NG = 1037361e513dSReid Spencer new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(), 1038749e4668SLauro Ramos Venancio /*init*/0, First->first, M, G1->isThreadLocal()); 1039361e513dSReid Spencer 104085703e37SLauro Ramos Venancio // Propagate alignment, visibility and section info. 104185703e37SLauro Ramos Venancio CopyGVAttributes(NG, G1); 104285703e37SLauro Ramos Venancio 1043361e513dSReid Spencer // Merge the initializer... 1044361e513dSReid Spencer Inits.reserve(NewSize); 1045361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) { 1046361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1047361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1048361e513dSReid Spencer } else { 1049361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G1->getInitializer())); 1050361e513dSReid Spencer Constant *CV = Constant::getNullValue(T1->getElementType()); 1051361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 1052361e513dSReid Spencer Inits.push_back(CV); 1053361e513dSReid Spencer } 1054361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) { 1055361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1056361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 1057361e513dSReid Spencer } else { 1058361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G2->getInitializer())); 1059361e513dSReid Spencer Constant *CV = Constant::getNullValue(T2->getElementType()); 1060361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 1061361e513dSReid Spencer Inits.push_back(CV); 1062361e513dSReid Spencer } 1063361e513dSReid Spencer NG->setInitializer(ConstantArray::get(NewType, Inits)); 1064361e513dSReid Spencer Inits.clear(); 1065361e513dSReid Spencer 1066361e513dSReid Spencer // Replace any uses of the two global variables with uses of the new 1067361e513dSReid Spencer // global... 1068361e513dSReid Spencer 1069361e513dSReid Spencer // FIXME: This should rewrite simple/straight-forward uses such as 1070361e513dSReid Spencer // getelementptr instructions to not use the Cast! 1071b341b086SReid Spencer G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType())); 1072b341b086SReid Spencer G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType())); 1073361e513dSReid Spencer 1074361e513dSReid Spencer // Remove the two globals from the module now... 1075361e513dSReid Spencer M->getGlobalList().erase(G1); 1076361e513dSReid Spencer M->getGlobalList().erase(G2); 1077361e513dSReid Spencer 1078361e513dSReid Spencer // Put the new global into the AppendingVars map so that we can handle 1079361e513dSReid Spencer // linking of more than two vars... 1080361e513dSReid Spencer Second->second = NG; 1081361e513dSReid Spencer } 1082361e513dSReid Spencer AppendingVars.erase(First); 1083361e513dSReid Spencer } 1084361e513dSReid Spencer 1085361e513dSReid Spencer return false; 1086361e513dSReid Spencer } 1087361e513dSReid Spencer 10882609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) { 10892609888fSAnton Korobeynikov for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end(); 1090e6d90f5aSAnton Korobeynikov I != E; ++I) 1091e6d90f5aSAnton Korobeynikov if (const GlobalValue *GV = I->resolveAliasedGlobal()) 10922609888fSAnton Korobeynikov if (!GV->isDeclaration()) 1093e6d90f5aSAnton Korobeynikov I->replaceAllUsesWith(const_cast<GlobalValue*>(GV)); 10942609888fSAnton Korobeynikov 10952609888fSAnton Korobeynikov return false; 10962609888fSAnton Korobeynikov } 1097361e513dSReid Spencer 1098361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting 1099361e513dSReid Spencer // left module modified to be the composite of the two input modules. If an 1100361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate 1101361e513dSReid Spencer // the problem. Upon failure, the Dest module could be in a modified state, and 1102361e513dSReid Spencer // shouldn't be relied on to be consistent. 1103c4e31534SReid Spencer bool 1104c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) { 1105361e513dSReid Spencer assert(Dest != 0 && "Invalid Destination module"); 1106361e513dSReid Spencer assert(Src != 0 && "Invalid Source Module"); 1107361e513dSReid Spencer 11087f3bd82aSChris Lattner if (Dest->getDataLayout().empty()) { 11097f3bd82aSChris Lattner if (!Src->getDataLayout().empty()) { 111078bddc38SChris Lattner Dest->setDataLayout(Src->getDataLayout()); 11117f3bd82aSChris Lattner } else { 11123ac38e99SReid Spencer std::string DataLayout; 11133ac38e99SReid Spencer 1114bddf51bcSAnton Korobeynikov if (Dest->getEndianness() == Module::AnyEndianness) { 11153ac38e99SReid Spencer if (Src->getEndianness() == Module::BigEndian) 11163ac38e99SReid Spencer DataLayout.append("E"); 11173ac38e99SReid Spencer else if (Src->getEndianness() == Module::LittleEndian) 11183ac38e99SReid Spencer DataLayout.append("e"); 1119bddf51bcSAnton Korobeynikov } 1120bddf51bcSAnton Korobeynikov 1121bddf51bcSAnton Korobeynikov if (Dest->getPointerSize() == Module::AnyPointerSize) { 11223ac38e99SReid Spencer if (Src->getPointerSize() == Module::Pointer64) 11233ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64"); 11243ac38e99SReid Spencer else if (Src->getPointerSize() == Module::Pointer32) 11253ac38e99SReid Spencer DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32"); 1126bddf51bcSAnton Korobeynikov } 11273ac38e99SReid Spencer Dest->setDataLayout(DataLayout); 11287f3bd82aSChris Lattner } 11297f3bd82aSChris Lattner } 1130361e513dSReid Spencer 113190c2df5bSChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 11327f3bd82aSChris Lattner if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty()) 11337f3bd82aSChris Lattner Dest->setTargetTriple(Src->getTargetTriple()); 11347f3bd82aSChris Lattner 11357f3bd82aSChris Lattner if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() && 11367f3bd82aSChris Lattner Src->getDataLayout() != Dest->getDataLayout()) 11373ac38e99SReid Spencer cerr << "WARNING: Linking two modules of different data layouts!\n"; 1138b7f5916eSChris Lattner if (!Src->getTargetTriple().empty() && 1139b7f5916eSChris Lattner Dest->getTargetTriple() != Src->getTargetTriple()) 1140f3baad3eSBill Wendling cerr << "WARNING: Linking two modules of different target triples!\n"; 1141361e513dSReid Spencer 114290c2df5bSChris Lattner // Append the module inline asm string. 11438ebd2164SChris Lattner if (!Src->getModuleInlineAsm().empty()) { 11448ebd2164SChris Lattner if (Dest->getModuleInlineAsm().empty()) 11458ebd2164SChris Lattner Dest->setModuleInlineAsm(Src->getModuleInlineAsm()); 1146dd2d3fafSChris Lattner else 11478ebd2164SChris Lattner Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+ 11488ebd2164SChris Lattner Src->getModuleInlineAsm()); 1149dd2d3fafSChris Lattner } 1150dd2d3fafSChris Lattner 1151361e513dSReid Spencer // Update the destination module's dependent libraries list with the libraries 1152361e513dSReid Spencer // from the source module. There's no opportunity for duplicates here as the 1153361e513dSReid Spencer // Module ensures that duplicate insertions are discarded. 115490c2df5bSChris Lattner for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end(); 115590c2df5bSChris Lattner SI != SE; ++SI) 1156361e513dSReid Spencer Dest->addLibrary(*SI); 1157361e513dSReid Spencer 1158361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 1159361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 1160361e513dSReid Spencer // Make sure there are no type name conflicts. 1161d3ba7d9bSReid Spencer if (LinkTypes(Dest, Src, ErrorMsg)) 1162d3ba7d9bSReid Spencer return true; 1163361e513dSReid Spencer 1164361e513dSReid Spencer // ValueMap - Mapping of values from what they used to be in Src, to what they 1165361e513dSReid Spencer // are now in Dest. 1166361e513dSReid Spencer std::map<const Value*, Value*> ValueMap; 1167361e513dSReid Spencer 1168361e513dSReid Spencer // AppendingVars - Keep track of global variables in the destination module 1169361e513dSReid Spencer // with appending linkage. After the module is linked together, they are 1170361e513dSReid Spencer // appended and the module is rewritten. 1171361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> AppendingVars; 117244ab8aefSChris Lattner for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end(); 117344ab8aefSChris Lattner I != E; ++I) { 1174361e513dSReid Spencer // Add all of the appending globals already in the Dest module to 1175361e513dSReid Spencer // AppendingVars. 1176361e513dSReid Spencer if (I->hasAppendingLinkage()) 1177361e513dSReid Spencer AppendingVars.insert(std::make_pair(I->getName(), I)); 1178361e513dSReid Spencer } 1179361e513dSReid Spencer 1180361e513dSReid Spencer // Insert all of the globals in src into the Dest module... without linking 1181361e513dSReid Spencer // initializers (which could refer to functions not yet mapped over). 11823aaaa0b2SReid Spencer if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) 1183361e513dSReid Spencer return true; 1184361e513dSReid Spencer 1185361e513dSReid Spencer // Link the functions together between the two modules, without doing function 1186361e513dSReid Spencer // bodies... this just adds external function prototypes to the Dest 1187361e513dSReid Spencer // function... We do this so that when we begin processing function bodies, 1188361e513dSReid Spencer // all of the global values that may be referenced are available in our 1189361e513dSReid Spencer // ValueMap. 11903aaaa0b2SReid Spencer if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) 1191361e513dSReid Spencer return true; 1192361e513dSReid Spencer 11932e13597fSAnton Korobeynikov // If there were any alias, link them now. We really need to do this now, 11942e13597fSAnton Korobeynikov // because all of the aliases that may be referenced need to be available in 11952e13597fSAnton Korobeynikov // ValueMap 11962e13597fSAnton Korobeynikov if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true; 11972e13597fSAnton Korobeynikov 1198361e513dSReid Spencer // Update the initializers in the Dest module now that all globals that may 1199361e513dSReid Spencer // be referenced are in Dest. 1200361e513dSReid Spencer if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true; 1201361e513dSReid Spencer 1202361e513dSReid Spencer // Link in the function bodies that are defined in the source module into the 1203361e513dSReid Spencer // DestModule. This consists basically of copying the function over and 1204361e513dSReid Spencer // fixing up references to values. 1205361e513dSReid Spencer if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true; 1206361e513dSReid Spencer 1207361e513dSReid Spencer // If there were any appending global variables, link them together now. 1208361e513dSReid Spencer if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true; 1209361e513dSReid Spencer 1210e43711d3SAnton Korobeynikov // Resolve all uses of aliases with aliasees 1211e43711d3SAnton Korobeynikov if (ResolveAliases(Dest)) return true; 1212e43711d3SAnton Korobeynikov 1213361e513dSReid Spencer // If the source library's module id is in the dependent library list of the 1214361e513dSReid Spencer // destination library, remove it since that module is now linked in. 1215361e513dSReid Spencer sys::Path modId; 1216c9c0473fSReid Spencer modId.set(Src->getModuleIdentifier()); 1217361e513dSReid Spencer if (!modId.isEmpty()) 1218361e513dSReid Spencer Dest->removeLibrary(modId.getBasename()); 1219361e513dSReid Spencer 1220361e513dSReid Spencer return false; 1221361e513dSReid Spencer } 1222361e513dSReid Spencer 1223361e513dSReid Spencer // vim: sw=2 1224