1361e513dSReid Spencer //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5361e513dSReid Spencer // This file was developed by the LLVM research group and is distributed under 6361e513dSReid Spencer // the University of Illinois Open Source 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" 23361e513dSReid Spencer #include "llvm/SymbolTable.h" 24361e513dSReid Spencer #include "llvm/Instructions.h" 25361e513dSReid Spencer #include "llvm/Assembly/Writer.h" 26361e513dSReid Spencer #include "llvm/System/Path.h" 27361e513dSReid Spencer #include <iostream> 28361e513dSReid Spencer #include <sstream> 29361e513dSReid Spencer using namespace llvm; 30361e513dSReid Spencer 31361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true. 32361e513dSReid Spencer // This just makes error return conditions a little bit simpler... 33361e513dSReid Spencer // 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 39361e513dSReid Spencer static std::string ToStr(const Type *Ty, const Module *M) { 40361e513dSReid Spencer std::ostringstream OS; 41361e513dSReid Spencer WriteTypeSymbolic(OS, Ty, M); 42361e513dSReid Spencer return OS.str(); 43361e513dSReid Spencer } 44361e513dSReid Spencer 45361e513dSReid Spencer // 46361e513dSReid Spencer // Function: ResolveTypes() 47361e513dSReid Spencer // 48361e513dSReid Spencer // Description: 49361e513dSReid Spencer // Attempt to link the two specified types together. 50361e513dSReid Spencer // 51361e513dSReid Spencer // Inputs: 52361e513dSReid Spencer // DestTy - The type to which we wish to resolve. 53361e513dSReid Spencer // SrcTy - The original type which we want to resolve. 54361e513dSReid Spencer // Name - The name of the type. 55361e513dSReid Spencer // 56361e513dSReid Spencer // Outputs: 57361e513dSReid Spencer // DestST - The symbol table in which the new type should be placed. 58361e513dSReid Spencer // 59361e513dSReid Spencer // Return value: 60361e513dSReid Spencer // true - There is an error and the types cannot yet be linked. 61361e513dSReid Spencer // false - No errors. 62361e513dSReid Spencer // 63361e513dSReid Spencer static bool ResolveTypes(const Type *DestTy, const Type *SrcTy, 64361e513dSReid Spencer SymbolTable *DestST, const std::string &Name) { 65361e513dSReid Spencer if (DestTy == SrcTy) return false; // If already equal, noop 66361e513dSReid Spencer 67361e513dSReid Spencer // Does the type already exist in the module? 68361e513dSReid Spencer if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists... 69361e513dSReid Spencer if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) { 70361e513dSReid Spencer const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy); 71361e513dSReid Spencer } else { 72361e513dSReid Spencer return true; // Cannot link types... neither is opaque and not-equal 73361e513dSReid Spencer } 74361e513dSReid Spencer } else { // Type not in dest module. Add it now. 75361e513dSReid Spencer if (DestTy) // Type _is_ in module, just opaque... 76361e513dSReid Spencer const_cast<OpaqueType*>(cast<OpaqueType>(DestTy)) 77361e513dSReid Spencer ->refineAbstractTypeTo(SrcTy); 78361e513dSReid Spencer else if (!Name.empty()) 79361e513dSReid Spencer DestST->insert(Name, const_cast<Type*>(SrcTy)); 80361e513dSReid Spencer } 81361e513dSReid Spencer return false; 82361e513dSReid Spencer } 83361e513dSReid Spencer 84361e513dSReid Spencer static const FunctionType *getFT(const PATypeHolder &TH) { 85361e513dSReid Spencer return cast<FunctionType>(TH.get()); 86361e513dSReid Spencer } 87361e513dSReid Spencer static const StructType *getST(const PATypeHolder &TH) { 88361e513dSReid Spencer return cast<StructType>(TH.get()); 89361e513dSReid Spencer } 90361e513dSReid Spencer 91361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it 92361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types 93361e513dSReid Spencer // are compatible. 94361e513dSReid Spencer // 95361e513dSReid Spencer static bool RecursiveResolveTypesI(const PATypeHolder &DestTy, 96361e513dSReid Spencer const PATypeHolder &SrcTy, 97361e513dSReid Spencer SymbolTable *DestST, const std::string &Name, 98361e513dSReid Spencer std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) { 99361e513dSReid Spencer const Type *SrcTyT = SrcTy.get(); 100361e513dSReid Spencer const Type *DestTyT = DestTy.get(); 101361e513dSReid Spencer if (DestTyT == SrcTyT) return false; // If already equal, noop 102361e513dSReid Spencer 103361e513dSReid Spencer // If we found our opaque type, resolve it now! 104361e513dSReid Spencer if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT)) 105361e513dSReid Spencer return ResolveTypes(DestTyT, SrcTyT, DestST, Name); 106361e513dSReid Spencer 107361e513dSReid Spencer // Two types cannot be resolved together if they are of different primitive 108361e513dSReid Spencer // type. For example, we cannot resolve an int to a float. 109361e513dSReid Spencer if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true; 110361e513dSReid Spencer 111361e513dSReid Spencer // Otherwise, resolve the used type used by this derived type... 112361e513dSReid Spencer switch (DestTyT->getTypeID()) { 113361e513dSReid Spencer case Type::FunctionTyID: { 114361e513dSReid Spencer if (cast<FunctionType>(DestTyT)->isVarArg() != 115361e513dSReid Spencer cast<FunctionType>(SrcTyT)->isVarArg() || 116361e513dSReid Spencer cast<FunctionType>(DestTyT)->getNumContainedTypes() != 117361e513dSReid Spencer cast<FunctionType>(SrcTyT)->getNumContainedTypes()) 118361e513dSReid Spencer return true; 119361e513dSReid Spencer for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i) 120361e513dSReid Spencer if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i), 121361e513dSReid Spencer getFT(SrcTy)->getContainedType(i), DestST, "", 122361e513dSReid Spencer Pointers)) 123361e513dSReid Spencer return true; 124361e513dSReid Spencer return false; 125361e513dSReid Spencer } 126361e513dSReid Spencer case Type::StructTyID: { 127361e513dSReid Spencer if (getST(DestTy)->getNumContainedTypes() != 128361e513dSReid Spencer getST(SrcTy)->getNumContainedTypes()) return 1; 129361e513dSReid Spencer for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i) 130361e513dSReid Spencer if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i), 131361e513dSReid Spencer getST(SrcTy)->getContainedType(i), DestST, "", 132361e513dSReid Spencer Pointers)) 133361e513dSReid Spencer return true; 134361e513dSReid Spencer return false; 135361e513dSReid Spencer } 136361e513dSReid Spencer case Type::ArrayTyID: { 137361e513dSReid Spencer const ArrayType *DAT = cast<ArrayType>(DestTy.get()); 138361e513dSReid Spencer const ArrayType *SAT = cast<ArrayType>(SrcTy.get()); 139361e513dSReid Spencer if (DAT->getNumElements() != SAT->getNumElements()) return true; 140361e513dSReid Spencer return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(), 141361e513dSReid Spencer DestST, "", Pointers); 142361e513dSReid Spencer } 143361e513dSReid Spencer case Type::PointerTyID: { 144361e513dSReid Spencer // If this is a pointer type, check to see if we have already seen it. If 145361e513dSReid Spencer // so, we are in a recursive branch. Cut off the search now. We cannot use 146361e513dSReid Spencer // an associative container for this search, because the type pointers (keys 147361e513dSReid Spencer // in the container) change whenever types get resolved... 148361e513dSReid Spencer // 149361e513dSReid Spencer for (unsigned i = 0, e = Pointers.size(); i != e; ++i) 150361e513dSReid Spencer if (Pointers[i].first == DestTy) 151361e513dSReid Spencer return Pointers[i].second != SrcTy; 152361e513dSReid Spencer 153361e513dSReid Spencer // Otherwise, add the current pointers to the vector to stop recursion on 154361e513dSReid Spencer // this pair. 155361e513dSReid Spencer Pointers.push_back(std::make_pair(DestTyT, SrcTyT)); 156361e513dSReid Spencer bool Result = 157361e513dSReid Spencer RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(), 158361e513dSReid Spencer cast<PointerType>(SrcTy.get())->getElementType(), 159361e513dSReid Spencer DestST, "", Pointers); 160361e513dSReid Spencer Pointers.pop_back(); 161361e513dSReid Spencer return Result; 162361e513dSReid Spencer } 163361e513dSReid Spencer default: assert(0 && "Unexpected type!"); return true; 164361e513dSReid Spencer } 165361e513dSReid Spencer } 166361e513dSReid Spencer 167361e513dSReid Spencer static bool RecursiveResolveTypes(const PATypeHolder &DestTy, 168361e513dSReid Spencer const PATypeHolder &SrcTy, 169361e513dSReid Spencer SymbolTable *DestST, const std::string &Name){ 170361e513dSReid Spencer std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes; 171361e513dSReid Spencer return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes); 172361e513dSReid Spencer } 173361e513dSReid Spencer 174361e513dSReid Spencer 175361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 176361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 177361e513dSReid Spencer // Make sure there are no type name conflicts. 178361e513dSReid Spencer // 179361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) { 180361e513dSReid Spencer SymbolTable *DestST = &Dest->getSymbolTable(); 181361e513dSReid Spencer const SymbolTable *SrcST = &Src->getSymbolTable(); 182361e513dSReid Spencer 183361e513dSReid Spencer // Look for a type plane for Type's... 184361e513dSReid Spencer SymbolTable::type_const_iterator TI = SrcST->type_begin(); 185361e513dSReid Spencer SymbolTable::type_const_iterator TE = SrcST->type_end(); 186361e513dSReid Spencer if (TI == TE) return false; // No named types, do nothing. 187361e513dSReid Spencer 188361e513dSReid Spencer // Some types cannot be resolved immediately because they depend on other 189361e513dSReid Spencer // types being resolved to each other first. This contains a list of types we 190361e513dSReid Spencer // are waiting to recheck. 191361e513dSReid Spencer std::vector<std::string> DelayedTypesToResolve; 192361e513dSReid Spencer 193361e513dSReid Spencer for ( ; TI != TE; ++TI ) { 194361e513dSReid Spencer const std::string &Name = TI->first; 195361e513dSReid Spencer const Type *RHS = TI->second; 196361e513dSReid Spencer 197361e513dSReid Spencer // Check to see if this type name is already in the dest module... 198361e513dSReid Spencer Type *Entry = DestST->lookupType(Name); 199361e513dSReid Spencer 200361e513dSReid Spencer if (ResolveTypes(Entry, RHS, DestST, Name)) { 201361e513dSReid Spencer // They look different, save the types 'till later to resolve. 202361e513dSReid Spencer DelayedTypesToResolve.push_back(Name); 203361e513dSReid Spencer } 204361e513dSReid Spencer } 205361e513dSReid Spencer 206361e513dSReid Spencer // Iteratively resolve types while we can... 207361e513dSReid Spencer while (!DelayedTypesToResolve.empty()) { 208361e513dSReid Spencer // Loop over all of the types, attempting to resolve them if possible... 209361e513dSReid Spencer unsigned OldSize = DelayedTypesToResolve.size(); 210361e513dSReid Spencer 211361e513dSReid Spencer // Try direct resolution by name... 212361e513dSReid Spencer for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) { 213361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 214361e513dSReid Spencer Type *T1 = SrcST->lookupType(Name); 215361e513dSReid Spencer Type *T2 = DestST->lookupType(Name); 216361e513dSReid Spencer if (!ResolveTypes(T2, T1, DestST, Name)) { 217361e513dSReid Spencer // We are making progress! 218361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 219361e513dSReid Spencer --i; 220361e513dSReid Spencer } 221361e513dSReid Spencer } 222361e513dSReid Spencer 223361e513dSReid Spencer // Did we not eliminate any types? 224361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 225361e513dSReid Spencer // Attempt to resolve subelements of types. This allows us to merge these 226361e513dSReid Spencer // two types: { int* } and { opaque* } 227361e513dSReid Spencer for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) { 228361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve[i]; 229361e513dSReid Spencer PATypeHolder T1(SrcST->lookupType(Name)); 230361e513dSReid Spencer PATypeHolder T2(DestST->lookupType(Name)); 231361e513dSReid Spencer 232361e513dSReid Spencer if (!RecursiveResolveTypes(T2, T1, DestST, Name)) { 233361e513dSReid Spencer // We are making progress! 234361e513dSReid Spencer DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i); 235361e513dSReid Spencer 236361e513dSReid Spencer // Go back to the main loop, perhaps we can resolve directly by name 237361e513dSReid Spencer // now... 238361e513dSReid Spencer break; 239361e513dSReid Spencer } 240361e513dSReid Spencer } 241361e513dSReid Spencer 242361e513dSReid Spencer // If we STILL cannot resolve the types, then there is something wrong. 243361e513dSReid Spencer // Report the warning and delete one of the names. 244361e513dSReid Spencer if (DelayedTypesToResolve.size() == OldSize) { 245361e513dSReid Spencer const std::string &Name = DelayedTypesToResolve.back(); 246361e513dSReid Spencer 247361e513dSReid Spencer const Type *T1 = SrcST->lookupType(Name); 248361e513dSReid Spencer const Type *T2 = DestST->lookupType(Name); 249361e513dSReid Spencer std::cerr << "WARNING: Type conflict between types named '" << Name 250361e513dSReid Spencer << "'.\n Src='"; 251361e513dSReid Spencer WriteTypeSymbolic(std::cerr, T1, Src); 252361e513dSReid Spencer std::cerr << "'.\n Dest='"; 253361e513dSReid Spencer WriteTypeSymbolic(std::cerr, T2, Dest); 254361e513dSReid Spencer std::cerr << "'\n"; 255361e513dSReid Spencer 256361e513dSReid Spencer // Remove the symbol name from the destination. 257361e513dSReid Spencer DelayedTypesToResolve.pop_back(); 258361e513dSReid Spencer } 259361e513dSReid Spencer } 260361e513dSReid Spencer } 261361e513dSReid Spencer 262361e513dSReid Spencer 263361e513dSReid Spencer return false; 264361e513dSReid Spencer } 265361e513dSReid Spencer 266361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) { 267361e513dSReid Spencer for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end(); 268361e513dSReid Spencer I != E; ++I) { 269361e513dSReid Spencer std::cerr << " Fr: " << (void*)I->first << " "; 270361e513dSReid Spencer I->first->dump(); 271361e513dSReid Spencer std::cerr << " To: " << (void*)I->second << " "; 272361e513dSReid Spencer I->second->dump(); 273361e513dSReid Spencer std::cerr << "\n"; 274361e513dSReid Spencer } 275361e513dSReid Spencer } 276361e513dSReid Spencer 277361e513dSReid Spencer 2787391dde1SChris Lattner // RemapOperand - Use ValueMap to convert references from one module to another. 2797391dde1SChris Lattner // This is somewhat sophisticated in that it can automatically handle constant 2807391dde1SChris Lattner // references correctly as well... 281361e513dSReid Spencer // 282361e513dSReid Spencer static Value *RemapOperand(const Value *In, 2837391dde1SChris Lattner std::map<const Value*, Value*> &ValueMap) { 2847391dde1SChris Lattner std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In); 2857391dde1SChris Lattner if (I != ValueMap.end()) return I->second; 286361e513dSReid Spencer 2877391dde1SChris Lattner // Check to see if it's a constant that we are interesting in transforming. 288361e513dSReid Spencer if (const Constant *CPV = dyn_cast<Constant>(In)) { 289361e513dSReid Spencer if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) || 290361e513dSReid Spencer isa<ConstantAggregateZero>(CPV)) 2917391dde1SChris Lattner return const_cast<Constant*>(CPV); // Simple constants stay identical. 292361e513dSReid Spencer 293361e513dSReid Spencer Constant *Result = 0; 294361e513dSReid Spencer 295361e513dSReid Spencer if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) { 296361e513dSReid Spencer std::vector<Constant*> Operands(CPA->getNumOperands()); 297361e513dSReid Spencer for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 2987391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap)); 299361e513dSReid Spencer Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands); 300361e513dSReid Spencer } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) { 301361e513dSReid Spencer std::vector<Constant*> Operands(CPS->getNumOperands()); 302361e513dSReid Spencer for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 3037391dde1SChris Lattner Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap)); 304361e513dSReid Spencer Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands); 305361e513dSReid Spencer } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) { 306361e513dSReid Spencer Result = const_cast<Constant*>(CPV); 307361e513dSReid Spencer } else if (isa<GlobalValue>(CPV)) { 3087391dde1SChris Lattner Result = cast<Constant>(RemapOperand(CPV, ValueMap)); 309361e513dSReid Spencer } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) { 310361e513dSReid Spencer if (CE->getOpcode() == Instruction::GetElementPtr) { 3117391dde1SChris Lattner Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap); 312361e513dSReid Spencer std::vector<Constant*> Indices; 313361e513dSReid Spencer Indices.reserve(CE->getNumOperands()-1); 314361e513dSReid Spencer for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 315361e513dSReid Spencer Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i), 3167391dde1SChris Lattner ValueMap))); 317361e513dSReid Spencer 318361e513dSReid Spencer Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices); 319361e513dSReid Spencer } else if (CE->getNumOperands() == 1) { 320361e513dSReid Spencer // Cast instruction 321361e513dSReid Spencer assert(CE->getOpcode() == Instruction::Cast); 3227391dde1SChris Lattner Value *V = RemapOperand(CE->getOperand(0), ValueMap); 323361e513dSReid Spencer Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType()); 324361e513dSReid Spencer } else if (CE->getNumOperands() == 3) { 325361e513dSReid Spencer // Select instruction 326361e513dSReid Spencer assert(CE->getOpcode() == Instruction::Select); 3277391dde1SChris Lattner Value *V1 = RemapOperand(CE->getOperand(0), ValueMap); 3287391dde1SChris Lattner Value *V2 = RemapOperand(CE->getOperand(1), ValueMap); 3297391dde1SChris Lattner Value *V3 = RemapOperand(CE->getOperand(2), ValueMap); 330361e513dSReid Spencer Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2), 331361e513dSReid Spencer cast<Constant>(V3)); 332361e513dSReid Spencer } else if (CE->getNumOperands() == 2) { 333361e513dSReid Spencer // Binary operator... 3347391dde1SChris Lattner Value *V1 = RemapOperand(CE->getOperand(0), ValueMap); 3357391dde1SChris Lattner Value *V2 = RemapOperand(CE->getOperand(1), ValueMap); 336361e513dSReid Spencer 337361e513dSReid Spencer Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1), 338361e513dSReid Spencer cast<Constant>(V2)); 339361e513dSReid Spencer } else { 340361e513dSReid Spencer assert(0 && "Unknown constant expr type!"); 341361e513dSReid Spencer } 342361e513dSReid Spencer 343361e513dSReid Spencer } else { 344361e513dSReid Spencer assert(0 && "Unknown type of derived type constant value!"); 345361e513dSReid Spencer } 346361e513dSReid Spencer 347361e513dSReid Spencer // Cache the mapping in our local map structure... 3487391dde1SChris Lattner ValueMap.insert(std::make_pair(In, Result)); 349361e513dSReid Spencer return Result; 350361e513dSReid Spencer } 351361e513dSReid Spencer 3527391dde1SChris Lattner std::cerr << "LinkModules ValueMap: \n"; 3537391dde1SChris Lattner PrintMap(ValueMap); 354361e513dSReid Spencer 355361e513dSReid Spencer std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n"; 356361e513dSReid Spencer assert(0 && "Couldn't remap value!"); 357361e513dSReid Spencer return 0; 358361e513dSReid Spencer } 359361e513dSReid Spencer 360361e513dSReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict 361361e513dSReid Spencer /// in the symbol table. This is good for all clients except for us. Go 362361e513dSReid Spencer /// through the trouble to force this back. 363361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) { 364361e513dSReid Spencer assert(GV->getName() != Name && "Can't force rename to self"); 365361e513dSReid Spencer SymbolTable &ST = GV->getParent()->getSymbolTable(); 366361e513dSReid Spencer 367361e513dSReid Spencer // If there is a conflict, rename the conflict. 368361e513dSReid Spencer Value *ConflictVal = ST.lookup(GV->getType(), Name); 369361e513dSReid Spencer assert(ConflictVal&&"Why do we have to force rename if there is no conflic?"); 370361e513dSReid Spencer GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal); 371361e513dSReid Spencer assert(ConflictGV->hasInternalLinkage() && 372361e513dSReid Spencer "Not conflicting with a static global, should link instead!"); 373361e513dSReid Spencer 374361e513dSReid Spencer ConflictGV->setName(""); // Eliminate the conflict 375361e513dSReid Spencer GV->setName(Name); // Force the name back 376361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 377361e513dSReid Spencer assert(GV->getName() == Name && ConflictGV->getName() != Name && 378361e513dSReid Spencer "ForceRenaming didn't work"); 379361e513dSReid Spencer } 380361e513dSReid Spencer 381361e513dSReid Spencer 382361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge 383361e513dSReid Spencer // them into the dest module. 384361e513dSReid Spencer // 385361e513dSReid Spencer static bool LinkGlobals(Module *Dest, const Module *Src, 386361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 387361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 388361e513dSReid Spencer std::map<std::string, GlobalValue*> &GlobalsByName, 389361e513dSReid Spencer std::string *Err) { 390361e513dSReid Spencer // We will need a module level symbol table if the src module has a module 391361e513dSReid Spencer // level symbol table... 392361e513dSReid Spencer SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable(); 393361e513dSReid Spencer 394361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 395361e513dSReid Spencer // 396361e513dSReid Spencer for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){ 397361e513dSReid Spencer const GlobalVariable *SGV = I; 398361e513dSReid Spencer GlobalVariable *DGV = 0; 399361e513dSReid Spencer // Check to see if may have to link the global. 400361e513dSReid Spencer if (SGV->hasName() && !SGV->hasInternalLinkage()) 401361e513dSReid Spencer if (!(DGV = Dest->getGlobalVariable(SGV->getName(), 402361e513dSReid Spencer SGV->getType()->getElementType()))) { 403361e513dSReid Spencer std::map<std::string, GlobalValue*>::iterator EGV = 404361e513dSReid Spencer GlobalsByName.find(SGV->getName()); 405361e513dSReid Spencer if (EGV != GlobalsByName.end()) 406361e513dSReid Spencer DGV = dyn_cast<GlobalVariable>(EGV->second); 407361e513dSReid Spencer if (DGV && RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "")) 408361e513dSReid Spencer DGV = 0; // FIXME: gross. 409361e513dSReid Spencer } 410361e513dSReid Spencer 411361e513dSReid Spencer assert(SGV->hasInitializer() || SGV->hasExternalLinkage() && 412361e513dSReid Spencer "Global must either be external or have an initializer!"); 413361e513dSReid Spencer 414361e513dSReid Spencer bool SGExtern = SGV->isExternal(); 415361e513dSReid Spencer bool DGExtern = DGV ? DGV->isExternal() : false; 416361e513dSReid Spencer 417361e513dSReid Spencer if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) { 418361e513dSReid Spencer // No linking to be performed, simply create an identical version of the 419361e513dSReid Spencer // symbol over in the dest module... the initializer will be filled in 420361e513dSReid Spencer // later by LinkGlobalInits... 421361e513dSReid Spencer // 422361e513dSReid Spencer GlobalVariable *NewDGV = 423361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 424361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 425361e513dSReid Spencer SGV->getName(), Dest); 426361e513dSReid Spencer 427361e513dSReid Spencer // If the LLVM runtime renamed the global, but it is an externally visible 428361e513dSReid Spencer // symbol, DGV must be an existing global with internal linkage. Rename 429361e513dSReid Spencer // it. 430361e513dSReid Spencer if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()) 431361e513dSReid Spencer ForceRenaming(NewDGV, SGV->getName()); 432361e513dSReid Spencer 433361e513dSReid Spencer // Make sure to remember this mapping... 434361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, NewDGV)); 435361e513dSReid Spencer if (SGV->hasAppendingLinkage()) 436361e513dSReid Spencer // Keep track that this is an appending variable... 437361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 438361e513dSReid Spencer 439361e513dSReid Spencer } else if (SGV->isExternal()) { 440361e513dSReid Spencer // If SGV is external or if both SGV & DGV are external.. Just link the 441361e513dSReid Spencer // external globals, we aren't adding anything. 442361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, DGV)); 443361e513dSReid Spencer 444361e513dSReid Spencer // Inherit 'const' information. 445361e513dSReid Spencer if (SGV->isConstant()) DGV->setConstant(true); 446361e513dSReid Spencer 447361e513dSReid Spencer } else if (DGV->isExternal()) { // If DGV is external but SGV is not... 448361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, DGV)); 449361e513dSReid Spencer DGV->setLinkage(SGV->getLinkage()); // Inherit linkage! 450361e513dSReid Spencer 451361e513dSReid Spencer if (DGV->isConstant() && !SGV->isConstant()) 452361e513dSReid Spencer return Error(Err, "Linking globals named '" + SGV->getName() + 453361e513dSReid Spencer "': declaration is const but definition is not!"); 454361e513dSReid Spencer 455361e513dSReid Spencer // Inherit 'const' information. 456361e513dSReid Spencer if (SGV->isConstant()) DGV->setConstant(true); 457361e513dSReid Spencer 458361e513dSReid Spencer } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) { 459361e513dSReid Spencer // At this point we know that DGV has LinkOnce, Appending, Weak, or 460361e513dSReid Spencer // External linkage. If DGV is Appending, this is an error. 461361e513dSReid Spencer if (DGV->hasAppendingLinkage()) 462361e513dSReid Spencer return Error(Err, "Linking globals named '" + SGV->getName() + 463361e513dSReid Spencer "' with 'weak' and 'appending' linkage is not allowed!"); 464361e513dSReid Spencer 465361e513dSReid Spencer if (SGV->isConstant() != DGV->isConstant()) 466361e513dSReid Spencer return Error(Err, "Global Variable Collision on '" + 467361e513dSReid Spencer ToStr(SGV->getType(), Src) + " %" + SGV->getName() + 468361e513dSReid Spencer "' - Global variables differ in const'ness"); 469361e513dSReid Spencer 470361e513dSReid Spencer // Otherwise, just perform the link. 471361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, DGV)); 472361e513dSReid Spencer 473361e513dSReid Spencer // Linkonce+Weak = Weak 474361e513dSReid Spencer if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage()) 475361e513dSReid Spencer DGV->setLinkage(SGV->getLinkage()); 476361e513dSReid Spencer 477361e513dSReid Spencer } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) { 478361e513dSReid Spencer // At this point we know that SGV has LinkOnce, Appending, or External 479361e513dSReid Spencer // linkage. If SGV is Appending, this is an error. 480361e513dSReid Spencer if (SGV->hasAppendingLinkage()) 481361e513dSReid Spencer return Error(Err, "Linking globals named '" + SGV->getName() + 482361e513dSReid Spencer " ' with 'weak' and 'appending' linkage is not allowed!"); 483361e513dSReid Spencer 484361e513dSReid Spencer if (SGV->isConstant() != DGV->isConstant()) 485361e513dSReid Spencer return Error(Err, "Global Variable Collision on '" + 486361e513dSReid Spencer ToStr(SGV->getType(), Src) + " %" + SGV->getName() + 487361e513dSReid Spencer "' - Global variables differ in const'ness"); 488361e513dSReid Spencer 489361e513dSReid Spencer if (!SGV->hasLinkOnceLinkage()) 490361e513dSReid Spencer DGV->setLinkage(SGV->getLinkage()); // Inherit linkage! 491361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, DGV)); 492361e513dSReid Spencer 493361e513dSReid Spencer } else if (SGV->getLinkage() != DGV->getLinkage()) { 494361e513dSReid Spencer return Error(Err, "Global variables named '" + SGV->getName() + 495361e513dSReid Spencer "' have different linkage specifiers!"); 496361e513dSReid Spencer // Inherit 'const' information. 497361e513dSReid Spencer if (SGV->isConstant()) DGV->setConstant(true); 498361e513dSReid Spencer 499361e513dSReid Spencer } else if (SGV->hasExternalLinkage()) { 500361e513dSReid Spencer // Allow linking two exactly identical external global variables... 501361e513dSReid Spencer if (SGV->isConstant() != DGV->isConstant()) 502361e513dSReid Spencer return Error(Err, "Global Variable Collision on '" + 503361e513dSReid Spencer ToStr(SGV->getType(), Src) + " %" + SGV->getName() + 504361e513dSReid Spencer "' - Global variables differ in const'ness"); 505361e513dSReid Spencer 506361e513dSReid Spencer if (SGV->getInitializer() != DGV->getInitializer()) 507361e513dSReid Spencer return Error(Err, "Global Variable Collision on '" + 508361e513dSReid Spencer ToStr(SGV->getType(), Src) + " %" + SGV->getName() + 509361e513dSReid Spencer "' - External linkage globals have different initializers"); 510361e513dSReid Spencer 511361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, DGV)); 512361e513dSReid Spencer } else if (SGV->hasAppendingLinkage()) { 513361e513dSReid Spencer // No linking is performed yet. Just insert a new copy of the global, and 514361e513dSReid Spencer // keep track of the fact that it is an appending variable in the 515361e513dSReid Spencer // AppendingVars map. The name is cleared out so that no linkage is 516361e513dSReid Spencer // performed. 517361e513dSReid Spencer GlobalVariable *NewDGV = 518361e513dSReid Spencer new GlobalVariable(SGV->getType()->getElementType(), 519361e513dSReid Spencer SGV->isConstant(), SGV->getLinkage(), /*init*/0, 520361e513dSReid Spencer "", Dest); 521361e513dSReid Spencer 522361e513dSReid Spencer // Make sure to remember this mapping... 523361e513dSReid Spencer ValueMap.insert(std::make_pair(SGV, NewDGV)); 524361e513dSReid Spencer 525361e513dSReid Spencer // Keep track that this is an appending variable... 526361e513dSReid Spencer AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV)); 527361e513dSReid Spencer } else { 528361e513dSReid Spencer assert(0 && "Unknown linkage!"); 529361e513dSReid Spencer } 530361e513dSReid Spencer } 531361e513dSReid Spencer return false; 532361e513dSReid Spencer } 533361e513dSReid Spencer 534361e513dSReid Spencer 535361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all 536361e513dSReid Spencer // globals that may be referenced are in Dest. 537361e513dSReid Spencer // 538361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src, 539361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 540361e513dSReid Spencer std::string *Err) { 541361e513dSReid Spencer 542361e513dSReid Spencer // Loop over all of the globals in the src module, mapping them over as we go 543361e513dSReid Spencer // 544361e513dSReid Spencer for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){ 545361e513dSReid Spencer const GlobalVariable *SGV = I; 546361e513dSReid Spencer 547361e513dSReid Spencer if (SGV->hasInitializer()) { // Only process initialized GV's 548361e513dSReid Spencer // Figure out what the initializer looks like in the dest module... 549361e513dSReid Spencer Constant *SInit = 5507391dde1SChris Lattner cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap)); 551361e513dSReid Spencer 552361e513dSReid Spencer GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]); 553361e513dSReid Spencer if (DGV->hasInitializer()) { 554361e513dSReid Spencer if (SGV->hasExternalLinkage()) { 555361e513dSReid Spencer if (DGV->getInitializer() != SInit) 556361e513dSReid Spencer return Error(Err, "Global Variable Collision on '" + 557361e513dSReid Spencer ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+ 558361e513dSReid Spencer " - Global variables have different initializers"); 559361e513dSReid Spencer } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) { 560361e513dSReid Spencer // Nothing is required, mapped values will take the new global 561361e513dSReid Spencer // automatically. 562361e513dSReid Spencer } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) { 563361e513dSReid Spencer // Nothing is required, mapped values will take the new global 564361e513dSReid Spencer // automatically. 565361e513dSReid Spencer } else if (DGV->hasAppendingLinkage()) { 566361e513dSReid Spencer assert(0 && "Appending linkage unimplemented!"); 567361e513dSReid Spencer } else { 568361e513dSReid Spencer assert(0 && "Unknown linkage!"); 569361e513dSReid Spencer } 570361e513dSReid Spencer } else { 571361e513dSReid Spencer // Copy the initializer over now... 572361e513dSReid Spencer DGV->setInitializer(SInit); 573361e513dSReid Spencer } 574361e513dSReid Spencer } 575361e513dSReid Spencer } 576361e513dSReid Spencer return false; 577361e513dSReid Spencer } 578361e513dSReid Spencer 579361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules, 580361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes 581361e513dSReid Spencer // to the Dest function... 582361e513dSReid Spencer // 583361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src, 584361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 585361e513dSReid Spencer std::map<std::string, GlobalValue*> &GlobalsByName, 586361e513dSReid Spencer std::string *Err) { 587361e513dSReid Spencer SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable(); 588361e513dSReid Spencer 589361e513dSReid Spencer // Loop over all of the functions in the src module, mapping them over as we 590361e513dSReid Spencer // go 591361e513dSReid Spencer // 592361e513dSReid Spencer for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) { 593361e513dSReid Spencer const Function *SF = I; // SrcFunction 594361e513dSReid Spencer Function *DF = 0; 595361e513dSReid Spencer if (SF->hasName() && !SF->hasInternalLinkage()) { 596361e513dSReid Spencer // Check to see if may have to link the function. 597361e513dSReid Spencer if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) { 598361e513dSReid Spencer std::map<std::string, GlobalValue*>::iterator EF = 599361e513dSReid Spencer GlobalsByName.find(SF->getName()); 600361e513dSReid Spencer if (EF != GlobalsByName.end()) 601361e513dSReid Spencer DF = dyn_cast<Function>(EF->second); 602361e513dSReid Spencer if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, "")) 603361e513dSReid Spencer DF = 0; // FIXME: gross. 604361e513dSReid Spencer } 605361e513dSReid Spencer } 606361e513dSReid Spencer 607361e513dSReid Spencer if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) { 608361e513dSReid Spencer // Function does not already exist, simply insert an function signature 609361e513dSReid Spencer // identical to SF into the dest module... 610361e513dSReid Spencer Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(), 611361e513dSReid Spencer SF->getName(), Dest); 612361e513dSReid Spencer 613361e513dSReid Spencer // If the LLVM runtime renamed the function, but it is an externally 614361e513dSReid Spencer // visible symbol, DF must be an existing function with internal linkage. 615361e513dSReid Spencer // Rename it. 616361e513dSReid Spencer if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) 617361e513dSReid Spencer ForceRenaming(NewDF, SF->getName()); 618361e513dSReid Spencer 619361e513dSReid Spencer // ... and remember this mapping... 620361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, NewDF)); 621361e513dSReid Spencer } else if (SF->isExternal()) { 622361e513dSReid Spencer // If SF is external or if both SF & DF are external.. Just link the 623361e513dSReid Spencer // external functions, we aren't adding anything. 624361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 625361e513dSReid Spencer } else if (DF->isExternal()) { // If DF is external but SF is not... 626361e513dSReid Spencer // Link the external functions, update linkage qualifiers 627361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 628361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 629361e513dSReid Spencer 630361e513dSReid Spencer } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) { 631361e513dSReid Spencer // At this point we know that DF has LinkOnce, Weak, or External linkage. 632361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 633361e513dSReid Spencer 634361e513dSReid Spencer // Linkonce+Weak = Weak 635361e513dSReid Spencer if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) 636361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 637361e513dSReid Spencer 638361e513dSReid Spencer } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) { 639361e513dSReid Spencer // At this point we know that SF has LinkOnce or External linkage. 640361e513dSReid Spencer ValueMap.insert(std::make_pair(SF, DF)); 641361e513dSReid Spencer if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage 642361e513dSReid Spencer DF->setLinkage(SF->getLinkage()); 643361e513dSReid Spencer 644361e513dSReid Spencer } else if (SF->getLinkage() != DF->getLinkage()) { 645361e513dSReid Spencer return Error(Err, "Functions named '" + SF->getName() + 646361e513dSReid Spencer "' have different linkage specifiers!"); 647361e513dSReid Spencer } else if (SF->hasExternalLinkage()) { 648361e513dSReid Spencer // The function is defined in both modules!! 649361e513dSReid Spencer return Error(Err, "Function '" + 650361e513dSReid Spencer ToStr(SF->getFunctionType(), Src) + "':\"" + 651361e513dSReid Spencer SF->getName() + "\" - Function is already defined!"); 652361e513dSReid Spencer } else { 653361e513dSReid Spencer assert(0 && "Unknown linkage configuration found!"); 654361e513dSReid Spencer } 655361e513dSReid Spencer } 656361e513dSReid Spencer return false; 657361e513dSReid Spencer } 658361e513dSReid Spencer 659361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and 660361e513dSReid Spencer // fix up references to values. At this point we know that Dest is an external 661361e513dSReid Spencer // function, and that Src is not. 662361e513dSReid Spencer // 6632f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src, 664361e513dSReid Spencer std::map<const Value*, Value*> &GlobalMap, 665361e513dSReid Spencer std::string *Err) { 666361e513dSReid Spencer assert(Src && Dest && Dest->isExternal() && !Src->isExternal()); 667361e513dSReid Spencer 6687391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 669361e513dSReid Spencer Function::aiterator DI = Dest->abegin(); 6702f0557d0SChris Lattner for (Function::aiterator I = Src->abegin(), E = Src->aend(); 671361e513dSReid Spencer I != E; ++I, ++DI) { 672361e513dSReid Spencer DI->setName(I->getName()); // Copy the name information over... 673361e513dSReid Spencer 674361e513dSReid Spencer // Add a mapping to our local map 6757391dde1SChris Lattner GlobalMap.insert(std::make_pair(I, DI)); 676361e513dSReid Spencer } 677361e513dSReid Spencer 6782f0557d0SChris Lattner // Splice the body of the source function into the dest function. 6792f0557d0SChris Lattner Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList()); 680361e513dSReid Spencer 681361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 682361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 683361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 684361e513dSReid Spencer // functions and patch them up to point to the local versions... 685361e513dSReid Spencer // 686361e513dSReid Spencer for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB) 687361e513dSReid Spencer for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 688361e513dSReid Spencer for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 689361e513dSReid Spencer OI != OE; ++OI) 6902f0557d0SChris Lattner if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI)) 6917391dde1SChris Lattner *OI = RemapOperand(*OI, GlobalMap); 6927391dde1SChris Lattner 6937391dde1SChris Lattner // There is no need to map the arguments anymore. 694*f27514dfSChris Lattner for (Function::aiterator I = Src->abegin(), E = Src->aend(); I != E; ++I) 6957391dde1SChris Lattner GlobalMap.erase(I); 696361e513dSReid Spencer 697361e513dSReid Spencer return false; 698361e513dSReid Spencer } 699361e513dSReid Spencer 700361e513dSReid Spencer 701361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the 702361e513dSReid Spencer // source module into the DestModule. This consists basically of copying the 703361e513dSReid Spencer // function over and fixing up references to values. 704361e513dSReid Spencer // 7052f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src, 706361e513dSReid Spencer std::map<const Value*, Value*> &ValueMap, 707361e513dSReid Spencer std::string *Err) { 708361e513dSReid Spencer 709361e513dSReid Spencer // Loop over all of the functions in the src module, mapping them over as we 710361e513dSReid Spencer // go 711361e513dSReid Spencer // 7122f0557d0SChris Lattner for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) { 713361e513dSReid Spencer if (!SF->isExternal()) { // No body if function is external 714361e513dSReid Spencer Function *DF = cast<Function>(ValueMap[SF]); // Destination function 715361e513dSReid Spencer 716361e513dSReid Spencer // DF not external SF external? 717361e513dSReid Spencer if (DF->isExternal()) { 718361e513dSReid Spencer // Only provide the function body if there isn't one already. 719361e513dSReid Spencer if (LinkFunctionBody(DF, SF, ValueMap, Err)) 720361e513dSReid Spencer return true; 721361e513dSReid Spencer } 722361e513dSReid Spencer } 723361e513dSReid Spencer } 724361e513dSReid Spencer return false; 725361e513dSReid Spencer } 726361e513dSReid Spencer 727361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them 728361e513dSReid Spencer // together now. Return true on error. 729361e513dSReid Spencer // 730361e513dSReid Spencer static bool LinkAppendingVars(Module *M, 731361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> &AppendingVars, 732361e513dSReid Spencer std::string *ErrorMsg) { 733361e513dSReid Spencer if (AppendingVars.empty()) return false; // Nothing to do. 734361e513dSReid Spencer 735361e513dSReid Spencer // Loop over the multimap of appending vars, processing any variables with the 736361e513dSReid Spencer // same name, forming a new appending global variable with both of the 737361e513dSReid Spencer // initializers merged together, then rewrite references to the old variables 738361e513dSReid Spencer // and delete them. 739361e513dSReid Spencer // 740361e513dSReid Spencer std::vector<Constant*> Inits; 741361e513dSReid Spencer while (AppendingVars.size() > 1) { 742361e513dSReid Spencer // Get the first two elements in the map... 743361e513dSReid Spencer std::multimap<std::string, 744361e513dSReid Spencer GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++; 745361e513dSReid Spencer 746361e513dSReid Spencer // If the first two elements are for different names, there is no pair... 747361e513dSReid Spencer // Otherwise there is a pair, so link them together... 748361e513dSReid Spencer if (First->first == Second->first) { 749361e513dSReid Spencer GlobalVariable *G1 = First->second, *G2 = Second->second; 750361e513dSReid Spencer const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType()); 751361e513dSReid Spencer const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType()); 752361e513dSReid Spencer 753361e513dSReid Spencer // Check to see that they two arrays agree on type... 754361e513dSReid Spencer if (T1->getElementType() != T2->getElementType()) 755361e513dSReid Spencer return Error(ErrorMsg, 756361e513dSReid Spencer "Appending variables with different element types need to be linked!"); 757361e513dSReid Spencer if (G1->isConstant() != G2->isConstant()) 758361e513dSReid Spencer return Error(ErrorMsg, 759361e513dSReid Spencer "Appending variables linked with different const'ness!"); 760361e513dSReid Spencer 761361e513dSReid Spencer unsigned NewSize = T1->getNumElements() + T2->getNumElements(); 762361e513dSReid Spencer ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize); 763361e513dSReid Spencer 764361e513dSReid Spencer // Create the new global variable... 765361e513dSReid Spencer GlobalVariable *NG = 766361e513dSReid Spencer new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(), 767361e513dSReid Spencer /*init*/0, First->first, M); 768361e513dSReid Spencer 769361e513dSReid Spencer // Merge the initializer... 770361e513dSReid Spencer Inits.reserve(NewSize); 771361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) { 772361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 773361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 774361e513dSReid Spencer } else { 775361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G1->getInitializer())); 776361e513dSReid Spencer Constant *CV = Constant::getNullValue(T1->getElementType()); 777361e513dSReid Spencer for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i) 778361e513dSReid Spencer Inits.push_back(CV); 779361e513dSReid Spencer } 780361e513dSReid Spencer if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) { 781361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 782361e513dSReid Spencer Inits.push_back(I->getOperand(i)); 783361e513dSReid Spencer } else { 784361e513dSReid Spencer assert(isa<ConstantAggregateZero>(G2->getInitializer())); 785361e513dSReid Spencer Constant *CV = Constant::getNullValue(T2->getElementType()); 786361e513dSReid Spencer for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i) 787361e513dSReid Spencer Inits.push_back(CV); 788361e513dSReid Spencer } 789361e513dSReid Spencer NG->setInitializer(ConstantArray::get(NewType, Inits)); 790361e513dSReid Spencer Inits.clear(); 791361e513dSReid Spencer 792361e513dSReid Spencer // Replace any uses of the two global variables with uses of the new 793361e513dSReid Spencer // global... 794361e513dSReid Spencer 795361e513dSReid Spencer // FIXME: This should rewrite simple/straight-forward uses such as 796361e513dSReid Spencer // getelementptr instructions to not use the Cast! 797361e513dSReid Spencer G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType())); 798361e513dSReid Spencer G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType())); 799361e513dSReid Spencer 800361e513dSReid Spencer // Remove the two globals from the module now... 801361e513dSReid Spencer M->getGlobalList().erase(G1); 802361e513dSReid Spencer M->getGlobalList().erase(G2); 803361e513dSReid Spencer 804361e513dSReid Spencer // Put the new global into the AppendingVars map so that we can handle 805361e513dSReid Spencer // linking of more than two vars... 806361e513dSReid Spencer Second->second = NG; 807361e513dSReid Spencer } 808361e513dSReid Spencer AppendingVars.erase(First); 809361e513dSReid Spencer } 810361e513dSReid Spencer 811361e513dSReid Spencer return false; 812361e513dSReid Spencer } 813361e513dSReid Spencer 814361e513dSReid Spencer 815361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting 816361e513dSReid Spencer // left module modified to be the composite of the two input modules. If an 817361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate 818361e513dSReid Spencer // the problem. Upon failure, the Dest module could be in a modified state, and 819361e513dSReid Spencer // shouldn't be relied on to be consistent. 820f2e80844SChris Lattner bool llvm::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) { 821361e513dSReid Spencer assert(Dest != 0 && "Invalid Destination module"); 822361e513dSReid Spencer assert(Src != 0 && "Invalid Source Module"); 823361e513dSReid Spencer 824361e513dSReid Spencer if (Dest->getEndianness() == Module::AnyEndianness) 825361e513dSReid Spencer Dest->setEndianness(Src->getEndianness()); 826361e513dSReid Spencer if (Dest->getPointerSize() == Module::AnyPointerSize) 827361e513dSReid Spencer Dest->setPointerSize(Src->getPointerSize()); 828361e513dSReid Spencer 829361e513dSReid Spencer if (Src->getEndianness() != Module::AnyEndianness && 830361e513dSReid Spencer Dest->getEndianness() != Src->getEndianness()) 831361e513dSReid Spencer std::cerr << "WARNING: Linking two modules of different endianness!\n"; 832361e513dSReid Spencer if (Src->getPointerSize() != Module::AnyPointerSize && 833361e513dSReid Spencer Dest->getPointerSize() != Src->getPointerSize()) 834361e513dSReid Spencer std::cerr << "WARNING: Linking two modules of different pointer size!\n"; 835361e513dSReid Spencer 836361e513dSReid Spencer // Update the destination module's dependent libraries list with the libraries 837361e513dSReid Spencer // from the source module. There's no opportunity for duplicates here as the 838361e513dSReid Spencer // Module ensures that duplicate insertions are discarded. 839361e513dSReid Spencer Module::lib_iterator SI = Src->lib_begin(); 840361e513dSReid Spencer Module::lib_iterator SE = Src->lib_end(); 841361e513dSReid Spencer while ( SI != SE ) { 842361e513dSReid Spencer Dest->addLibrary(*SI); 843361e513dSReid Spencer ++SI; 844361e513dSReid Spencer } 845361e513dSReid Spencer 846361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any 847361e513dSReid Spencer // types are named in the src module that are not named in the Dst module. 848361e513dSReid Spencer // Make sure there are no type name conflicts. 849361e513dSReid Spencer // 850361e513dSReid Spencer if (LinkTypes(Dest, Src, ErrorMsg)) return true; 851361e513dSReid Spencer 852361e513dSReid Spencer // ValueMap - Mapping of values from what they used to be in Src, to what they 853361e513dSReid Spencer // are now in Dest. 854361e513dSReid Spencer // 855361e513dSReid Spencer std::map<const Value*, Value*> ValueMap; 856361e513dSReid Spencer 857361e513dSReid Spencer // AppendingVars - Keep track of global variables in the destination module 858361e513dSReid Spencer // with appending linkage. After the module is linked together, they are 859361e513dSReid Spencer // appended and the module is rewritten. 860361e513dSReid Spencer // 861361e513dSReid Spencer std::multimap<std::string, GlobalVariable *> AppendingVars; 862361e513dSReid Spencer 863361e513dSReid Spencer // GlobalsByName - The LLVM SymbolTable class fights our best efforts at 864361e513dSReid Spencer // linking by separating globals by type. Until PR411 is fixed, we replicate 865361e513dSReid Spencer // it's functionality here. 866361e513dSReid Spencer std::map<std::string, GlobalValue*> GlobalsByName; 867361e513dSReid Spencer 868361e513dSReid Spencer for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I) { 869361e513dSReid Spencer // Add all of the appending globals already in the Dest module to 870361e513dSReid Spencer // AppendingVars. 871361e513dSReid Spencer if (I->hasAppendingLinkage()) 872361e513dSReid Spencer AppendingVars.insert(std::make_pair(I->getName(), I)); 873361e513dSReid Spencer 874361e513dSReid Spencer // Keep track of all globals by name. 875361e513dSReid Spencer if (!I->hasInternalLinkage() && I->hasName()) 876361e513dSReid Spencer GlobalsByName[I->getName()] = I; 877361e513dSReid Spencer } 878361e513dSReid Spencer 879361e513dSReid Spencer // Keep track of all globals by name. 880361e513dSReid Spencer for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I) 881361e513dSReid Spencer if (!I->hasInternalLinkage() && I->hasName()) 882361e513dSReid Spencer GlobalsByName[I->getName()] = I; 883361e513dSReid Spencer 884361e513dSReid Spencer // Insert all of the globals in src into the Dest module... without linking 885361e513dSReid Spencer // initializers (which could refer to functions not yet mapped over). 886361e513dSReid Spencer // 887361e513dSReid Spencer if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg)) 888361e513dSReid Spencer return true; 889361e513dSReid Spencer 890361e513dSReid Spencer // Link the functions together between the two modules, without doing function 891361e513dSReid Spencer // bodies... this just adds external function prototypes to the Dest 892361e513dSReid Spencer // function... We do this so that when we begin processing function bodies, 893361e513dSReid Spencer // all of the global values that may be referenced are available in our 894361e513dSReid Spencer // ValueMap. 895361e513dSReid Spencer // 896361e513dSReid Spencer if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg)) 897361e513dSReid Spencer return true; 898361e513dSReid Spencer 899361e513dSReid Spencer // Update the initializers in the Dest module now that all globals that may 900361e513dSReid Spencer // be referenced are in Dest. 901361e513dSReid Spencer // 902361e513dSReid Spencer if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true; 903361e513dSReid Spencer 904361e513dSReid Spencer // Link in the function bodies that are defined in the source module into the 905361e513dSReid Spencer // DestModule. This consists basically of copying the function over and 906361e513dSReid Spencer // fixing up references to values. 907361e513dSReid Spencer // 908361e513dSReid Spencer if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true; 909361e513dSReid Spencer 910361e513dSReid Spencer // If there were any appending global variables, link them together now. 911361e513dSReid Spencer // 912361e513dSReid Spencer if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true; 913361e513dSReid Spencer 914361e513dSReid Spencer // If the source library's module id is in the dependent library list of the 915361e513dSReid Spencer // destination library, remove it since that module is now linked in. 916361e513dSReid Spencer sys::Path modId; 917361e513dSReid Spencer modId.setFile(Src->getModuleIdentifier()); 918361e513dSReid Spencer if (!modId.isEmpty()) 919361e513dSReid Spencer Dest->removeLibrary(modId.getBasename()); 920361e513dSReid Spencer 921361e513dSReid Spencer return false; 922361e513dSReid Spencer } 923361e513dSReid Spencer 924361e513dSReid Spencer // vim: sw=2 925