1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===// 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 #include "llvm/Linker/IRMover.h" 11 #include "LinkDiagnosticInfo.h" 12 #include "llvm/ADT/SetVector.h" 13 #include "llvm/ADT/SmallString.h" 14 #include "llvm/ADT/Triple.h" 15 #include "llvm/IR/Constants.h" 16 #include "llvm/IR/DebugInfo.h" 17 #include "llvm/IR/DiagnosticPrinter.h" 18 #include "llvm/IR/GVMaterializer.h" 19 #include "llvm/IR/Intrinsics.h" 20 #include "llvm/IR/TypeFinder.h" 21 #include "llvm/Support/Error.h" 22 #include "llvm/Transforms/Utils/Cloning.h" 23 #include <utility> 24 using namespace llvm; 25 26 //===----------------------------------------------------------------------===// 27 // TypeMap implementation. 28 //===----------------------------------------------------------------------===// 29 30 namespace { 31 class TypeMapTy : public ValueMapTypeRemapper { 32 /// This is a mapping from a source type to a destination type to use. 33 DenseMap<Type *, Type *> MappedTypes; 34 35 /// When checking to see if two subgraphs are isomorphic, we speculatively 36 /// add types to MappedTypes, but keep track of them here in case we need to 37 /// roll back. 38 SmallVector<Type *, 16> SpeculativeTypes; 39 40 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes; 41 42 /// This is a list of non-opaque structs in the source module that are mapped 43 /// to an opaque struct in the destination module. 44 SmallVector<StructType *, 16> SrcDefinitionsToResolve; 45 46 /// This is the set of opaque types in the destination modules who are 47 /// getting a body from the source module. 48 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes; 49 50 public: 51 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet) 52 : DstStructTypesSet(DstStructTypesSet) {} 53 54 IRMover::IdentifiedStructTypeSet &DstStructTypesSet; 55 /// Indicate that the specified type in the destination module is conceptually 56 /// equivalent to the specified type in the source module. 57 void addTypeMapping(Type *DstTy, Type *SrcTy); 58 59 /// Produce a body for an opaque type in the dest module from a type 60 /// definition in the source module. 61 void linkDefinedTypeBodies(); 62 63 /// Return the mapped type to use for the specified input type from the 64 /// source module. 65 Type *get(Type *SrcTy); 66 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited); 67 68 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes); 69 70 FunctionType *get(FunctionType *T) { 71 return cast<FunctionType>(get((Type *)T)); 72 } 73 74 private: 75 Type *remapType(Type *SrcTy) override { return get(SrcTy); } 76 77 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 78 }; 79 } 80 81 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 82 assert(SpeculativeTypes.empty()); 83 assert(SpeculativeDstOpaqueTypes.empty()); 84 85 // Check to see if these types are recursively isomorphic and establish a 86 // mapping between them if so. 87 if (!areTypesIsomorphic(DstTy, SrcTy)) { 88 // Oops, they aren't isomorphic. Just discard this request by rolling out 89 // any speculative mappings we've established. 90 for (Type *Ty : SpeculativeTypes) 91 MappedTypes.erase(Ty); 92 93 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - 94 SpeculativeDstOpaqueTypes.size()); 95 for (StructType *Ty : SpeculativeDstOpaqueTypes) 96 DstResolvedOpaqueTypes.erase(Ty); 97 } else { 98 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy 99 // and all its descendants to lower amount of renaming in LLVM context 100 // Renaming occurs because we load all source modules to the same context 101 // and declaration with existing name gets renamed (i.e Foo -> Foo.42). 102 // As a result we may get several different types in the destination 103 // module, which are in fact the same. 104 for (Type *Ty : SpeculativeTypes) 105 if (auto *STy = dyn_cast<StructType>(Ty)) 106 if (STy->hasName()) 107 STy->setName(""); 108 } 109 SpeculativeTypes.clear(); 110 SpeculativeDstOpaqueTypes.clear(); 111 } 112 113 /// Recursively walk this pair of types, returning true if they are isomorphic, 114 /// false if they are not. 115 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 116 // Two types with differing kinds are clearly not isomorphic. 117 if (DstTy->getTypeID() != SrcTy->getTypeID()) 118 return false; 119 120 // If we have an entry in the MappedTypes table, then we have our answer. 121 Type *&Entry = MappedTypes[SrcTy]; 122 if (Entry) 123 return Entry == DstTy; 124 125 // Two identical types are clearly isomorphic. Remember this 126 // non-speculatively. 127 if (DstTy == SrcTy) { 128 Entry = DstTy; 129 return true; 130 } 131 132 // Okay, we have two types with identical kinds that we haven't seen before. 133 134 // If this is an opaque struct type, special case it. 135 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 136 // Mapping an opaque type to any struct, just keep the dest struct. 137 if (SSTy->isOpaque()) { 138 Entry = DstTy; 139 SpeculativeTypes.push_back(SrcTy); 140 return true; 141 } 142 143 // Mapping a non-opaque source type to an opaque dest. If this is the first 144 // type that we're mapping onto this destination type then we succeed. Keep 145 // the dest, but fill it in later. If this is the second (different) type 146 // that we're trying to map onto the same opaque type then we fail. 147 if (cast<StructType>(DstTy)->isOpaque()) { 148 // We can only map one source type onto the opaque destination type. 149 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 150 return false; 151 SrcDefinitionsToResolve.push_back(SSTy); 152 SpeculativeTypes.push_back(SrcTy); 153 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); 154 Entry = DstTy; 155 return true; 156 } 157 } 158 159 // If the number of subtypes disagree between the two types, then we fail. 160 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 161 return false; 162 163 // Fail if any of the extra properties (e.g. array size) of the type disagree. 164 if (isa<IntegerType>(DstTy)) 165 return false; // bitwidth disagrees. 166 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 167 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 168 return false; 169 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 170 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 171 return false; 172 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 173 StructType *SSTy = cast<StructType>(SrcTy); 174 if (DSTy->isLiteral() != SSTy->isLiteral() || 175 DSTy->isPacked() != SSTy->isPacked()) 176 return false; 177 } else if (auto *DSeqTy = dyn_cast<SequentialType>(DstTy)) { 178 if (DSeqTy->getNumElements() != 179 cast<SequentialType>(SrcTy)->getNumElements()) 180 return false; 181 } 182 183 // Otherwise, we speculate that these two types will line up and recursively 184 // check the subelements. 185 Entry = DstTy; 186 SpeculativeTypes.push_back(SrcTy); 187 188 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 189 if (!areTypesIsomorphic(DstTy->getContainedType(I), 190 SrcTy->getContainedType(I))) 191 return false; 192 193 // If everything seems to have lined up, then everything is great. 194 return true; 195 } 196 197 void TypeMapTy::linkDefinedTypeBodies() { 198 SmallVector<Type *, 16> Elements; 199 for (StructType *SrcSTy : SrcDefinitionsToResolve) { 200 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 201 assert(DstSTy->isOpaque()); 202 203 // Map the body of the source type over to a new body for the dest type. 204 Elements.resize(SrcSTy->getNumElements()); 205 for (unsigned I = 0, E = Elements.size(); I != E; ++I) 206 Elements[I] = get(SrcSTy->getElementType(I)); 207 208 DstSTy->setBody(Elements, SrcSTy->isPacked()); 209 DstStructTypesSet.switchToNonOpaque(DstSTy); 210 } 211 SrcDefinitionsToResolve.clear(); 212 DstResolvedOpaqueTypes.clear(); 213 } 214 215 void TypeMapTy::finishType(StructType *DTy, StructType *STy, 216 ArrayRef<Type *> ETypes) { 217 DTy->setBody(ETypes, STy->isPacked()); 218 219 // Steal STy's name. 220 if (STy->hasName()) { 221 SmallString<16> TmpName = STy->getName(); 222 STy->setName(""); 223 DTy->setName(TmpName); 224 } 225 226 DstStructTypesSet.addNonOpaque(DTy); 227 } 228 229 Type *TypeMapTy::get(Type *Ty) { 230 SmallPtrSet<StructType *, 8> Visited; 231 return get(Ty, Visited); 232 } 233 234 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) { 235 // If we already have an entry for this type, return it. 236 Type **Entry = &MappedTypes[Ty]; 237 if (*Entry) 238 return *Entry; 239 240 // These are types that LLVM itself will unique. 241 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral(); 242 243 if (!IsUniqued) { 244 StructType *STy = cast<StructType>(Ty); 245 // This is actually a type from the destination module, this can be reached 246 // when this type is loaded in another module, added to DstStructTypesSet, 247 // and then we reach the same type in another module where it has not been 248 // added to MappedTypes. (PR37684) 249 if (STy->getContext().isODRUniquingDebugTypes() && !STy->isOpaque() && 250 DstStructTypesSet.hasType(STy)) 251 return *Entry = STy; 252 253 #ifndef NDEBUG 254 for (auto &Pair : MappedTypes) { 255 assert(!(Pair.first != Ty && Pair.second == Ty) && 256 "mapping to a source type"); 257 } 258 #endif 259 260 if (!Visited.insert(STy).second) { 261 StructType *DTy = StructType::create(Ty->getContext()); 262 return *Entry = DTy; 263 } 264 } 265 266 // If this is not a recursive type, then just map all of the elements and 267 // then rebuild the type from inside out. 268 SmallVector<Type *, 4> ElementTypes; 269 270 // If there are no element types to map, then the type is itself. This is 271 // true for the anonymous {} struct, things like 'float', integers, etc. 272 if (Ty->getNumContainedTypes() == 0 && IsUniqued) 273 return *Entry = Ty; 274 275 // Remap all of the elements, keeping track of whether any of them change. 276 bool AnyChange = false; 277 ElementTypes.resize(Ty->getNumContainedTypes()); 278 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 279 ElementTypes[I] = get(Ty->getContainedType(I), Visited); 280 AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 281 } 282 283 // If we found our type while recursively processing stuff, just use it. 284 Entry = &MappedTypes[Ty]; 285 if (*Entry) { 286 if (auto *DTy = dyn_cast<StructType>(*Entry)) { 287 if (DTy->isOpaque()) { 288 auto *STy = cast<StructType>(Ty); 289 finishType(DTy, STy, ElementTypes); 290 } 291 } 292 return *Entry; 293 } 294 295 // If all of the element types mapped directly over and the type is not 296 // a named struct, then the type is usable as-is. 297 if (!AnyChange && IsUniqued) 298 return *Entry = Ty; 299 300 // Otherwise, rebuild a modified type. 301 switch (Ty->getTypeID()) { 302 default: 303 llvm_unreachable("unknown derived type to remap"); 304 case Type::ArrayTyID: 305 return *Entry = ArrayType::get(ElementTypes[0], 306 cast<ArrayType>(Ty)->getNumElements()); 307 case Type::VectorTyID: 308 return *Entry = VectorType::get(ElementTypes[0], 309 cast<VectorType>(Ty)->getNumElements()); 310 case Type::PointerTyID: 311 return *Entry = PointerType::get(ElementTypes[0], 312 cast<PointerType>(Ty)->getAddressSpace()); 313 case Type::FunctionTyID: 314 return *Entry = FunctionType::get(ElementTypes[0], 315 makeArrayRef(ElementTypes).slice(1), 316 cast<FunctionType>(Ty)->isVarArg()); 317 case Type::StructTyID: { 318 auto *STy = cast<StructType>(Ty); 319 bool IsPacked = STy->isPacked(); 320 if (IsUniqued) 321 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked); 322 323 // If the type is opaque, we can just use it directly. 324 if (STy->isOpaque()) { 325 DstStructTypesSet.addOpaque(STy); 326 return *Entry = Ty; 327 } 328 329 if (StructType *OldT = 330 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) { 331 STy->setName(""); 332 return *Entry = OldT; 333 } 334 335 if (!AnyChange) { 336 DstStructTypesSet.addNonOpaque(STy); 337 return *Entry = Ty; 338 } 339 340 StructType *DTy = StructType::create(Ty->getContext()); 341 finishType(DTy, STy, ElementTypes); 342 return *Entry = DTy; 343 } 344 } 345 } 346 347 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 348 const Twine &Msg) 349 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 350 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 351 352 //===----------------------------------------------------------------------===// 353 // IRLinker implementation. 354 //===----------------------------------------------------------------------===// 355 356 namespace { 357 class IRLinker; 358 359 /// Creates prototypes for functions that are lazily linked on the fly. This 360 /// speeds up linking for modules with many/ lazily linked functions of which 361 /// few get used. 362 class GlobalValueMaterializer final : public ValueMaterializer { 363 IRLinker &TheIRLinker; 364 365 public: 366 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} 367 Value *materialize(Value *V) override; 368 }; 369 370 class LocalValueMaterializer final : public ValueMaterializer { 371 IRLinker &TheIRLinker; 372 373 public: 374 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} 375 Value *materialize(Value *V) override; 376 }; 377 378 /// Type of the Metadata map in \a ValueToValueMapTy. 379 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT; 380 381 /// This is responsible for keeping track of the state used for moving data 382 /// from SrcM to DstM. 383 class IRLinker { 384 Module &DstM; 385 std::unique_ptr<Module> SrcM; 386 387 /// See IRMover::move(). 388 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor; 389 390 TypeMapTy TypeMap; 391 GlobalValueMaterializer GValMaterializer; 392 LocalValueMaterializer LValMaterializer; 393 394 /// A metadata map that's shared between IRLinker instances. 395 MDMapT &SharedMDs; 396 397 /// Mapping of values from what they used to be in Src, to what they are now 398 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 399 /// due to the use of Value handles which the Linker doesn't actually need, 400 /// but this allows us to reuse the ValueMapper code. 401 ValueToValueMapTy ValueMap; 402 ValueToValueMapTy AliasValueMap; 403 404 DenseSet<GlobalValue *> ValuesToLink; 405 std::vector<GlobalValue *> Worklist; 406 407 void maybeAdd(GlobalValue *GV) { 408 if (ValuesToLink.insert(GV).second) 409 Worklist.push_back(GV); 410 } 411 412 /// Whether we are importing globals for ThinLTO, as opposed to linking the 413 /// source module. If this flag is set, it means that we can rely on some 414 /// other object file to define any non-GlobalValue entities defined by the 415 /// source module. This currently causes us to not link retained types in 416 /// debug info metadata and module inline asm. 417 bool IsPerformingImport; 418 419 /// Set to true when all global value body linking is complete (including 420 /// lazy linking). Used to prevent metadata linking from creating new 421 /// references. 422 bool DoneLinkingBodies = false; 423 424 /// The Error encountered during materialization. We use an Optional here to 425 /// avoid needing to manage an unconsumed success value. 426 Optional<Error> FoundError; 427 void setError(Error E) { 428 if (E) 429 FoundError = std::move(E); 430 } 431 432 /// Most of the errors produced by this module are inconvertible StringErrors. 433 /// This convenience function lets us return one of those more easily. 434 Error stringErr(const Twine &T) { 435 return make_error<StringError>(T, inconvertibleErrorCode()); 436 } 437 438 /// Entry point for mapping values and alternate context for mapping aliases. 439 ValueMapper Mapper; 440 unsigned AliasMCID; 441 442 /// Handles cloning of a global values from the source module into 443 /// the destination module, including setting the attributes and visibility. 444 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition); 445 446 void emitWarning(const Twine &Message) { 447 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message)); 448 } 449 450 /// Given a global in the source module, return the global in the 451 /// destination module that is being linked to, if any. 452 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 453 // If the source has no name it can't link. If it has local linkage, 454 // there is no name match-up going on. 455 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 456 return nullptr; 457 458 // Otherwise see if we have a match in the destination module's symtab. 459 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName()); 460 if (!DGV) 461 return nullptr; 462 463 // If we found a global with the same name in the dest module, but it has 464 // internal linkage, we are really not doing any linkage here. 465 if (DGV->hasLocalLinkage()) 466 return nullptr; 467 468 // Otherwise, we do in fact link to the destination global. 469 return DGV; 470 } 471 472 void computeTypeMapping(); 473 474 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV, 475 const GlobalVariable *SrcGV); 476 477 /// Given the GlobaValue \p SGV in the source module, and the matching 478 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV 479 /// into the destination module. 480 /// 481 /// Note this code may call the client-provided \p AddLazyFor. 482 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV); 483 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias); 484 485 Error linkModuleFlagsMetadata(); 486 487 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src); 488 Error linkFunctionBody(Function &Dst, Function &Src); 489 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); 490 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src); 491 492 /// Functions that take care of cloning a specific global value type 493 /// into the destination module. 494 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar); 495 Function *copyFunctionProto(const Function *SF); 496 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA); 497 498 /// When importing for ThinLTO, prevent importing of types listed on 499 /// the DICompileUnit that we don't need a copy of in the importing 500 /// module. 501 void prepareCompileUnitsForImport(); 502 void linkNamedMDNodes(); 503 504 public: 505 IRLinker(Module &DstM, MDMapT &SharedMDs, 506 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM, 507 ArrayRef<GlobalValue *> ValuesToLink, 508 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor, 509 bool IsPerformingImport) 510 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)), 511 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this), 512 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport), 513 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap, 514 &GValMaterializer), 515 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap, 516 &LValMaterializer)) { 517 ValueMap.getMDMap() = std::move(SharedMDs); 518 for (GlobalValue *GV : ValuesToLink) 519 maybeAdd(GV); 520 if (IsPerformingImport) 521 prepareCompileUnitsForImport(); 522 } 523 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); } 524 525 Error run(); 526 Value *materialize(Value *V, bool ForAlias); 527 }; 528 } 529 530 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 531 /// table. This is good for all clients except for us. Go through the trouble 532 /// to force this back. 533 static void forceRenaming(GlobalValue *GV, StringRef Name) { 534 // If the global doesn't force its name or if it already has the right name, 535 // there is nothing for us to do. 536 if (GV->hasLocalLinkage() || GV->getName() == Name) 537 return; 538 539 Module *M = GV->getParent(); 540 541 // If there is a conflict, rename the conflict. 542 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 543 GV->takeName(ConflictGV); 544 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 545 assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 546 } else { 547 GV->setName(Name); // Force the name back 548 } 549 } 550 551 Value *GlobalValueMaterializer::materialize(Value *SGV) { 552 return TheIRLinker.materialize(SGV, false); 553 } 554 555 Value *LocalValueMaterializer::materialize(Value *SGV) { 556 return TheIRLinker.materialize(SGV, true); 557 } 558 559 Value *IRLinker::materialize(Value *V, bool ForAlias) { 560 auto *SGV = dyn_cast<GlobalValue>(V); 561 if (!SGV) 562 return nullptr; 563 564 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias); 565 if (!NewProto) { 566 setError(NewProto.takeError()); 567 return nullptr; 568 } 569 if (!*NewProto) 570 return nullptr; 571 572 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto); 573 if (!New) 574 return *NewProto; 575 576 // If we already created the body, just return. 577 if (auto *F = dyn_cast<Function>(New)) { 578 if (!F->isDeclaration()) 579 return New; 580 } else if (auto *V = dyn_cast<GlobalVariable>(New)) { 581 if (V->hasInitializer() || V->hasAppendingLinkage()) 582 return New; 583 } else { 584 auto *A = cast<GlobalAlias>(New); 585 if (A->getAliasee()) 586 return New; 587 } 588 589 // When linking a global for an alias, it will always be linked. However we 590 // need to check if it was not already scheduled to satisfy a reference from a 591 // regular global value initializer. We know if it has been schedule if the 592 // "New" GlobalValue that is mapped here for the alias is the same as the one 593 // already mapped. If there is an entry in the ValueMap but the value is 594 // different, it means that the value already had a definition in the 595 // destination module (linkonce for instance), but we need a new definition 596 // for the alias ("New" will be different. 597 if (ForAlias && ValueMap.lookup(SGV) == New) 598 return New; 599 600 if (ForAlias || shouldLink(New, *SGV)) 601 setError(linkGlobalValueBody(*New, *SGV)); 602 603 return New; 604 } 605 606 /// Loop through the global variables in the src module and merge them into the 607 /// dest module. 608 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { 609 // No linking to be performed or linking from the source: simply create an 610 // identical version of the symbol over in the dest module... the 611 // initializer will be filled in later by LinkGlobalInits. 612 GlobalVariable *NewDGV = 613 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()), 614 SGVar->isConstant(), GlobalValue::ExternalLinkage, 615 /*init*/ nullptr, SGVar->getName(), 616 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 617 SGVar->getType()->getAddressSpace()); 618 NewDGV->setAlignment(SGVar->getAlignment()); 619 NewDGV->copyAttributesFrom(SGVar); 620 return NewDGV; 621 } 622 623 /// Link the function in the source module into the destination module if 624 /// needed, setting up mapping information. 625 Function *IRLinker::copyFunctionProto(const Function *SF) { 626 // If there is no linkage to be performed or we are linking from the source, 627 // bring SF over. 628 auto *F = 629 Function::Create(TypeMap.get(SF->getFunctionType()), 630 GlobalValue::ExternalLinkage, SF->getName(), &DstM); 631 F->copyAttributesFrom(SF); 632 return F; 633 } 634 635 /// Set up prototypes for any aliases that come over from the source module. 636 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) { 637 // If there is no linkage to be performed or we're linking from the source, 638 // bring over SGA. 639 auto *Ty = TypeMap.get(SGA->getValueType()); 640 auto *GA = 641 GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), 642 GlobalValue::ExternalLinkage, SGA->getName(), &DstM); 643 GA->copyAttributesFrom(SGA); 644 return GA; 645 } 646 647 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, 648 bool ForDefinition) { 649 GlobalValue *NewGV; 650 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { 651 NewGV = copyGlobalVariableProto(SGVar); 652 } else if (auto *SF = dyn_cast<Function>(SGV)) { 653 NewGV = copyFunctionProto(SF); 654 } else { 655 if (ForDefinition) 656 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV)); 657 else if (SGV->getValueType()->isFunctionTy()) 658 NewGV = 659 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())), 660 GlobalValue::ExternalLinkage, SGV->getName(), &DstM); 661 else 662 NewGV = new GlobalVariable( 663 DstM, TypeMap.get(SGV->getValueType()), 664 /*isConstant*/ false, GlobalValue::ExternalLinkage, 665 /*init*/ nullptr, SGV->getName(), 666 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(), 667 SGV->getType()->getAddressSpace()); 668 } 669 670 if (ForDefinition) 671 NewGV->setLinkage(SGV->getLinkage()); 672 else if (SGV->hasExternalWeakLinkage()) 673 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage); 674 675 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 676 // Metadata for global variables and function declarations is copied eagerly. 677 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) 678 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0); 679 } 680 681 // Remove these copied constants in case this stays a declaration, since 682 // they point to the source module. If the def is linked the values will 683 // be mapped in during linkFunctionBody. 684 if (auto *NewF = dyn_cast<Function>(NewGV)) { 685 NewF->setPersonalityFn(nullptr); 686 NewF->setPrefixData(nullptr); 687 NewF->setPrologueData(nullptr); 688 } 689 690 return NewGV; 691 } 692 693 static StringRef getTypeNamePrefix(StringRef Name) { 694 size_t DotPos = Name.rfind('.'); 695 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' || 696 !isdigit(static_cast<unsigned char>(Name[DotPos + 1]))) 697 ? Name 698 : Name.substr(0, DotPos); 699 } 700 701 /// Loop over all of the linked values to compute type mappings. For example, 702 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 703 /// types 'Foo' but one got renamed when the module was loaded into the same 704 /// LLVMContext. 705 void IRLinker::computeTypeMapping() { 706 for (GlobalValue &SGV : SrcM->globals()) { 707 GlobalValue *DGV = getLinkedToGlobal(&SGV); 708 if (!DGV) 709 continue; 710 711 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 712 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 713 continue; 714 } 715 716 // Unify the element type of appending arrays. 717 ArrayType *DAT = cast<ArrayType>(DGV->getValueType()); 718 ArrayType *SAT = cast<ArrayType>(SGV.getValueType()); 719 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 720 } 721 722 for (GlobalValue &SGV : *SrcM) 723 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 724 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 725 726 for (GlobalValue &SGV : SrcM->aliases()) 727 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 728 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 729 730 // Incorporate types by name, scanning all the types in the source module. 731 // At this point, the destination module may have a type "%foo = { i32 }" for 732 // example. When the source module got loaded into the same LLVMContext, if 733 // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 734 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); 735 for (StructType *ST : Types) { 736 if (!ST->hasName()) 737 continue; 738 739 if (TypeMap.DstStructTypesSet.hasType(ST)) { 740 // This is actually a type from the destination module. 741 // getIdentifiedStructTypes() can have found it by walking debug info 742 // metadata nodes, some of which get linked by name when ODR Type Uniquing 743 // is enabled on the Context, from the source to the destination module. 744 continue; 745 } 746 747 auto STTypePrefix = getTypeNamePrefix(ST->getName()); 748 if (STTypePrefix.size()== ST->getName().size()) 749 continue; 750 751 // Check to see if the destination module has a struct with the prefix name. 752 StructType *DST = DstM.getTypeByName(STTypePrefix); 753 if (!DST) 754 continue; 755 756 // Don't use it if this actually came from the source module. They're in 757 // the same LLVMContext after all. Also don't use it unless the type is 758 // actually used in the destination module. This can happen in situations 759 // like this: 760 // 761 // Module A Module B 762 // -------- -------- 763 // %Z = type { %A } %B = type { %C.1 } 764 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 765 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 766 // %C = type { i8* } %B.3 = type { %C.1 } 767 // 768 // When we link Module B with Module A, the '%B' in Module B is 769 // used. However, that would then use '%C.1'. But when we process '%C.1', 770 // we prefer to take the '%C' version. So we are then left with both 771 // '%C.1' and '%C' being used for the same types. This leads to some 772 // variables using one type and some using the other. 773 if (TypeMap.DstStructTypesSet.hasType(DST)) 774 TypeMap.addTypeMapping(DST, ST); 775 } 776 777 // Now that we have discovered all of the type equivalences, get a body for 778 // any 'opaque' types in the dest module that are now resolved. 779 TypeMap.linkDefinedTypeBodies(); 780 } 781 782 static void getArrayElements(const Constant *C, 783 SmallVectorImpl<Constant *> &Dest) { 784 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 785 786 for (unsigned i = 0; i != NumElements; ++i) 787 Dest.push_back(C->getAggregateElement(i)); 788 } 789 790 /// If there were any appending global variables, link them together now. 791 Expected<Constant *> 792 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV, 793 const GlobalVariable *SrcGV) { 794 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType())) 795 ->getElementType(); 796 797 // FIXME: This upgrade is done during linking to support the C API. Once the 798 // old form is deprecated, we should move this upgrade to 799 // llvm::UpgradeGlobalVariable() and simplify the logic here and in 800 // Mapper::mapAppendingVariable() in ValueMapper.cpp. 801 StringRef Name = SrcGV->getName(); 802 bool IsNewStructor = false; 803 bool IsOldStructor = false; 804 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") { 805 if (cast<StructType>(EltTy)->getNumElements() == 3) 806 IsNewStructor = true; 807 else 808 IsOldStructor = true; 809 } 810 811 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo(); 812 if (IsOldStructor) { 813 auto &ST = *cast<StructType>(EltTy); 814 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy}; 815 EltTy = StructType::get(SrcGV->getContext(), Tys, false); 816 } 817 818 uint64_t DstNumElements = 0; 819 if (DstGV) { 820 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType()); 821 DstNumElements = DstTy->getNumElements(); 822 823 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 824 return stringErr( 825 "Linking globals named '" + SrcGV->getName() + 826 "': can only link appending global with another appending " 827 "global!"); 828 829 // Check to see that they two arrays agree on type. 830 if (EltTy != DstTy->getElementType()) 831 return stringErr("Appending variables with different element types!"); 832 if (DstGV->isConstant() != SrcGV->isConstant()) 833 return stringErr("Appending variables linked with different const'ness!"); 834 835 if (DstGV->getAlignment() != SrcGV->getAlignment()) 836 return stringErr( 837 "Appending variables with different alignment need to be linked!"); 838 839 if (DstGV->getVisibility() != SrcGV->getVisibility()) 840 return stringErr( 841 "Appending variables with different visibility need to be linked!"); 842 843 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr()) 844 return stringErr( 845 "Appending variables with different unnamed_addr need to be linked!"); 846 847 if (DstGV->getSection() != SrcGV->getSection()) 848 return stringErr( 849 "Appending variables with different section name need to be linked!"); 850 } 851 852 SmallVector<Constant *, 16> SrcElements; 853 getArrayElements(SrcGV->getInitializer(), SrcElements); 854 855 if (IsNewStructor) { 856 auto It = remove_if(SrcElements, [this](Constant *E) { 857 auto *Key = 858 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts()); 859 if (!Key) 860 return false; 861 GlobalValue *DGV = getLinkedToGlobal(Key); 862 return !shouldLink(DGV, *Key); 863 }); 864 SrcElements.erase(It, SrcElements.end()); 865 } 866 uint64_t NewSize = DstNumElements + SrcElements.size(); 867 ArrayType *NewType = ArrayType::get(EltTy, NewSize); 868 869 // Create the new global variable. 870 GlobalVariable *NG = new GlobalVariable( 871 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(), 872 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(), 873 SrcGV->getType()->getAddressSpace()); 874 875 NG->copyAttributesFrom(SrcGV); 876 forceRenaming(NG, SrcGV->getName()); 877 878 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 879 880 Mapper.scheduleMapAppendingVariable(*NG, 881 DstGV ? DstGV->getInitializer() : nullptr, 882 IsOldStructor, SrcElements); 883 884 // Replace any uses of the two global variables with uses of the new 885 // global. 886 if (DstGV) { 887 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 888 DstGV->eraseFromParent(); 889 } 890 891 return Ret; 892 } 893 894 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) { 895 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage()) 896 return true; 897 898 if (DGV && !DGV->isDeclarationForLinker()) 899 return false; 900 901 if (SGV.isDeclaration() || DoneLinkingBodies) 902 return false; 903 904 // Callback to the client to give a chance to lazily add the Global to the 905 // list of value to link. 906 bool LazilyAdded = false; 907 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) { 908 maybeAdd(&GV); 909 LazilyAdded = true; 910 }); 911 return LazilyAdded; 912 } 913 914 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV, 915 bool ForAlias) { 916 GlobalValue *DGV = getLinkedToGlobal(SGV); 917 918 bool ShouldLink = shouldLink(DGV, *SGV); 919 920 // just missing from map 921 if (ShouldLink) { 922 auto I = ValueMap.find(SGV); 923 if (I != ValueMap.end()) 924 return cast<Constant>(I->second); 925 926 I = AliasValueMap.find(SGV); 927 if (I != AliasValueMap.end()) 928 return cast<Constant>(I->second); 929 } 930 931 if (!ShouldLink && ForAlias) 932 DGV = nullptr; 933 934 // Handle the ultra special appending linkage case first. 935 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage()); 936 if (SGV->hasAppendingLinkage()) 937 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV), 938 cast<GlobalVariable>(SGV)); 939 940 GlobalValue *NewGV; 941 if (DGV && !ShouldLink) { 942 NewGV = DGV; 943 } else { 944 // If we are done linking global value bodies (i.e. we are performing 945 // metadata linking), don't link in the global value due to this 946 // reference, simply map it to null. 947 if (DoneLinkingBodies) 948 return nullptr; 949 950 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForAlias); 951 if (ShouldLink || !ForAlias) 952 forceRenaming(NewGV, SGV->getName()); 953 } 954 955 // Overloaded intrinsics have overloaded types names as part of their 956 // names. If we renamed overloaded types we should rename the intrinsic 957 // as well. 958 if (Function *F = dyn_cast<Function>(NewGV)) 959 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) 960 NewGV = Remangled.getValue(); 961 962 if (ShouldLink || ForAlias) { 963 if (const Comdat *SC = SGV->getComdat()) { 964 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) { 965 Comdat *DC = DstM.getOrInsertComdat(SC->getName()); 966 DC->setSelectionKind(SC->getSelectionKind()); 967 GO->setComdat(DC); 968 } 969 } 970 } 971 972 if (!ShouldLink && ForAlias) 973 NewGV->setLinkage(GlobalValue::InternalLinkage); 974 975 Constant *C = NewGV; 976 // Only create a bitcast if necessary. In particular, with 977 // DebugTypeODRUniquing we may reach metadata in the destination module 978 // containing a GV from the source module, in which case SGV will be 979 // the same as DGV and NewGV, and TypeMap.get() will assert since it 980 // assumes it is being invoked on a type in the source module. 981 if (DGV && NewGV != SGV) 982 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType())); 983 984 if (DGV && NewGV != DGV) { 985 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); 986 DGV->eraseFromParent(); 987 } 988 989 return C; 990 } 991 992 /// Update the initializers in the Dest module now that all globals that may be 993 /// referenced are in Dest. 994 void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) { 995 // Figure out what the initializer looks like in the dest module. 996 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer()); 997 } 998 999 /// Copy the source function over into the dest function and fix up references 1000 /// to values. At this point we know that Dest is an external function, and 1001 /// that Src is not. 1002 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) { 1003 assert(Dst.isDeclaration() && !Src.isDeclaration()); 1004 1005 // Materialize if needed. 1006 if (Error Err = Src.materialize()) 1007 return Err; 1008 1009 // Link in the operands without remapping. 1010 if (Src.hasPrefixData()) 1011 Dst.setPrefixData(Src.getPrefixData()); 1012 if (Src.hasPrologueData()) 1013 Dst.setPrologueData(Src.getPrologueData()); 1014 if (Src.hasPersonalityFn()) 1015 Dst.setPersonalityFn(Src.getPersonalityFn()); 1016 1017 // Copy over the metadata attachments without remapping. 1018 Dst.copyMetadata(&Src, 0); 1019 1020 // Steal arguments and splice the body of Src into Dst. 1021 Dst.stealArgumentListFrom(Src); 1022 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); 1023 1024 // Everything has been moved over. Remap it. 1025 Mapper.scheduleRemapFunction(Dst); 1026 return Error::success(); 1027 } 1028 1029 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { 1030 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID); 1031 } 1032 1033 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) { 1034 if (auto *F = dyn_cast<Function>(&Src)) 1035 return linkFunctionBody(cast<Function>(Dst), *F); 1036 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { 1037 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar); 1038 return Error::success(); 1039 } 1040 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src)); 1041 return Error::success(); 1042 } 1043 1044 void IRLinker::prepareCompileUnitsForImport() { 1045 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu"); 1046 if (!SrcCompileUnits) 1047 return; 1048 // When importing for ThinLTO, prevent importing of types listed on 1049 // the DICompileUnit that we don't need a copy of in the importing 1050 // module. They will be emitted by the originating module. 1051 for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) { 1052 auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I)); 1053 assert(CU && "Expected valid compile unit"); 1054 // Enums, macros, and retained types don't need to be listed on the 1055 // imported DICompileUnit. This means they will only be imported 1056 // if reached from the mapped IR. Do this by setting their value map 1057 // entries to nullptr, which will automatically prevent their importing 1058 // when reached from the DICompileUnit during metadata mapping. 1059 ValueMap.MD()[CU->getRawEnumTypes()].reset(nullptr); 1060 ValueMap.MD()[CU->getRawMacros()].reset(nullptr); 1061 ValueMap.MD()[CU->getRawRetainedTypes()].reset(nullptr); 1062 // We import global variables only temporarily in order for instcombine 1063 // and globalopt to perform constant folding and static constructor 1064 // evaluation. After that elim-avail-extern will covert imported globals 1065 // back to declarations, so we don't need debug info for them. 1066 ValueMap.MD()[CU->getRawGlobalVariables()].reset(nullptr); 1067 1068 // Imported entities only need to be mapped in if they have local 1069 // scope, as those might correspond to an imported entity inside a 1070 // function being imported (any locally scoped imported entities that 1071 // don't end up referenced by an imported function will not be emitted 1072 // into the object). Imported entities not in a local scope 1073 // (e.g. on the namespace) only need to be emitted by the originating 1074 // module. Create a list of the locally scoped imported entities, and 1075 // replace the source CUs imported entity list with the new list, so 1076 // only those are mapped in. 1077 // FIXME: Locally-scoped imported entities could be moved to the 1078 // functions they are local to instead of listing them on the CU, and 1079 // we would naturally only link in those needed by function importing. 1080 SmallVector<TrackingMDNodeRef, 4> AllImportedModules; 1081 bool ReplaceImportedEntities = false; 1082 for (auto *IE : CU->getImportedEntities()) { 1083 DIScope *Scope = IE->getScope(); 1084 assert(Scope && "Invalid Scope encoding!"); 1085 if (isa<DILocalScope>(Scope)) 1086 AllImportedModules.emplace_back(IE); 1087 else 1088 ReplaceImportedEntities = true; 1089 } 1090 if (ReplaceImportedEntities) { 1091 if (!AllImportedModules.empty()) 1092 CU->replaceImportedEntities(MDTuple::get( 1093 CU->getContext(), 1094 SmallVector<Metadata *, 16>(AllImportedModules.begin(), 1095 AllImportedModules.end()))); 1096 else 1097 // If there were no local scope imported entities, we can map 1098 // the whole list to nullptr. 1099 ValueMap.MD()[CU->getRawImportedEntities()].reset(nullptr); 1100 } 1101 } 1102 } 1103 1104 /// Insert all of the named MDNodes in Src into the Dest module. 1105 void IRLinker::linkNamedMDNodes() { 1106 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1107 for (const NamedMDNode &NMD : SrcM->named_metadata()) { 1108 // Don't link module flags here. Do them separately. 1109 if (&NMD == SrcModFlags) 1110 continue; 1111 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); 1112 // Add Src elements into Dest node. 1113 for (const MDNode *Op : NMD.operands()) 1114 DestNMD->addOperand(Mapper.mapMDNode(*Op)); 1115 } 1116 } 1117 1118 /// Merge the linker flags in Src into the Dest module. 1119 Error IRLinker::linkModuleFlagsMetadata() { 1120 // If the source module has no module flags, we are done. 1121 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1122 if (!SrcModFlags) 1123 return Error::success(); 1124 1125 // If the destination module doesn't have module flags yet, then just copy 1126 // over the source module's flags. 1127 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata(); 1128 if (DstModFlags->getNumOperands() == 0) { 1129 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 1130 DstModFlags->addOperand(SrcModFlags->getOperand(I)); 1131 1132 return Error::success(); 1133 } 1134 1135 // First build a map of the existing module flags and requirements. 1136 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; 1137 SmallSetVector<MDNode *, 16> Requirements; 1138 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1139 MDNode *Op = DstModFlags->getOperand(I); 1140 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); 1141 MDString *ID = cast<MDString>(Op->getOperand(1)); 1142 1143 if (Behavior->getZExtValue() == Module::Require) { 1144 Requirements.insert(cast<MDNode>(Op->getOperand(2))); 1145 } else { 1146 Flags[ID] = std::make_pair(Op, I); 1147 } 1148 } 1149 1150 // Merge in the flags from the source module, and also collect its set of 1151 // requirements. 1152 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1153 MDNode *SrcOp = SrcModFlags->getOperand(I); 1154 ConstantInt *SrcBehavior = 1155 mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); 1156 MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 1157 MDNode *DstOp; 1158 unsigned DstIndex; 1159 std::tie(DstOp, DstIndex) = Flags.lookup(ID); 1160 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 1161 1162 // If this is a requirement, add it and continue. 1163 if (SrcBehaviorValue == Module::Require) { 1164 // If the destination module does not already have this requirement, add 1165 // it. 1166 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 1167 DstModFlags->addOperand(SrcOp); 1168 } 1169 continue; 1170 } 1171 1172 // If there is no existing flag with this ID, just add it. 1173 if (!DstOp) { 1174 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); 1175 DstModFlags->addOperand(SrcOp); 1176 continue; 1177 } 1178 1179 // Otherwise, perform a merge. 1180 ConstantInt *DstBehavior = 1181 mdconst::extract<ConstantInt>(DstOp->getOperand(0)); 1182 unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 1183 1184 auto overrideDstValue = [&]() { 1185 DstModFlags->setOperand(DstIndex, SrcOp); 1186 Flags[ID].first = SrcOp; 1187 }; 1188 1189 // If either flag has override behavior, handle it first. 1190 if (DstBehaviorValue == Module::Override) { 1191 // Diagnose inconsistent flags which both have override behavior. 1192 if (SrcBehaviorValue == Module::Override && 1193 SrcOp->getOperand(2) != DstOp->getOperand(2)) 1194 return stringErr("linking module flags '" + ID->getString() + 1195 "': IDs have conflicting override values"); 1196 continue; 1197 } else if (SrcBehaviorValue == Module::Override) { 1198 // Update the destination flag to that of the source. 1199 overrideDstValue(); 1200 continue; 1201 } 1202 1203 // Diagnose inconsistent merge behavior types. 1204 if (SrcBehaviorValue != DstBehaviorValue) 1205 return stringErr("linking module flags '" + ID->getString() + 1206 "': IDs have conflicting behaviors"); 1207 1208 auto replaceDstValue = [&](MDNode *New) { 1209 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; 1210 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps); 1211 DstModFlags->setOperand(DstIndex, Flag); 1212 Flags[ID].first = Flag; 1213 }; 1214 1215 // Perform the merge for standard behavior types. 1216 switch (SrcBehaviorValue) { 1217 case Module::Require: 1218 case Module::Override: 1219 llvm_unreachable("not possible"); 1220 case Module::Error: { 1221 // Emit an error if the values differ. 1222 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) 1223 return stringErr("linking module flags '" + ID->getString() + 1224 "': IDs have conflicting values"); 1225 continue; 1226 } 1227 case Module::Warning: { 1228 // Emit a warning if the values differ. 1229 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1230 emitWarning("linking module flags '" + ID->getString() + 1231 "': IDs have conflicting values"); 1232 } 1233 continue; 1234 } 1235 case Module::Max: { 1236 ConstantInt *DstValue = 1237 mdconst::extract<ConstantInt>(DstOp->getOperand(2)); 1238 ConstantInt *SrcValue = 1239 mdconst::extract<ConstantInt>(SrcOp->getOperand(2)); 1240 if (SrcValue->getZExtValue() > DstValue->getZExtValue()) 1241 overrideDstValue(); 1242 break; 1243 } 1244 case Module::Append: { 1245 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1246 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1247 SmallVector<Metadata *, 8> MDs; 1248 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); 1249 MDs.append(DstValue->op_begin(), DstValue->op_end()); 1250 MDs.append(SrcValue->op_begin(), SrcValue->op_end()); 1251 1252 replaceDstValue(MDNode::get(DstM.getContext(), MDs)); 1253 break; 1254 } 1255 case Module::AppendUnique: { 1256 SmallSetVector<Metadata *, 16> Elts; 1257 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1258 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1259 Elts.insert(DstValue->op_begin(), DstValue->op_end()); 1260 Elts.insert(SrcValue->op_begin(), SrcValue->op_end()); 1261 1262 replaceDstValue(MDNode::get(DstM.getContext(), 1263 makeArrayRef(Elts.begin(), Elts.end()))); 1264 break; 1265 } 1266 } 1267 } 1268 1269 // Check all of the requirements. 1270 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 1271 MDNode *Requirement = Requirements[I]; 1272 MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1273 Metadata *ReqValue = Requirement->getOperand(1); 1274 1275 MDNode *Op = Flags[Flag].first; 1276 if (!Op || Op->getOperand(2) != ReqValue) 1277 return stringErr("linking module flags '" + Flag->getString() + 1278 "': does not have the required value"); 1279 } 1280 return Error::success(); 1281 } 1282 1283 /// Return InlineAsm adjusted with target-specific directives if required. 1284 /// For ARM and Thumb, we have to add directives to select the appropriate ISA 1285 /// to support mixing module-level inline assembly from ARM and Thumb modules. 1286 static std::string adjustInlineAsm(const std::string &InlineAsm, 1287 const Triple &Triple) { 1288 if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb) 1289 return ".text\n.balign 2\n.thumb\n" + InlineAsm; 1290 if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb) 1291 return ".text\n.balign 4\n.arm\n" + InlineAsm; 1292 return InlineAsm; 1293 } 1294 1295 Error IRLinker::run() { 1296 // Ensure metadata materialized before value mapping. 1297 if (SrcM->getMaterializer()) 1298 if (Error Err = SrcM->getMaterializer()->materializeMetadata()) 1299 return Err; 1300 1301 // Inherit the target data from the source module if the destination module 1302 // doesn't have one already. 1303 if (DstM.getDataLayout().isDefault()) 1304 DstM.setDataLayout(SrcM->getDataLayout()); 1305 1306 if (SrcM->getDataLayout() != DstM.getDataLayout()) { 1307 emitWarning("Linking two modules of different data layouts: '" + 1308 SrcM->getModuleIdentifier() + "' is '" + 1309 SrcM->getDataLayoutStr() + "' whereas '" + 1310 DstM.getModuleIdentifier() + "' is '" + 1311 DstM.getDataLayoutStr() + "'\n"); 1312 } 1313 1314 // Copy the target triple from the source to dest if the dest's is empty. 1315 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1316 DstM.setTargetTriple(SrcM->getTargetTriple()); 1317 1318 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple()); 1319 1320 if (!SrcM->getTargetTriple().empty()&& 1321 !SrcTriple.isCompatibleWith(DstTriple)) 1322 emitWarning("Linking two modules of different target triples: " + 1323 SrcM->getModuleIdentifier() + "' is '" + 1324 SrcM->getTargetTriple() + "' whereas '" + 1325 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() + 1326 "'\n"); 1327 1328 DstM.setTargetTriple(SrcTriple.merge(DstTriple)); 1329 1330 // Append the module inline asm string. 1331 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) { 1332 std::string SrcModuleInlineAsm = adjustInlineAsm(SrcM->getModuleInlineAsm(), 1333 SrcTriple); 1334 if (DstM.getModuleInlineAsm().empty()) 1335 DstM.setModuleInlineAsm(SrcModuleInlineAsm); 1336 else 1337 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" + 1338 SrcModuleInlineAsm); 1339 } 1340 1341 // Loop over all of the linked values to compute type mappings. 1342 computeTypeMapping(); 1343 1344 std::reverse(Worklist.begin(), Worklist.end()); 1345 while (!Worklist.empty()) { 1346 GlobalValue *GV = Worklist.back(); 1347 Worklist.pop_back(); 1348 1349 // Already mapped. 1350 if (ValueMap.find(GV) != ValueMap.end() || 1351 AliasValueMap.find(GV) != AliasValueMap.end()) 1352 continue; 1353 1354 assert(!GV->isDeclaration()); 1355 Mapper.mapValue(*GV); 1356 if (FoundError) 1357 return std::move(*FoundError); 1358 } 1359 1360 // Note that we are done linking global value bodies. This prevents 1361 // metadata linking from creating new references. 1362 DoneLinkingBodies = true; 1363 Mapper.addFlags(RF_NullMapMissingGlobalValues); 1364 1365 // Remap all of the named MDNodes in Src into the DstM module. We do this 1366 // after linking GlobalValues so that MDNodes that reference GlobalValues 1367 // are properly remapped. 1368 linkNamedMDNodes(); 1369 1370 // Merge the module flags into the DstM module. 1371 return linkModuleFlagsMetadata(); 1372 } 1373 1374 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) 1375 : ETypes(E), IsPacked(P) {} 1376 1377 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) 1378 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} 1379 1380 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { 1381 return IsPacked == That.IsPacked && ETypes == That.ETypes; 1382 } 1383 1384 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { 1385 return !this->operator==(That); 1386 } 1387 1388 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() { 1389 return DenseMapInfo<StructType *>::getEmptyKey(); 1390 } 1391 1392 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() { 1393 return DenseMapInfo<StructType *>::getTombstoneKey(); 1394 } 1395 1396 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { 1397 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), 1398 Key.IsPacked); 1399 } 1400 1401 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) { 1402 return getHashValue(KeyTy(ST)); 1403 } 1404 1405 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS, 1406 const StructType *RHS) { 1407 if (RHS == getEmptyKey() || RHS == getTombstoneKey()) 1408 return false; 1409 return LHS == KeyTy(RHS); 1410 } 1411 1412 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS, 1413 const StructType *RHS) { 1414 if (RHS == getEmptyKey() || RHS == getTombstoneKey()) 1415 return LHS == RHS; 1416 return KeyTy(LHS) == KeyTy(RHS); 1417 } 1418 1419 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { 1420 assert(!Ty->isOpaque()); 1421 NonOpaqueStructTypes.insert(Ty); 1422 } 1423 1424 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) { 1425 assert(!Ty->isOpaque()); 1426 NonOpaqueStructTypes.insert(Ty); 1427 bool Removed = OpaqueStructTypes.erase(Ty); 1428 (void)Removed; 1429 assert(Removed); 1430 } 1431 1432 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { 1433 assert(Ty->isOpaque()); 1434 OpaqueStructTypes.insert(Ty); 1435 } 1436 1437 StructType * 1438 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, 1439 bool IsPacked) { 1440 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); 1441 auto I = NonOpaqueStructTypes.find_as(Key); 1442 return I == NonOpaqueStructTypes.end() ? nullptr : *I; 1443 } 1444 1445 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) { 1446 if (Ty->isOpaque()) 1447 return OpaqueStructTypes.count(Ty); 1448 auto I = NonOpaqueStructTypes.find(Ty); 1449 return I == NonOpaqueStructTypes.end() ? false : *I == Ty; 1450 } 1451 1452 IRMover::IRMover(Module &M) : Composite(M) { 1453 TypeFinder StructTypes; 1454 StructTypes.run(M, /* OnlyNamed */ false); 1455 for (StructType *Ty : StructTypes) { 1456 if (Ty->isOpaque()) 1457 IdentifiedStructTypes.addOpaque(Ty); 1458 else 1459 IdentifiedStructTypes.addNonOpaque(Ty); 1460 } 1461 // Self-map metadatas in the destination module. This is needed when 1462 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the 1463 // destination module may be reached from the source module. 1464 for (auto *MD : StructTypes.getVisitedMetadata()) { 1465 SharedMDs[MD].reset(const_cast<MDNode *>(MD)); 1466 } 1467 } 1468 1469 Error IRMover::move( 1470 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink, 1471 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor, 1472 bool IsPerformingImport) { 1473 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes, 1474 std::move(Src), ValuesToLink, std::move(AddLazyFor), 1475 IsPerformingImport); 1476 Error E = TheIRLinker.run(); 1477 Composite.dropTriviallyDeadConstantArrays(); 1478 return E; 1479 } 1480