1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/DiagnosticPrinter.h"
17 #include "llvm/IR/TypeFinder.h"
18 #include "llvm/Transforms/Utils/Cloning.h"
21 //===----------------------------------------------------------------------===//
22 // TypeMap implementation.
23 //===----------------------------------------------------------------------===//
26 class TypeMapTy : public ValueMapTypeRemapper {
27 /// This is a mapping from a source type to a destination type to use.
28 DenseMap<Type *, Type *> MappedTypes;
30 /// When checking to see if two subgraphs are isomorphic, we speculatively
31 /// add types to MappedTypes, but keep track of them here in case we need to
33 SmallVector<Type *, 16> SpeculativeTypes;
35 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
37 /// This is a list of non-opaque structs in the source module that are mapped
38 /// to an opaque struct in the destination module.
39 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
41 /// This is the set of opaque types in the destination modules who are
42 /// getting a body from the source module.
43 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
46 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
47 : DstStructTypesSet(DstStructTypesSet) {}
49 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
50 /// Indicate that the specified type in the destination module is conceptually
51 /// equivalent to the specified type in the source module.
52 void addTypeMapping(Type *DstTy, Type *SrcTy);
54 /// Produce a body for an opaque type in the dest module from a type
55 /// definition in the source module.
56 void linkDefinedTypeBodies();
58 /// Return the mapped type to use for the specified input type from the
60 Type *get(Type *SrcTy);
61 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
63 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
65 FunctionType *get(FunctionType *T) {
66 return cast<FunctionType>(get((Type *)T));
70 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
72 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
76 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
77 assert(SpeculativeTypes.empty());
78 assert(SpeculativeDstOpaqueTypes.empty());
80 // Check to see if these types are recursively isomorphic and establish a
81 // mapping between them if so.
82 if (!areTypesIsomorphic(DstTy, SrcTy)) {
83 // Oops, they aren't isomorphic. Just discard this request by rolling out
84 // any speculative mappings we've established.
85 for (Type *Ty : SpeculativeTypes)
86 MappedTypes.erase(Ty);
88 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
89 SpeculativeDstOpaqueTypes.size());
90 for (StructType *Ty : SpeculativeDstOpaqueTypes)
91 DstResolvedOpaqueTypes.erase(Ty);
93 for (Type *Ty : SpeculativeTypes)
94 if (auto *STy = dyn_cast<StructType>(Ty))
98 SpeculativeTypes.clear();
99 SpeculativeDstOpaqueTypes.clear();
102 /// Recursively walk this pair of types, returning true if they are isomorphic,
103 /// false if they are not.
104 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
105 // Two types with differing kinds are clearly not isomorphic.
106 if (DstTy->getTypeID() != SrcTy->getTypeID())
109 // If we have an entry in the MappedTypes table, then we have our answer.
110 Type *&Entry = MappedTypes[SrcTy];
112 return Entry == DstTy;
114 // Two identical types are clearly isomorphic. Remember this
115 // non-speculatively.
116 if (DstTy == SrcTy) {
121 // Okay, we have two types with identical kinds that we haven't seen before.
123 // If this is an opaque struct type, special case it.
124 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
125 // Mapping an opaque type to any struct, just keep the dest struct.
126 if (SSTy->isOpaque()) {
128 SpeculativeTypes.push_back(SrcTy);
132 // Mapping a non-opaque source type to an opaque dest. If this is the first
133 // type that we're mapping onto this destination type then we succeed. Keep
134 // the dest, but fill it in later. If this is the second (different) type
135 // that we're trying to map onto the same opaque type then we fail.
136 if (cast<StructType>(DstTy)->isOpaque()) {
137 // We can only map one source type onto the opaque destination type.
138 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
140 SrcDefinitionsToResolve.push_back(SSTy);
141 SpeculativeTypes.push_back(SrcTy);
142 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
148 // If the number of subtypes disagree between the two types, then we fail.
149 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
152 // Fail if any of the extra properties (e.g. array size) of the type disagree.
153 if (isa<IntegerType>(DstTy))
154 return false; // bitwidth disagrees.
155 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
156 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
159 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
160 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
162 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
163 StructType *SSTy = cast<StructType>(SrcTy);
164 if (DSTy->isLiteral() != SSTy->isLiteral() ||
165 DSTy->isPacked() != SSTy->isPacked())
167 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
168 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
170 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
171 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
175 // Otherwise, we speculate that these two types will line up and recursively
176 // check the subelements.
178 SpeculativeTypes.push_back(SrcTy);
180 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
181 if (!areTypesIsomorphic(DstTy->getContainedType(I),
182 SrcTy->getContainedType(I)))
185 // If everything seems to have lined up, then everything is great.
189 void TypeMapTy::linkDefinedTypeBodies() {
190 SmallVector<Type *, 16> Elements;
191 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
192 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
193 assert(DstSTy->isOpaque());
195 // Map the body of the source type over to a new body for the dest type.
196 Elements.resize(SrcSTy->getNumElements());
197 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
198 Elements[I] = get(SrcSTy->getElementType(I));
200 DstSTy->setBody(Elements, SrcSTy->isPacked());
201 DstStructTypesSet.switchToNonOpaque(DstSTy);
203 SrcDefinitionsToResolve.clear();
204 DstResolvedOpaqueTypes.clear();
207 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
208 ArrayRef<Type *> ETypes) {
209 DTy->setBody(ETypes, STy->isPacked());
212 if (STy->hasName()) {
213 SmallString<16> TmpName = STy->getName();
215 DTy->setName(TmpName);
218 DstStructTypesSet.addNonOpaque(DTy);
221 Type *TypeMapTy::get(Type *Ty) {
222 SmallPtrSet<StructType *, 8> Visited;
223 return get(Ty, Visited);
226 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
227 // If we already have an entry for this type, return it.
228 Type **Entry = &MappedTypes[Ty];
232 // These are types that LLVM itself will unique.
233 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
237 for (auto &Pair : MappedTypes) {
238 assert(!(Pair.first != Ty && Pair.second == Ty) &&
239 "mapping to a source type");
244 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
245 StructType *DTy = StructType::create(Ty->getContext());
249 // If this is not a recursive type, then just map all of the elements and
250 // then rebuild the type from inside out.
251 SmallVector<Type *, 4> ElementTypes;
253 // If there are no element types to map, then the type is itself. This is
254 // true for the anonymous {} struct, things like 'float', integers, etc.
255 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
258 // Remap all of the elements, keeping track of whether any of them change.
259 bool AnyChange = false;
260 ElementTypes.resize(Ty->getNumContainedTypes());
261 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
262 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
263 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
266 // If we found our type while recursively processing stuff, just use it.
267 Entry = &MappedTypes[Ty];
269 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
270 if (DTy->isOpaque()) {
271 auto *STy = cast<StructType>(Ty);
272 finishType(DTy, STy, ElementTypes);
278 // If all of the element types mapped directly over and the type is not
279 // a nomed struct, then the type is usable as-is.
280 if (!AnyChange && IsUniqued)
283 // Otherwise, rebuild a modified type.
284 switch (Ty->getTypeID()) {
286 llvm_unreachable("unknown derived type to remap");
287 case Type::ArrayTyID:
288 return *Entry = ArrayType::get(ElementTypes[0],
289 cast<ArrayType>(Ty)->getNumElements());
290 case Type::VectorTyID:
291 return *Entry = VectorType::get(ElementTypes[0],
292 cast<VectorType>(Ty)->getNumElements());
293 case Type::PointerTyID:
294 return *Entry = PointerType::get(ElementTypes[0],
295 cast<PointerType>(Ty)->getAddressSpace());
296 case Type::FunctionTyID:
297 return *Entry = FunctionType::get(ElementTypes[0],
298 makeArrayRef(ElementTypes).slice(1),
299 cast<FunctionType>(Ty)->isVarArg());
300 case Type::StructTyID: {
301 auto *STy = cast<StructType>(Ty);
302 bool IsPacked = STy->isPacked();
304 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
306 // If the type is opaque, we can just use it directly.
307 if (STy->isOpaque()) {
308 DstStructTypesSet.addOpaque(STy);
312 if (StructType *OldT =
313 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
315 return *Entry = OldT;
319 DstStructTypesSet.addNonOpaque(STy);
323 StructType *DTy = StructType::create(Ty->getContext());
324 finishType(DTy, STy, ElementTypes);
330 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
332 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
333 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
335 //===----------------------------------------------------------------------===//
336 // ModuleLinker implementation.
337 //===----------------------------------------------------------------------===//
342 /// Creates prototypes for functions that are lazily linked on the fly. This
343 /// speeds up linking for modules with many/ lazily linked functions of which
345 class GlobalValueMaterializer final : public ValueMaterializer {
349 GlobalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
350 Value *materializeDeclFor(Value *V) override;
351 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
354 class LocalValueMaterializer final : public ValueMaterializer {
358 LocalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
359 Value *materializeDeclFor(Value *V) override;
360 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
363 /// This is responsible for keeping track of the state used for moving data
364 /// from SrcM to DstM.
369 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
372 GlobalValueMaterializer GValMaterializer;
373 LocalValueMaterializer LValMaterializer;
375 /// Mapping of values from what they used to be in Src, to what they are now
376 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
377 /// due to the use of Value handles which the Linker doesn't actually need,
378 /// but this allows us to reuse the ValueMapper code.
379 ValueToValueMapTy ValueMap;
380 ValueToValueMapTy AliasValueMap;
382 DenseSet<GlobalValue *> ValuesToLink;
383 std::vector<GlobalValue *> Worklist;
385 void maybeAdd(GlobalValue *GV) {
386 if (ValuesToLink.insert(GV).second)
387 Worklist.push_back(GV);
390 DiagnosticHandlerFunction DiagnosticHandler;
392 /// Set to true when all global value body linking is complete (including
393 /// lazy linking). Used to prevent metadata linking from creating new
395 bool DoneLinkingBodies = false;
397 bool HasError = false;
399 /// Handles cloning of a global values from the source module into
400 /// the destination module, including setting the attributes and visibility.
401 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
403 /// Helper method for setting a message and returning an error code.
404 bool emitError(const Twine &Message) {
405 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
410 void emitWarning(const Twine &Message) {
411 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
414 /// Given a global in the source module, return the global in the
415 /// destination module that is being linked to, if any.
416 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
417 // If the source has no name it can't link. If it has local linkage,
418 // there is no name match-up going on.
419 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
422 // Otherwise see if we have a match in the destination module's symtab.
423 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
427 // If we found a global with the same name in the dest module, but it has
428 // internal linkage, we are really not doing any linkage here.
429 if (DGV->hasLocalLinkage())
432 // Otherwise, we do in fact link to the destination global.
436 void computeTypeMapping();
438 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
439 const GlobalVariable *SrcGV);
441 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
442 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
444 bool linkModuleFlagsMetadata();
446 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
447 bool linkFunctionBody(Function &Dst, Function &Src);
448 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
449 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
451 /// Functions that take care of cloning a specific global value type
452 /// into the destination module.
453 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
454 Function *copyFunctionProto(const Function *SF);
455 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
457 void linkNamedMDNodes();
460 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, Module &SrcM,
461 DiagnosticHandlerFunction DiagnosticHandler,
462 ArrayRef<GlobalValue *> ValuesToLink,
463 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
464 : DstM(DstM), SrcM(SrcM), AddLazyFor(AddLazyFor), TypeMap(Set),
465 GValMaterializer(this), LValMaterializer(this),
466 DiagnosticHandler(DiagnosticHandler) {
467 for (GlobalValue *GV : ValuesToLink)
472 Value *materializeDeclFor(Value *V, bool ForAlias);
473 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
477 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
478 /// table. This is good for all clients except for us. Go through the trouble
479 /// to force this back.
480 static void forceRenaming(GlobalValue *GV, StringRef Name) {
481 // If the global doesn't force its name or if it already has the right name,
482 // there is nothing for us to do.
483 if (GV->hasLocalLinkage() || GV->getName() == Name)
486 Module *M = GV->getParent();
488 // If there is a conflict, rename the conflict.
489 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
490 GV->takeName(ConflictGV);
491 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
492 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
494 GV->setName(Name); // Force the name back
498 Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
499 return ModLinker->materializeDeclFor(V, false);
502 void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
504 ModLinker->materializeInitFor(New, Old, false);
507 Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
508 return ModLinker->materializeDeclFor(V, true);
511 void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
513 ModLinker->materializeInitFor(New, Old, true);
516 Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
517 auto *SGV = dyn_cast<GlobalValue>(V);
521 return linkGlobalValueProto(SGV, ForAlias);
524 void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
526 // If we already created the body, just return.
527 if (auto *F = dyn_cast<Function>(New)) {
528 if (!F->isDeclaration())
530 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
531 if (V->hasInitializer())
534 auto *A = cast<GlobalAlias>(New);
539 if (ForAlias || shouldLink(New, *Old))
540 linkGlobalValueBody(*New, *Old);
543 /// Loop through the global variables in the src module and merge them into the
545 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
546 // No linking to be performed or linking from the source: simply create an
547 // identical version of the symbol over in the dest module... the
548 // initializer will be filled in later by LinkGlobalInits.
549 GlobalVariable *NewDGV =
550 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
551 SGVar->isConstant(), GlobalValue::ExternalLinkage,
552 /*init*/ nullptr, SGVar->getName(),
553 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
554 SGVar->getType()->getAddressSpace());
555 NewDGV->setAlignment(SGVar->getAlignment());
559 /// Link the function in the source module into the destination module if
560 /// needed, setting up mapping information.
561 Function *IRLinker::copyFunctionProto(const Function *SF) {
562 // If there is no linkage to be performed or we are linking from the source,
564 return Function::Create(TypeMap.get(SF->getFunctionType()),
565 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
568 /// Set up prototypes for any aliases that come over from the source module.
569 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
570 // If there is no linkage to be performed or we're linking from the source,
572 auto *Ty = TypeMap.get(SGA->getValueType());
573 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
574 GlobalValue::ExternalLinkage, SGA->getName(),
578 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
579 bool ForDefinition) {
581 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
582 NewGV = copyGlobalVariableProto(SGVar);
583 } else if (auto *SF = dyn_cast<Function>(SGV)) {
584 NewGV = copyFunctionProto(SF);
587 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
589 NewGV = new GlobalVariable(
590 DstM, TypeMap.get(SGV->getType()->getElementType()),
591 /*isConstant*/ false, GlobalValue::ExternalLinkage,
592 /*init*/ nullptr, SGV->getName(),
593 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
594 SGV->getType()->getAddressSpace());
598 NewGV->setLinkage(SGV->getLinkage());
599 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
600 SGV->hasLinkOnceLinkage())
601 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
603 NewGV->copyAttributesFrom(SGV);
607 /// Loop over all of the linked values to compute type mappings. For example,
608 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
609 /// types 'Foo' but one got renamed when the module was loaded into the same
611 void IRLinker::computeTypeMapping() {
612 for (GlobalValue &SGV : SrcM.globals()) {
613 GlobalValue *DGV = getLinkedToGlobal(&SGV);
617 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
618 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
622 // Unify the element type of appending arrays.
623 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
624 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
625 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
628 for (GlobalValue &SGV : SrcM)
629 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
630 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
632 for (GlobalValue &SGV : SrcM.aliases())
633 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
634 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
636 // Incorporate types by name, scanning all the types in the source module.
637 // At this point, the destination module may have a type "%foo = { i32 }" for
638 // example. When the source module got loaded into the same LLVMContext, if
639 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
640 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
641 for (StructType *ST : Types) {
645 // Check to see if there is a dot in the name followed by a digit.
646 size_t DotPos = ST->getName().rfind('.');
647 if (DotPos == 0 || DotPos == StringRef::npos ||
648 ST->getName().back() == '.' ||
649 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
652 // Check to see if the destination module has a struct with the prefix name.
653 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
657 // Don't use it if this actually came from the source module. They're in
658 // the same LLVMContext after all. Also don't use it unless the type is
659 // actually used in the destination module. This can happen in situations
664 // %Z = type { %A } %B = type { %C.1 }
665 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
666 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
667 // %C = type { i8* } %B.3 = type { %C.1 }
669 // When we link Module B with Module A, the '%B' in Module B is
670 // used. However, that would then use '%C.1'. But when we process '%C.1',
671 // we prefer to take the '%C' version. So we are then left with both
672 // '%C.1' and '%C' being used for the same types. This leads to some
673 // variables using one type and some using the other.
674 if (TypeMap.DstStructTypesSet.hasType(DST))
675 TypeMap.addTypeMapping(DST, ST);
678 // Now that we have discovered all of the type equivalences, get a body for
679 // any 'opaque' types in the dest module that are now resolved.
680 TypeMap.linkDefinedTypeBodies();
683 static void getArrayElements(const Constant *C,
684 SmallVectorImpl<Constant *> &Dest) {
685 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
687 for (unsigned i = 0; i != NumElements; ++i)
688 Dest.push_back(C->getAggregateElement(i));
691 /// If there were any appending global variables, link them together now.
692 /// Return true on error.
693 Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
694 const GlobalVariable *SrcGV) {
695 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
698 StringRef Name = SrcGV->getName();
699 bool IsNewStructor = false;
700 bool IsOldStructor = false;
701 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
702 if (cast<StructType>(EltTy)->getNumElements() == 3)
703 IsNewStructor = true;
705 IsOldStructor = true;
708 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
710 auto &ST = *cast<StructType>(EltTy);
711 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
712 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
716 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
718 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
720 "Linking globals named '" + SrcGV->getName() +
721 "': can only link appending global with another appending global!");
725 // Check to see that they two arrays agree on type.
726 if (EltTy != DstTy->getElementType()) {
727 emitError("Appending variables with different element types!");
730 if (DstGV->isConstant() != SrcGV->isConstant()) {
731 emitError("Appending variables linked with different const'ness!");
735 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
737 "Appending variables with different alignment need to be linked!");
741 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
743 "Appending variables with different visibility need to be linked!");
747 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
749 "Appending variables with different unnamed_addr need to be linked!");
753 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
755 "Appending variables with different section name need to be linked!");
760 SmallVector<Constant *, 16> DstElements;
762 getArrayElements(DstGV->getInitializer(), DstElements);
764 SmallVector<Constant *, 16> SrcElements;
765 getArrayElements(SrcGV->getInitializer(), SrcElements);
769 std::remove_if(SrcElements.begin(), SrcElements.end(),
770 [this](Constant *E) {
771 auto *Key = dyn_cast<GlobalValue>(
772 E->getAggregateElement(2)->stripPointerCasts());
775 GlobalValue *DGV = getLinkedToGlobal(Key);
776 return !shouldLink(DGV, *Key);
779 uint64_t NewSize = DstElements.size() + SrcElements.size();
780 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
782 // Create the new global variable.
783 GlobalVariable *NG = new GlobalVariable(
784 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
785 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
786 SrcGV->getType()->getAddressSpace());
788 NG->copyAttributesFrom(SrcGV);
789 forceRenaming(NG, SrcGV->getName());
791 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
794 ValueMap[SrcGV] = Ret;
796 for (auto *V : SrcElements) {
799 auto *S = cast<ConstantStruct>(V);
800 auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
801 &TypeMap, &GValMaterializer);
802 auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
803 &TypeMap, &GValMaterializer);
804 Value *Null = Constant::getNullValue(VoidPtrTy);
806 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
808 NewV = MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap,
811 DstElements.push_back(NewV);
814 NG->setInitializer(ConstantArray::get(NewType, DstElements));
816 // Replace any uses of the two global variables with uses of the new
819 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
820 DstGV->eraseFromParent();
826 static bool useExistingDest(GlobalValue &SGV, GlobalValue *DGV,
831 if (SGV.isDeclaration())
834 if (DGV->isDeclarationForLinker())
843 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
844 if (ValuesToLink.count(&SGV))
847 if (SGV.hasLocalLinkage())
850 if (DGV && !DGV->isDeclaration())
853 if (SGV.hasAvailableExternallyLinkage())
856 if (DoneLinkingBodies)
859 AddLazyFor(SGV, [this](GlobalValue &GV) { maybeAdd(&GV); });
860 return ValuesToLink.count(&SGV);
863 Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
864 GlobalValue *DGV = getLinkedToGlobal(SGV);
866 bool ShouldLink = shouldLink(DGV, *SGV);
868 // just missing from map
870 auto I = ValueMap.find(SGV);
871 if (I != ValueMap.end())
872 return cast<Constant>(I->second);
874 I = AliasValueMap.find(SGV);
875 if (I != AliasValueMap.end())
876 return cast<Constant>(I->second);
880 if (ShouldLink || !ForAlias)
881 DGV = getLinkedToGlobal(SGV);
883 // Handle the ultra special appending linkage case first.
884 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
885 if (SGV->hasAppendingLinkage())
886 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
887 cast<GlobalVariable>(SGV));
890 if (useExistingDest(*SGV, DGV, ShouldLink)) {
893 // If we are done linking global value bodies (i.e. we are performing
894 // metadata linking), don't link in the global value due to this
895 // reference, simply map it to null.
896 if (DoneLinkingBodies)
899 NewGV = copyGlobalValueProto(SGV, ShouldLink);
901 forceRenaming(NewGV, SGV->getName());
903 if (ShouldLink || ForAlias) {
904 if (const Comdat *SC = SGV->getComdat()) {
905 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
906 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
907 DC->setSelectionKind(SC->getSelectionKind());
913 if (!ShouldLink && ForAlias)
914 NewGV->setLinkage(GlobalValue::InternalLinkage);
918 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
920 if (DGV && NewGV != DGV) {
921 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
922 DGV->eraseFromParent();
928 /// Update the initializers in the Dest module now that all globals that may be
929 /// referenced are in Dest.
930 void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
931 // Figure out what the initializer looks like in the dest module.
932 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
933 RF_MoveDistinctMDs, &TypeMap, &GValMaterializer));
936 /// Copy the source function over into the dest function and fix up references
937 /// to values. At this point we know that Dest is an external function, and
939 bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
940 assert(Dst.isDeclaration() && !Src.isDeclaration());
942 // Materialize if needed.
943 if (std::error_code EC = Src.materialize())
944 return emitError(EC.message());
946 // Link in the prefix data.
947 if (Src.hasPrefixData())
948 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
949 RF_MoveDistinctMDs, &TypeMap,
952 // Link in the prologue data.
953 if (Src.hasPrologueData())
954 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
955 RF_MoveDistinctMDs, &TypeMap,
958 // Link in the personality function.
959 if (Src.hasPersonalityFn())
960 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
961 RF_MoveDistinctMDs, &TypeMap,
964 // Go through and convert function arguments over, remembering the mapping.
965 Function::arg_iterator DI = Dst.arg_begin();
966 for (Argument &Arg : Src.args()) {
967 DI->setName(Arg.getName()); // Copy the name over.
969 // Add a mapping to our mapping.
970 ValueMap[&Arg] = &*DI;
974 // Copy over the metadata attachments.
975 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
976 Src.getAllMetadata(MDs);
977 for (const auto &I : MDs)
978 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
979 &TypeMap, &GValMaterializer));
981 // Splice the body of the source function into the dest function.
982 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
984 // At this point, all of the instructions and values of the function are now
985 // copied over. The only problem is that they are still referencing values in
986 // the Source function as operands. Loop through all of the operands of the
987 // functions and patch them up to point to the local versions.
988 for (BasicBlock &BB : Dst)
989 for (Instruction &I : BB)
990 RemapInstruction(&I, ValueMap,
991 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
994 // There is no need to map the arguments anymore.
995 for (Argument &Arg : Src.args())
996 ValueMap.erase(&Arg);
1002 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1003 Constant *Aliasee = Src.getAliasee();
1004 Constant *Val = MapValue(Aliasee, AliasValueMap, RF_MoveDistinctMDs, &TypeMap,
1006 Dst.setAliasee(Val);
1009 bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1010 if (auto *F = dyn_cast<Function>(&Src))
1011 return linkFunctionBody(cast<Function>(Dst), *F);
1012 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1013 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1016 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1020 /// Insert all of the named MDNodes in Src into the Dest module.
1021 void IRLinker::linkNamedMDNodes() {
1022 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1023 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1024 // Don't link module flags here. Do them separately.
1025 if (&NMD == SrcModFlags)
1027 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1028 // Add Src elements into Dest node.
1029 for (const MDNode *op : NMD.operands())
1030 DestNMD->addOperand(MapMetadata(
1031 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1032 &TypeMap, &GValMaterializer));
1036 /// Merge the linker flags in Src into the Dest module.
1037 bool IRLinker::linkModuleFlagsMetadata() {
1038 // If the source module has no module flags, we are done.
1039 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1043 // If the destination module doesn't have module flags yet, then just copy
1044 // over the source module's flags.
1045 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1046 if (DstModFlags->getNumOperands() == 0) {
1047 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1048 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1053 // First build a map of the existing module flags and requirements.
1054 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1055 SmallSetVector<MDNode *, 16> Requirements;
1056 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1057 MDNode *Op = DstModFlags->getOperand(I);
1058 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1059 MDString *ID = cast<MDString>(Op->getOperand(1));
1061 if (Behavior->getZExtValue() == Module::Require) {
1062 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1064 Flags[ID] = std::make_pair(Op, I);
1068 // Merge in the flags from the source module, and also collect its set of
1070 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1071 MDNode *SrcOp = SrcModFlags->getOperand(I);
1072 ConstantInt *SrcBehavior =
1073 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1074 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1077 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1078 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1080 // If this is a requirement, add it and continue.
1081 if (SrcBehaviorValue == Module::Require) {
1082 // If the destination module does not already have this requirement, add
1084 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1085 DstModFlags->addOperand(SrcOp);
1090 // If there is no existing flag with this ID, just add it.
1092 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1093 DstModFlags->addOperand(SrcOp);
1097 // Otherwise, perform a merge.
1098 ConstantInt *DstBehavior =
1099 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1100 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1102 // If either flag has override behavior, handle it first.
1103 if (DstBehaviorValue == Module::Override) {
1104 // Diagnose inconsistent flags which both have override behavior.
1105 if (SrcBehaviorValue == Module::Override &&
1106 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1107 emitError("linking module flags '" + ID->getString() +
1108 "': IDs have conflicting override values");
1111 } else if (SrcBehaviorValue == Module::Override) {
1112 // Update the destination flag to that of the source.
1113 DstModFlags->setOperand(DstIndex, SrcOp);
1114 Flags[ID].first = SrcOp;
1118 // Diagnose inconsistent merge behavior types.
1119 if (SrcBehaviorValue != DstBehaviorValue) {
1120 emitError("linking module flags '" + ID->getString() +
1121 "': IDs have conflicting behaviors");
1125 auto replaceDstValue = [&](MDNode *New) {
1126 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1127 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1128 DstModFlags->setOperand(DstIndex, Flag);
1129 Flags[ID].first = Flag;
1132 // Perform the merge for standard behavior types.
1133 switch (SrcBehaviorValue) {
1134 case Module::Require:
1135 case Module::Override:
1136 llvm_unreachable("not possible");
1137 case Module::Error: {
1138 // Emit an error if the values differ.
1139 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1140 emitError("linking module flags '" + ID->getString() +
1141 "': IDs have conflicting values");
1145 case Module::Warning: {
1146 // Emit a warning if the values differ.
1147 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1148 emitWarning("linking module flags '" + ID->getString() +
1149 "': IDs have conflicting values");
1153 case Module::Append: {
1154 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1155 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1156 SmallVector<Metadata *, 8> MDs;
1157 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1158 MDs.append(DstValue->op_begin(), DstValue->op_end());
1159 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1161 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1164 case Module::AppendUnique: {
1165 SmallSetVector<Metadata *, 16> Elts;
1166 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1167 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1168 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1169 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1171 replaceDstValue(MDNode::get(DstM.getContext(),
1172 makeArrayRef(Elts.begin(), Elts.end())));
1178 // Check all of the requirements.
1179 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1180 MDNode *Requirement = Requirements[I];
1181 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1182 Metadata *ReqValue = Requirement->getOperand(1);
1184 MDNode *Op = Flags[Flag].first;
1185 if (!Op || Op->getOperand(2) != ReqValue) {
1186 emitError("linking module flags '" + Flag->getString() +
1187 "': does not have the required value");
1195 // This function returns true if the triples match.
1196 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1197 // If vendor is apple, ignore the version number.
1198 if (T0.getVendor() == Triple::Apple)
1199 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1200 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1205 // This function returns the merged triple.
1206 static std::string mergeTriples(const Triple &SrcTriple,
1207 const Triple &DstTriple) {
1208 // If vendor is apple, pick the triple with the larger version number.
1209 if (SrcTriple.getVendor() == Triple::Apple)
1210 if (DstTriple.isOSVersionLT(SrcTriple))
1211 return SrcTriple.str();
1213 return DstTriple.str();
1216 bool IRLinker::run() {
1217 // Inherit the target data from the source module if the destination module
1218 // doesn't have one already.
1219 if (DstM.getDataLayout().isDefault())
1220 DstM.setDataLayout(SrcM.getDataLayout());
1222 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1223 emitWarning("Linking two modules of different data layouts: '" +
1224 SrcM.getModuleIdentifier() + "' is '" +
1225 SrcM.getDataLayoutStr() + "' whereas '" +
1226 DstM.getModuleIdentifier() + "' is '" +
1227 DstM.getDataLayoutStr() + "'\n");
1230 // Copy the target triple from the source to dest if the dest's is empty.
1231 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1232 DstM.setTargetTriple(SrcM.getTargetTriple());
1234 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1236 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1237 emitWarning("Linking two modules of different target triples: " +
1238 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1239 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1240 DstM.getTargetTriple() + "'\n");
1242 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1244 // Append the module inline asm string.
1245 if (!SrcM.getModuleInlineAsm().empty()) {
1246 if (DstM.getModuleInlineAsm().empty())
1247 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1249 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1250 SrcM.getModuleInlineAsm());
1253 // Loop over all of the linked values to compute type mappings.
1254 computeTypeMapping();
1256 std::reverse(Worklist.begin(), Worklist.end());
1257 while (!Worklist.empty()) {
1258 GlobalValue *GV = Worklist.back();
1259 Worklist.pop_back();
1262 if (ValueMap.find(GV) != ValueMap.end() ||
1263 AliasValueMap.find(GV) != AliasValueMap.end())
1266 assert(!GV->isDeclaration());
1267 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &GValMaterializer);
1272 // Note that we are done linking global value bodies. This prevents
1273 // metadata linking from creating new references.
1274 DoneLinkingBodies = true;
1276 // Remap all of the named MDNodes in Src into the DstM module. We do this
1277 // after linking GlobalValues so that MDNodes that reference GlobalValues
1278 // are properly remapped.
1281 // Merge the module flags into the DstM module.
1282 if (linkModuleFlagsMetadata())
1288 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1289 : ETypes(E), IsPacked(P) {}
1291 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1292 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1294 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1295 if (IsPacked != That.IsPacked)
1297 if (ETypes != That.ETypes)
1302 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1303 return !this->operator==(That);
1306 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1307 return DenseMapInfo<StructType *>::getEmptyKey();
1310 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1311 return DenseMapInfo<StructType *>::getTombstoneKey();
1314 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1315 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1319 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1320 return getHashValue(KeyTy(ST));
1323 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1324 const StructType *RHS) {
1325 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1327 return LHS == KeyTy(RHS);
1330 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1331 const StructType *RHS) {
1332 if (RHS == getEmptyKey())
1333 return LHS == getEmptyKey();
1335 if (RHS == getTombstoneKey())
1336 return LHS == getTombstoneKey();
1338 return KeyTy(LHS) == KeyTy(RHS);
1341 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1342 assert(!Ty->isOpaque());
1343 NonOpaqueStructTypes.insert(Ty);
1346 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1347 assert(!Ty->isOpaque());
1348 NonOpaqueStructTypes.insert(Ty);
1349 bool Removed = OpaqueStructTypes.erase(Ty);
1354 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1355 assert(Ty->isOpaque());
1356 OpaqueStructTypes.insert(Ty);
1360 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1362 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1363 auto I = NonOpaqueStructTypes.find_as(Key);
1364 if (I == NonOpaqueStructTypes.end())
1369 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1371 return OpaqueStructTypes.count(Ty);
1372 auto I = NonOpaqueStructTypes.find(Ty);
1373 if (I == NonOpaqueStructTypes.end())
1378 IRMover::IRMover(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1379 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1380 TypeFinder StructTypes;
1381 StructTypes.run(M, true);
1382 for (StructType *Ty : StructTypes) {
1384 IdentifiedStructTypes.addOpaque(Ty);
1386 IdentifiedStructTypes.addNonOpaque(Ty);
1391 Module &Src, ArrayRef<GlobalValue *> ValuesToLink,
1392 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
1393 IRLinker TheLinker(Composite, IdentifiedStructTypes, Src, DiagnosticHandler,
1394 ValuesToLink, AddLazyFor);
1395 bool RetCode = TheLinker.run();
1396 Composite.dropTriviallyDeadConstantArrays();