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