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