[clang][bytecode][NFC] Only get expr when checking for UB (#125397)
[llvm-project.git] / llvm / lib / Linker / IRMover.cpp
blob62e2af4da57bbf9a79198d4acd649f6c67e070b1
1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Linker/IRMover.h"
10 #include "LinkDiagnosticInfo.h"
11 #include "llvm/ADT/ScopeExit.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfoMetadata.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GVMaterializer.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PseudoProbe.h"
27 #include "llvm/IR/TypeFinder.h"
28 #include "llvm/Object/ModuleSymbolTable.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/TargetParser/Triple.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
33 #include <optional>
34 #include <utility>
35 using namespace llvm;
37 /// Most of the errors produced by this module are inconvertible StringErrors.
38 /// This convenience function lets us return one of those more easily.
39 static Error stringErr(const Twine &T) {
40 return make_error<StringError>(T, inconvertibleErrorCode());
43 //===----------------------------------------------------------------------===//
44 // TypeMap implementation.
45 //===----------------------------------------------------------------------===//
47 namespace {
48 class TypeMapTy : public ValueMapTypeRemapper {
49 /// This is a mapping from a source type to a destination type to use.
50 DenseMap<Type *, Type *> MappedTypes;
52 /// When checking to see if two subgraphs are isomorphic, we speculatively
53 /// add types to MappedTypes, but keep track of them here in case we need to
54 /// roll back.
55 SmallVector<Type *, 16> SpeculativeTypes;
57 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
59 /// This is a list of non-opaque structs in the source module that are mapped
60 /// to an opaque struct in the destination module.
61 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
63 /// This is the set of opaque types in the destination modules who are
64 /// getting a body from the source module.
65 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
67 public:
68 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
69 : DstStructTypesSet(DstStructTypesSet) {}
71 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
72 /// Indicate that the specified type in the destination module is conceptually
73 /// equivalent to the specified type in the source module.
74 void addTypeMapping(Type *DstTy, Type *SrcTy);
76 /// Produce a body for an opaque type in the dest module from a type
77 /// definition in the source module.
78 Error linkDefinedTypeBodies();
80 /// Return the mapped type to use for the specified input type from the
81 /// source module.
82 Type *get(Type *SrcTy);
83 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
85 FunctionType *get(FunctionType *T) {
86 return cast<FunctionType>(get((Type *)T));
89 private:
90 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 assert(SpeculativeTypes.empty());
98 assert(SpeculativeDstOpaqueTypes.empty());
100 // Check to see if these types are recursively isomorphic and establish a
101 // mapping between them if so.
102 if (!areTypesIsomorphic(DstTy, SrcTy)) {
103 // Oops, they aren't isomorphic. Just discard this request by rolling out
104 // any speculative mappings we've established.
105 for (Type *Ty : SpeculativeTypes)
106 MappedTypes.erase(Ty);
108 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
109 SpeculativeDstOpaqueTypes.size());
110 for (StructType *Ty : SpeculativeDstOpaqueTypes)
111 DstResolvedOpaqueTypes.erase(Ty);
112 } else {
113 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
114 // and all its descendants to lower amount of renaming in LLVM context
115 // Renaming occurs because we load all source modules to the same context
116 // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
117 // As a result we may get several different types in the destination
118 // module, which are in fact the same.
119 for (Type *Ty : SpeculativeTypes)
120 if (auto *STy = dyn_cast<StructType>(Ty))
121 if (STy->hasName())
122 STy->setName("");
124 SpeculativeTypes.clear();
125 SpeculativeDstOpaqueTypes.clear();
128 /// Recursively walk this pair of types, returning true if they are isomorphic,
129 /// false if they are not.
130 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
131 // Two types with differing kinds are clearly not isomorphic.
132 if (DstTy->getTypeID() != SrcTy->getTypeID())
133 return false;
135 // If we have an entry in the MappedTypes table, then we have our answer.
136 Type *&Entry = MappedTypes[SrcTy];
137 if (Entry)
138 return Entry == DstTy;
140 // Two identical types are clearly isomorphic. Remember this
141 // non-speculatively.
142 if (DstTy == SrcTy) {
143 Entry = DstTy;
144 return true;
147 // Okay, we have two types with identical kinds that we haven't seen before.
149 // If this is an opaque struct type, special case it.
150 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
151 // Mapping an opaque type to any struct, just keep the dest struct.
152 if (SSTy->isOpaque()) {
153 Entry = DstTy;
154 SpeculativeTypes.push_back(SrcTy);
155 return true;
158 // Mapping a non-opaque source type to an opaque dest. If this is the first
159 // type that we're mapping onto this destination type then we succeed. Keep
160 // the dest, but fill it in later. If this is the second (different) type
161 // that we're trying to map onto the same opaque type then we fail.
162 if (cast<StructType>(DstTy)->isOpaque()) {
163 // We can only map one source type onto the opaque destination type.
164 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
165 return false;
166 SrcDefinitionsToResolve.push_back(SSTy);
167 SpeculativeTypes.push_back(SrcTy);
168 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
169 Entry = DstTy;
170 return true;
174 // If the number of subtypes disagree between the two types, then we fail.
175 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176 return false;
178 // Fail if any of the extra properties (e.g. array size) of the type disagree.
179 if (isa<IntegerType>(DstTy))
180 return false; // bitwidth disagrees.
181 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183 return false;
184 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
185 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
186 return false;
187 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
188 StructType *SSTy = cast<StructType>(SrcTy);
189 if (DSTy->isLiteral() != SSTy->isLiteral() ||
190 DSTy->isPacked() != SSTy->isPacked())
191 return false;
192 } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
193 if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
194 return false;
195 } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
196 if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
197 return false;
200 // Otherwise, we speculate that these two types will line up and recursively
201 // check the subelements.
202 Entry = DstTy;
203 SpeculativeTypes.push_back(SrcTy);
205 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
206 if (!areTypesIsomorphic(DstTy->getContainedType(I),
207 SrcTy->getContainedType(I)))
208 return false;
210 // If everything seems to have lined up, then everything is great.
211 return true;
214 Error TypeMapTy::linkDefinedTypeBodies() {
215 SmallVector<Type *, 16> Elements;
216 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
217 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
218 assert(DstSTy->isOpaque());
220 // Map the body of the source type over to a new body for the dest type.
221 Elements.resize(SrcSTy->getNumElements());
222 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
223 Elements[I] = get(SrcSTy->getElementType(I));
225 if (auto E = DstSTy->setBodyOrError(Elements, SrcSTy->isPacked()))
226 return E;
227 DstStructTypesSet.switchToNonOpaque(DstSTy);
229 SrcDefinitionsToResolve.clear();
230 DstResolvedOpaqueTypes.clear();
231 return Error::success();
234 Type *TypeMapTy::get(Type *Ty) {
235 SmallPtrSet<StructType *, 8> Visited;
236 return get(Ty, Visited);
239 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
240 // If we already have an entry for this type, return it.
241 Type **Entry = &MappedTypes[Ty];
242 if (*Entry)
243 return *Entry;
245 // These are types that LLVM itself will unique.
246 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
248 if (!IsUniqued) {
249 #ifndef NDEBUG
250 for (auto &Pair : MappedTypes) {
251 assert(!(Pair.first != Ty && Pair.second == Ty) &&
252 "mapping to a source type");
254 #endif
256 if (!Visited.insert(cast<StructType>(Ty)).second) {
257 StructType *DTy = StructType::create(Ty->getContext());
258 return *Entry = DTy;
262 // If this is not a recursive type, then just map all of the elements and
263 // then rebuild the type from inside out.
264 SmallVector<Type *, 4> ElementTypes;
266 // If there are no element types to map, then the type is itself. This is
267 // true for the anonymous {} struct, things like 'float', integers, etc.
268 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
269 return *Entry = Ty;
271 // Remap all of the elements, keeping track of whether any of them change.
272 bool AnyChange = false;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
275 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
276 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
279 // Refresh Entry after recursively processing stuff.
280 Entry = &MappedTypes[Ty];
281 assert(!*Entry && "Recursive type!");
283 // If all of the element types mapped directly over and the type is not
284 // a named struct, then the type is usable as-is.
285 if (!AnyChange && IsUniqued)
286 return *Entry = Ty;
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
290 default:
291 llvm_unreachable("unknown derived type to remap");
292 case Type::ArrayTyID:
293 return *Entry = ArrayType::get(ElementTypes[0],
294 cast<ArrayType>(Ty)->getNumElements());
295 case Type::ScalableVectorTyID:
296 case Type::FixedVectorTyID:
297 return *Entry = VectorType::get(ElementTypes[0],
298 cast<VectorType>(Ty)->getElementCount());
299 case Type::FunctionTyID:
300 return *Entry = FunctionType::get(ElementTypes[0],
301 ArrayRef(ElementTypes).slice(1),
302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID: {
304 auto *STy = cast<StructType>(Ty);
305 bool IsPacked = STy->isPacked();
306 if (IsUniqued)
307 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
309 // If the type is opaque, we can just use it directly.
310 if (STy->isOpaque()) {
311 DstStructTypesSet.addOpaque(STy);
312 return *Entry = Ty;
315 if (StructType *OldT =
316 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
317 STy->setName("");
318 return *Entry = OldT;
321 if (!AnyChange) {
322 DstStructTypesSet.addNonOpaque(STy);
323 return *Entry = Ty;
326 StructType *DTy =
327 StructType::create(Ty->getContext(), ElementTypes, "", STy->isPacked());
329 // Steal STy's name.
330 if (STy->hasName()) {
331 SmallString<16> TmpName = STy->getName();
332 STy->setName("");
333 DTy->setName(TmpName);
336 DstStructTypesSet.addNonOpaque(DTy);
337 return *Entry = DTy;
342 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
343 const Twine &Msg)
344 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
345 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
347 //===----------------------------------------------------------------------===//
348 // IRLinker implementation.
349 //===----------------------------------------------------------------------===//
351 namespace {
352 class IRLinker;
354 /// Creates prototypes for functions that are lazily linked on the fly. This
355 /// speeds up linking for modules with many/ lazily linked functions of which
356 /// few get used.
357 class GlobalValueMaterializer final : public ValueMaterializer {
358 IRLinker &TheIRLinker;
360 public:
361 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
362 Value *materialize(Value *V) override;
365 class LocalValueMaterializer final : public ValueMaterializer {
366 IRLinker &TheIRLinker;
368 public:
369 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
370 Value *materialize(Value *V) override;
373 /// Type of the Metadata map in \a ValueToValueMapTy.
374 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
376 /// This is responsible for keeping track of the state used for moving data
377 /// from SrcM to DstM.
378 class IRLinker {
379 Module &DstM;
380 std::unique_ptr<Module> SrcM;
382 /// See IRMover::move().
383 IRMover::LazyCallback AddLazyFor;
385 TypeMapTy TypeMap;
386 GlobalValueMaterializer GValMaterializer;
387 LocalValueMaterializer LValMaterializer;
389 /// A metadata map that's shared between IRLinker instances.
390 MDMapT &SharedMDs;
392 /// Mapping of values from what they used to be in Src, to what they are now
393 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
394 /// due to the use of Value handles which the Linker doesn't actually need,
395 /// but this allows us to reuse the ValueMapper code.
396 ValueToValueMapTy ValueMap;
397 ValueToValueMapTy IndirectSymbolValueMap;
399 DenseSet<GlobalValue *> ValuesToLink;
400 std::vector<GlobalValue *> Worklist;
401 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
403 /// Set of globals with eagerly copied metadata that may require remapping.
404 /// This remapping is performed after metadata linking.
405 DenseSet<GlobalObject *> UnmappedMetadata;
407 void maybeAdd(GlobalValue *GV) {
408 if (ValuesToLink.insert(GV).second)
409 Worklist.push_back(GV);
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;
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;
424 /// The Error encountered during materialization. We use an Optional here to
425 /// avoid needing to manage an unconsumed success value.
426 std::optional<Error> FoundError;
427 void setError(Error E) {
428 if (E)
429 FoundError = std::move(E);
432 /// Entry point for mapping values and alternate context for mapping aliases.
433 ValueMapper Mapper;
434 unsigned IndirectSymbolMCID;
436 /// Handles cloning of a global values from the source module into
437 /// the destination module, including setting the attributes and visibility.
438 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
440 void emitWarning(const Twine &Message) {
441 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
444 /// Given a global in the source module, return the global in the
445 /// destination module that is being linked to, if any.
446 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
447 // If the source has no name it can't link. If it has local linkage,
448 // there is no name match-up going on.
449 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
450 return nullptr;
452 // Otherwise see if we have a match in the destination module's symtab.
453 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
454 if (!DGV)
455 return nullptr;
457 // If we found a global with the same name in the dest module, but it has
458 // internal linkage, we are really not doing any linkage here.
459 if (DGV->hasLocalLinkage())
460 return nullptr;
462 // If we found an intrinsic declaration with mismatching prototypes, we
463 // probably had a nameclash. Don't use that version.
464 if (auto *FDGV = dyn_cast<Function>(DGV))
465 if (FDGV->isIntrinsic())
466 if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
467 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
468 return nullptr;
470 // Otherwise, we do in fact link to the destination global.
471 return DGV;
474 void computeTypeMapping();
476 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
477 const GlobalVariable *SrcGV);
479 /// Given the GlobaValue \p SGV in the source module, and the matching
480 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
481 /// into the destination module.
483 /// Note this code may call the client-provided \p AddLazyFor.
484 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
485 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
486 bool ForIndirectSymbol);
488 Error linkModuleFlagsMetadata();
490 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
491 Error linkFunctionBody(Function &Dst, Function &Src);
492 void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
493 void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
494 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
496 /// Replace all types in the source AttributeList with the
497 /// corresponding destination type.
498 AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
500 /// Functions that take care of cloning a specific global value type
501 /// into the destination module.
502 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503 Function *copyFunctionProto(const Function *SF);
504 GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
506 /// Perform "replace all uses with" operations. These work items need to be
507 /// performed as part of materialization, but we postpone them to happen after
508 /// materialization is done. The materializer called by ValueMapper is not
509 /// expected to delete constants, as ValueMapper is holding pointers to some
510 /// of them, but constant destruction may be indirectly triggered by RAUW.
511 /// Hence, the need to move this out of the materialization call chain.
512 void flushRAUWWorklist();
514 /// When importing for ThinLTO, prevent importing of types listed on
515 /// the DICompileUnit that we don't need a copy of in the importing
516 /// module.
517 void prepareCompileUnitsForImport();
518 void linkNamedMDNodes();
520 /// Update attributes while linking.
521 void updateAttributes(GlobalValue &GV);
523 public:
524 IRLinker(Module &DstM, MDMapT &SharedMDs,
525 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
526 ArrayRef<GlobalValue *> ValuesToLink,
527 IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
528 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
529 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
530 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
531 Mapper(ValueMap, RF_ReuseAndMutateDistinctMDs | RF_IgnoreMissingLocals,
532 &TypeMap, &GValMaterializer),
533 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
534 IndirectSymbolValueMap, &LValMaterializer)) {
535 ValueMap.getMDMap() = std::move(SharedMDs);
536 for (GlobalValue *GV : ValuesToLink)
537 maybeAdd(GV);
538 if (IsPerformingImport)
539 prepareCompileUnitsForImport();
541 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
543 Error run();
544 Value *materialize(Value *V, bool ForIndirectSymbol);
548 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
549 /// table. This is good for all clients except for us. Go through the trouble
550 /// to force this back.
551 static void forceRenaming(GlobalValue *GV, StringRef Name) {
552 // If the global doesn't force its name or if it already has the right name,
553 // there is nothing for us to do.
554 if (GV->hasLocalLinkage() || GV->getName() == Name)
555 return;
557 Module *M = GV->getParent();
559 // If there is a conflict, rename the conflict.
560 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
561 GV->takeName(ConflictGV);
562 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
563 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
564 } else {
565 GV->setName(Name); // Force the name back
569 Value *GlobalValueMaterializer::materialize(Value *SGV) {
570 return TheIRLinker.materialize(SGV, false);
573 Value *LocalValueMaterializer::materialize(Value *SGV) {
574 return TheIRLinker.materialize(SGV, true);
577 Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
578 auto *SGV = dyn_cast<GlobalValue>(V);
579 if (!SGV)
580 return nullptr;
582 // If SGV is from dest, it was already materialized when dest was loaded.
583 if (SGV->getParent() == &DstM)
584 return nullptr;
586 // When linking a global from other modules than source & dest, skip
587 // materializing it because it would be mapped later when its containing
588 // module is linked. Linking it now would potentially pull in many types that
589 // may not be mapped properly.
590 if (SGV->getParent() != SrcM.get())
591 return nullptr;
593 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
594 if (!NewProto) {
595 setError(NewProto.takeError());
596 return nullptr;
598 if (!*NewProto)
599 return nullptr;
601 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
602 if (!New)
603 return *NewProto;
605 // If we already created the body, just return.
606 if (auto *F = dyn_cast<Function>(New)) {
607 if (!F->isDeclaration())
608 return New;
609 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
610 if (V->hasInitializer() || V->hasAppendingLinkage())
611 return New;
612 } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
613 if (GA->getAliasee())
614 return New;
615 } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
616 if (GI->getResolver())
617 return New;
618 } else {
619 llvm_unreachable("Invalid GlobalValue type");
622 // If the global is being linked for an indirect symbol, it may have already
623 // been scheduled to satisfy a regular symbol. Similarly, a global being linked
624 // for a regular symbol may have already been scheduled for an indirect
625 // symbol. Check for these cases by looking in the other value map and
626 // confirming the same value has been scheduled. If there is an entry in the
627 // ValueMap but the value is different, it means that the value already had a
628 // definition in the destination module (linkonce for instance), but we need a
629 // new definition for the indirect symbol ("New" will be different).
630 if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
631 (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
632 return New;
634 if (ForIndirectSymbol || shouldLink(New, *SGV))
635 setError(linkGlobalValueBody(*New, *SGV));
637 updateAttributes(*New);
638 return New;
641 /// Loop through the global variables in the src module and merge them into the
642 /// dest module.
643 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
644 // No linking to be performed or linking from the source: simply create an
645 // identical version of the symbol over in the dest module... the
646 // initializer will be filled in later by LinkGlobalInits.
647 GlobalVariable *NewDGV =
648 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
649 SGVar->isConstant(), GlobalValue::ExternalLinkage,
650 /*init*/ nullptr, SGVar->getName(),
651 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
652 SGVar->getAddressSpace());
653 NewDGV->setAlignment(SGVar->getAlign());
654 NewDGV->copyAttributesFrom(SGVar);
655 return NewDGV;
658 AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
659 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
660 for (int AttrIdx = Attribute::FirstTypeAttr;
661 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
662 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
663 if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
664 if (Type *Ty =
665 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
666 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
667 TypeMap.get(Ty));
668 break;
673 return Attrs;
676 /// Link the function in the source module into the destination module if
677 /// needed, setting up mapping information.
678 Function *IRLinker::copyFunctionProto(const Function *SF) {
679 // If there is no linkage to be performed or we are linking from the source,
680 // bring SF over.
681 auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
682 GlobalValue::ExternalLinkage,
683 SF->getAddressSpace(), SF->getName(), &DstM);
684 F->copyAttributesFrom(SF);
685 F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
686 F->IsNewDbgInfoFormat = SF->IsNewDbgInfoFormat;
687 return F;
690 /// Set up prototypes for any indirect symbols that come over from the source
691 /// module.
692 GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
693 // If there is no linkage to be performed or we're linking from the source,
694 // bring over SGA.
695 auto *Ty = TypeMap.get(SGV->getValueType());
697 if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
698 auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
699 GlobalValue::ExternalLinkage,
700 SGV->getName(), &DstM);
701 DGA->copyAttributesFrom(GA);
702 return DGA;
705 if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
706 auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
707 GlobalValue::ExternalLinkage,
708 SGV->getName(), nullptr, &DstM);
709 DGI->copyAttributesFrom(GI);
710 return DGI;
713 llvm_unreachable("Invalid source global value type");
716 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
717 bool ForDefinition) {
718 GlobalValue *NewGV;
719 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
720 NewGV = copyGlobalVariableProto(SGVar);
721 } else if (auto *SF = dyn_cast<Function>(SGV)) {
722 NewGV = copyFunctionProto(SF);
723 } else {
724 if (ForDefinition)
725 NewGV = copyIndirectSymbolProto(SGV);
726 else if (SGV->getValueType()->isFunctionTy())
727 NewGV =
728 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
729 GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
730 SGV->getName(), &DstM);
731 else
732 NewGV =
733 new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
734 /*isConstant*/ false, GlobalValue::ExternalLinkage,
735 /*init*/ nullptr, SGV->getName(),
736 /*insertbefore*/ nullptr,
737 SGV->getThreadLocalMode(), SGV->getAddressSpace());
740 if (ForDefinition)
741 NewGV->setLinkage(SGV->getLinkage());
742 else if (SGV->hasExternalWeakLinkage())
743 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
745 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
746 // Metadata for global variables and function declarations is copied eagerly.
747 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) {
748 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
749 if (SGV->isDeclaration() && NewGO->hasMetadata())
750 UnmappedMetadata.insert(NewGO);
754 // Remove these copied constants in case this stays a declaration, since
755 // they point to the source module. If the def is linked the values will
756 // be mapped in during linkFunctionBody.
757 if (auto *NewF = dyn_cast<Function>(NewGV)) {
758 NewF->setPersonalityFn(nullptr);
759 NewF->setPrefixData(nullptr);
760 NewF->setPrologueData(nullptr);
763 return NewGV;
766 static StringRef getTypeNamePrefix(StringRef Name) {
767 size_t DotPos = Name.rfind('.');
768 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
769 !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
770 ? Name
771 : Name.substr(0, DotPos);
774 /// Loop over all of the linked values to compute type mappings. For example,
775 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
776 /// types 'Foo' but one got renamed when the module was loaded into the same
777 /// LLVMContext.
778 void IRLinker::computeTypeMapping() {
779 for (GlobalValue &SGV : SrcM->globals()) {
780 GlobalValue *DGV = getLinkedToGlobal(&SGV);
781 if (!DGV)
782 continue;
784 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
785 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
786 continue;
789 // Unify the element type of appending arrays.
790 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
791 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
792 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
795 for (GlobalValue &SGV : *SrcM)
796 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
797 if (DGV->getType() == SGV.getType()) {
798 // If the types of DGV and SGV are the same, it means that DGV is from
799 // the source module and got added to DstM from a shared metadata. We
800 // shouldn't map this type to itself in case the type's components get
801 // remapped to a new type from DstM (for instance, during the loop over
802 // SrcM->getIdentifiedStructTypes() below).
803 continue;
806 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
809 for (GlobalValue &SGV : SrcM->aliases())
810 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
811 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
813 // Incorporate types by name, scanning all the types in the source module.
814 // At this point, the destination module may have a type "%foo = { i32 }" for
815 // example. When the source module got loaded into the same LLVMContext, if
816 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
817 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
818 for (StructType *ST : Types) {
819 if (!ST->hasName())
820 continue;
822 if (TypeMap.DstStructTypesSet.hasType(ST)) {
823 // This is actually a type from the destination module.
824 // getIdentifiedStructTypes() can have found it by walking debug info
825 // metadata nodes, some of which get linked by name when ODR Type Uniquing
826 // is enabled on the Context, from the source to the destination module.
827 continue;
830 auto STTypePrefix = getTypeNamePrefix(ST->getName());
831 if (STTypePrefix.size() == ST->getName().size())
832 continue;
834 // Check to see if the destination module has a struct with the prefix name.
835 StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
836 if (!DST)
837 continue;
839 // Don't use it if this actually came from the source module. They're in
840 // the same LLVMContext after all. Also don't use it unless the type is
841 // actually used in the destination module. This can happen in situations
842 // like this:
844 // Module A Module B
845 // -------- --------
846 // %Z = type { %A } %B = type { %C.1 }
847 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
848 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
849 // %C = type { i8* } %B.3 = type { %C.1 }
851 // When we link Module B with Module A, the '%B' in Module B is
852 // used. However, that would then use '%C.1'. But when we process '%C.1',
853 // we prefer to take the '%C' version. So we are then left with both
854 // '%C.1' and '%C' being used for the same types. This leads to some
855 // variables using one type and some using the other.
856 if (TypeMap.DstStructTypesSet.hasType(DST))
857 TypeMap.addTypeMapping(DST, ST);
860 // Now that we have discovered all of the type equivalences, get a body for
861 // any 'opaque' types in the dest module that are now resolved.
862 setError(TypeMap.linkDefinedTypeBodies());
865 static void getArrayElements(const Constant *C,
866 SmallVectorImpl<Constant *> &Dest) {
867 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
869 for (unsigned i = 0; i != NumElements; ++i)
870 Dest.push_back(C->getAggregateElement(i));
873 /// If there were any appending global variables, link them together now.
874 Expected<Constant *>
875 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
876 const GlobalVariable *SrcGV) {
877 // Check that both variables have compatible properties.
878 if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
879 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
880 return stringErr(
881 "Linking globals named '" + SrcGV->getName() +
882 "': can only link appending global with another appending "
883 "global!");
885 if (DstGV->isConstant() != SrcGV->isConstant())
886 return stringErr("Appending variables linked with different const'ness!");
888 if (DstGV->getAlign() != SrcGV->getAlign())
889 return stringErr(
890 "Appending variables with different alignment need to be linked!");
892 if (DstGV->getVisibility() != SrcGV->getVisibility())
893 return stringErr(
894 "Appending variables with different visibility need to be linked!");
896 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
897 return stringErr(
898 "Appending variables with different unnamed_addr need to be linked!");
900 if (DstGV->getSection() != SrcGV->getSection())
901 return stringErr(
902 "Appending variables with different section name need to be linked!");
904 if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
905 return stringErr("Appending variables with different address spaces need "
906 "to be linked!");
909 // Do not need to do anything if source is a declaration.
910 if (SrcGV->isDeclaration())
911 return DstGV;
913 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
914 ->getElementType();
916 // FIXME: This upgrade is done during linking to support the C API. Once the
917 // old form is deprecated, we should move this upgrade to
918 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
919 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
920 StringRef Name = SrcGV->getName();
921 bool IsNewStructor = false;
922 bool IsOldStructor = false;
923 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
924 if (cast<StructType>(EltTy)->getNumElements() == 3)
925 IsNewStructor = true;
926 else
927 IsOldStructor = true;
930 PointerType *VoidPtrTy = PointerType::get(SrcGV->getContext(), 0);
931 if (IsOldStructor) {
932 auto &ST = *cast<StructType>(EltTy);
933 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
934 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
937 uint64_t DstNumElements = 0;
938 if (DstGV && !DstGV->isDeclaration()) {
939 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
940 DstNumElements = DstTy->getNumElements();
942 // Check to see that they two arrays agree on type.
943 if (EltTy != DstTy->getElementType())
944 return stringErr("Appending variables with different element types!");
947 SmallVector<Constant *, 16> SrcElements;
948 getArrayElements(SrcGV->getInitializer(), SrcElements);
950 if (IsNewStructor) {
951 erase_if(SrcElements, [this](Constant *E) {
952 auto *Key =
953 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
954 if (!Key)
955 return false;
956 GlobalValue *DGV = getLinkedToGlobal(Key);
957 return !shouldLink(DGV, *Key);
960 uint64_t NewSize = DstNumElements + SrcElements.size();
961 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
963 // Create the new global variable.
964 GlobalVariable *NG = new GlobalVariable(
965 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
966 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
967 SrcGV->getAddressSpace());
969 NG->copyAttributesFrom(SrcGV);
970 forceRenaming(NG, SrcGV->getName());
972 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
974 Mapper.scheduleMapAppendingVariable(
975 *NG,
976 (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
977 IsOldStructor, SrcElements);
979 // Replace any uses of the two global variables with uses of the new
980 // global.
981 if (DstGV) {
982 RAUWWorklist.push_back(std::make_pair(DstGV, NG));
985 return Ret;
988 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
989 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
990 return true;
992 if (DGV && !DGV->isDeclarationForLinker())
993 return false;
995 if (SGV.isDeclaration() || DoneLinkingBodies)
996 return false;
998 // Callback to the client to give a chance to lazily add the Global to the
999 // list of value to link.
1000 bool LazilyAdded = false;
1001 if (AddLazyFor)
1002 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1003 maybeAdd(&GV);
1004 LazilyAdded = true;
1006 return LazilyAdded;
1009 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1010 bool ForIndirectSymbol) {
1011 GlobalValue *DGV = getLinkedToGlobal(SGV);
1013 bool ShouldLink = shouldLink(DGV, *SGV);
1015 // just missing from map
1016 if (ShouldLink) {
1017 auto I = ValueMap.find(SGV);
1018 if (I != ValueMap.end())
1019 return cast<Constant>(I->second);
1021 I = IndirectSymbolValueMap.find(SGV);
1022 if (I != IndirectSymbolValueMap.end())
1023 return cast<Constant>(I->second);
1026 if (!ShouldLink && ForIndirectSymbol)
1027 DGV = nullptr;
1029 // Handle the ultra special appending linkage case first.
1030 if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
1031 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1032 cast<GlobalVariable>(SGV));
1034 bool NeedsRenaming = false;
1035 GlobalValue *NewGV;
1036 if (DGV && !ShouldLink) {
1037 NewGV = DGV;
1038 } else {
1039 // If we are done linking global value bodies (i.e. we are performing
1040 // metadata linking), don't link in the global value due to this
1041 // reference, simply map it to null.
1042 if (DoneLinkingBodies)
1043 return nullptr;
1045 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1046 if (ShouldLink || !ForIndirectSymbol)
1047 NeedsRenaming = true;
1050 // Overloaded intrinsics have overloaded types names as part of their
1051 // names. If we renamed overloaded types we should rename the intrinsic
1052 // as well.
1053 if (Function *F = dyn_cast<Function>(NewGV))
1054 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
1055 // Note: remangleIntrinsicFunction does not copy metadata and as such
1056 // F should not occur in the set of objects with unmapped metadata.
1057 // If this assertion fails then remangleIntrinsicFunction needs updating.
1058 assert(!UnmappedMetadata.count(F) && "intrinsic has unmapped metadata");
1059 NewGV->eraseFromParent();
1060 NewGV = *Remangled;
1061 NeedsRenaming = false;
1064 if (NeedsRenaming)
1065 forceRenaming(NewGV, SGV->getName());
1067 if (ShouldLink || ForIndirectSymbol) {
1068 if (const Comdat *SC = SGV->getComdat()) {
1069 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1070 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1071 DC->setSelectionKind(SC->getSelectionKind());
1072 GO->setComdat(DC);
1077 if (!ShouldLink && ForIndirectSymbol)
1078 NewGV->setLinkage(GlobalValue::InternalLinkage);
1080 Constant *C = NewGV;
1081 // Only create a bitcast if necessary. In particular, with
1082 // DebugTypeODRUniquing we may reach metadata in the destination module
1083 // containing a GV from the source module, in which case SGV will be
1084 // the same as DGV and NewGV, and TypeMap.get() will assert since it
1085 // assumes it is being invoked on a type in the source module.
1086 if (DGV && NewGV != SGV) {
1087 C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1088 NewGV, TypeMap.get(SGV->getType()));
1091 if (DGV && NewGV != DGV) {
1092 // Schedule "replace all uses with" to happen after materializing is
1093 // done. It is not safe to do it now, since ValueMapper may be holding
1094 // pointers to constants that will get deleted if RAUW runs.
1095 RAUWWorklist.push_back(std::make_pair(
1096 DGV,
1097 ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
1100 return C;
1103 /// Update the initializers in the Dest module now that all globals that may be
1104 /// referenced are in Dest.
1105 void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1106 // Figure out what the initializer looks like in the dest module.
1107 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1110 /// Copy the source function over into the dest function and fix up references
1111 /// to values. At this point we know that Dest is an external function, and
1112 /// that Src is not.
1113 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1114 assert(Dst.isDeclaration() && !Src.isDeclaration());
1116 // Materialize if needed.
1117 if (Error Err = Src.materialize())
1118 return Err;
1120 // Link in the operands without remapping.
1121 if (Src.hasPrefixData())
1122 Dst.setPrefixData(Src.getPrefixData());
1123 if (Src.hasPrologueData())
1124 Dst.setPrologueData(Src.getPrologueData());
1125 if (Src.hasPersonalityFn())
1126 Dst.setPersonalityFn(Src.getPersonalityFn());
1127 assert(Src.IsNewDbgInfoFormat == Dst.IsNewDbgInfoFormat);
1129 // Copy over the metadata attachments without remapping.
1130 Dst.copyMetadata(&Src, 0);
1132 // Steal arguments and splice the body of Src into Dst.
1133 Dst.stealArgumentListFrom(Src);
1134 Dst.splice(Dst.end(), &Src);
1136 // Everything has been moved over. Remap it.
1137 Mapper.scheduleRemapFunction(Dst);
1138 return Error::success();
1141 void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1142 Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1145 void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1146 Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1149 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1150 if (auto *F = dyn_cast<Function>(&Src))
1151 return linkFunctionBody(cast<Function>(Dst), *F);
1152 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1153 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1154 return Error::success();
1156 if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1157 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1158 return Error::success();
1160 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1161 return Error::success();
1164 void IRLinker::flushRAUWWorklist() {
1165 for (const auto &Elem : RAUWWorklist) {
1166 GlobalValue *Old;
1167 Value *New;
1168 std::tie(Old, New) = Elem;
1170 Old->replaceAllUsesWith(New);
1171 Old->eraseFromParent();
1173 RAUWWorklist.clear();
1176 void IRLinker::prepareCompileUnitsForImport() {
1177 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1178 if (!SrcCompileUnits)
1179 return;
1180 // When importing for ThinLTO, prevent importing of types listed on
1181 // the DICompileUnit that we don't need a copy of in the importing
1182 // module. They will be emitted by the originating module.
1183 for (MDNode *N : SrcCompileUnits->operands()) {
1184 auto *CU = cast<DICompileUnit>(N);
1185 assert(CU && "Expected valid compile unit");
1186 // Enums, macros, and retained types don't need to be listed on the
1187 // imported DICompileUnit. This means they will only be imported
1188 // if reached from the mapped IR.
1189 CU->replaceEnumTypes(nullptr);
1190 CU->replaceMacros(nullptr);
1191 CU->replaceRetainedTypes(nullptr);
1193 // The original definition (or at least its debug info - if the variable is
1194 // internalized and optimized away) will remain in the source module, so
1195 // there's no need to import them.
1196 // If LLVM ever does more advanced optimizations on global variables
1197 // (removing/localizing write operations, for instance) that can track
1198 // through debug info, this decision may need to be revisited - but do so
1199 // with care when it comes to debug info size. Emitting small CUs containing
1200 // only a few imported entities into every destination module may be very
1201 // size inefficient.
1202 CU->replaceGlobalVariables(nullptr);
1204 CU->replaceImportedEntities(nullptr);
1208 /// Insert all of the named MDNodes in Src into the Dest module.
1209 void IRLinker::linkNamedMDNodes() {
1210 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1211 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1212 // Don't link module flags here. Do them separately.
1213 if (&NMD == SrcModFlags)
1214 continue;
1215 // Don't import pseudo probe descriptors here for thinLTO. They will be
1216 // emitted by the originating module.
1217 if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
1218 if (!DstM.getNamedMetadata(NMD.getName()))
1219 emitWarning("Pseudo-probe ignored: source module '" +
1220 SrcM->getModuleIdentifier() +
1221 "' is compiled with -fpseudo-probe-for-profiling while "
1222 "destination module '" +
1223 DstM.getModuleIdentifier() + "' is not\n");
1224 continue;
1226 // The stats are computed per module and will all be merged in the binary.
1227 // Importing the metadata will cause duplication of the stats.
1228 if (IsPerformingImport && NMD.getName() == "llvm.stats")
1229 continue;
1231 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1232 // Add Src elements into Dest node.
1233 for (const MDNode *Op : NMD.operands())
1234 DestNMD->addOperand(Mapper.mapMDNode(*Op));
1238 /// Merge the linker flags in Src into the Dest module.
1239 Error IRLinker::linkModuleFlagsMetadata() {
1240 // If the source module has no module flags, we are done.
1241 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1242 if (!SrcModFlags)
1243 return Error::success();
1245 // Check for module flag for updates before do anything.
1246 UpgradeModuleFlags(*SrcM);
1247 UpgradeNVVMAnnotations(*SrcM);
1249 // If the destination module doesn't have module flags yet, then just copy
1250 // over the source module's flags.
1251 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1252 if (DstModFlags->getNumOperands() == 0) {
1253 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1254 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1256 return Error::success();
1259 // First build a map of the existing module flags and requirements.
1260 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1261 SmallSetVector<MDNode *, 16> Requirements;
1262 SmallVector<unsigned, 0> Mins;
1263 DenseSet<MDString *> SeenMin;
1264 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1265 MDNode *Op = DstModFlags->getOperand(I);
1266 uint64_t Behavior =
1267 mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1268 MDString *ID = cast<MDString>(Op->getOperand(1));
1270 if (Behavior == Module::Require) {
1271 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1272 } else {
1273 if (Behavior == Module::Min)
1274 Mins.push_back(I);
1275 Flags[ID] = std::make_pair(Op, I);
1279 // Merge in the flags from the source module, and also collect its set of
1280 // requirements.
1281 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1282 MDNode *SrcOp = SrcModFlags->getOperand(I);
1283 ConstantInt *SrcBehavior =
1284 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1285 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1286 MDNode *DstOp;
1287 unsigned DstIndex;
1288 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1289 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1290 SeenMin.insert(ID);
1292 // If this is a requirement, add it and continue.
1293 if (SrcBehaviorValue == Module::Require) {
1294 // If the destination module does not already have this requirement, add
1295 // it.
1296 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1297 DstModFlags->addOperand(SrcOp);
1299 continue;
1302 // If there is no existing flag with this ID, just add it.
1303 if (!DstOp) {
1304 if (SrcBehaviorValue == Module::Min) {
1305 Mins.push_back(DstModFlags->getNumOperands());
1306 SeenMin.erase(ID);
1308 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1309 DstModFlags->addOperand(SrcOp);
1310 continue;
1313 // Otherwise, perform a merge.
1314 ConstantInt *DstBehavior =
1315 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1316 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1318 auto overrideDstValue = [&]() {
1319 DstModFlags->setOperand(DstIndex, SrcOp);
1320 Flags[ID].first = SrcOp;
1323 // If either flag has override behavior, handle it first.
1324 if (DstBehaviorValue == Module::Override) {
1325 // Diagnose inconsistent flags which both have override behavior.
1326 if (SrcBehaviorValue == Module::Override &&
1327 SrcOp->getOperand(2) != DstOp->getOperand(2))
1328 return stringErr("linking module flags '" + ID->getString() +
1329 "': IDs have conflicting override values in '" +
1330 SrcM->getModuleIdentifier() + "' and '" +
1331 DstM.getModuleIdentifier() + "'");
1332 continue;
1333 } else if (SrcBehaviorValue == Module::Override) {
1334 // Update the destination flag to that of the source.
1335 overrideDstValue();
1336 continue;
1339 // Diagnose inconsistent merge behavior types.
1340 if (SrcBehaviorValue != DstBehaviorValue) {
1341 bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1342 DstBehaviorValue == Module::Warning) ||
1343 (DstBehaviorValue == Module::Min &&
1344 SrcBehaviorValue == Module::Warning);
1345 bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1346 DstBehaviorValue == Module::Warning) ||
1347 (DstBehaviorValue == Module::Max &&
1348 SrcBehaviorValue == Module::Warning);
1349 if (!(MaxAndWarn || MinAndWarn))
1350 return stringErr("linking module flags '" + ID->getString() +
1351 "': IDs have conflicting behaviors in '" +
1352 SrcM->getModuleIdentifier() + "' and '" +
1353 DstM.getModuleIdentifier() + "'");
1356 auto ensureDistinctOp = [&](MDNode *DstValue) {
1357 assert(isa<MDTuple>(DstValue) &&
1358 "Expected MDTuple when appending module flags");
1359 if (DstValue->isDistinct())
1360 return dyn_cast<MDTuple>(DstValue);
1361 ArrayRef<MDOperand> DstOperands = DstValue->operands();
1362 MDTuple *New = MDTuple::getDistinct(
1363 DstM.getContext(), SmallVector<Metadata *, 4>(DstOperands));
1364 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1365 MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1366 DstModFlags->setOperand(DstIndex, Flag);
1367 Flags[ID].first = Flag;
1368 return New;
1371 // Emit a warning if the values differ and either source or destination
1372 // request Warning behavior.
1373 if ((DstBehaviorValue == Module::Warning ||
1374 SrcBehaviorValue == Module::Warning) &&
1375 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1376 std::string Str;
1377 raw_string_ostream(Str)
1378 << "linking module flags '" << ID->getString()
1379 << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1380 << "' from " << SrcM->getModuleIdentifier() << " with '"
1381 << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1382 << ')';
1383 emitWarning(Str);
1386 // Choose the minimum if either source or destination request Min behavior.
1387 if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1388 ConstantInt *DstValue =
1389 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1390 ConstantInt *SrcValue =
1391 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1393 // The resulting flag should have a Min behavior, and contain the minimum
1394 // value from between the source and destination values.
1395 Metadata *FlagOps[] = {
1396 (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1397 (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1398 ->getOperand(2)};
1399 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1400 DstModFlags->setOperand(DstIndex, Flag);
1401 Flags[ID].first = Flag;
1402 continue;
1405 // Choose the maximum if either source or destination request Max behavior.
1406 if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1407 ConstantInt *DstValue =
1408 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1409 ConstantInt *SrcValue =
1410 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1412 // The resulting flag should have a Max behavior, and contain the maximum
1413 // value from between the source and destination values.
1414 Metadata *FlagOps[] = {
1415 (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1416 (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1417 ->getOperand(2)};
1418 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1419 DstModFlags->setOperand(DstIndex, Flag);
1420 Flags[ID].first = Flag;
1421 continue;
1424 // Perform the merge for standard behavior types.
1425 switch (SrcBehaviorValue) {
1426 case Module::Require:
1427 case Module::Override:
1428 llvm_unreachable("not possible");
1429 case Module::Error: {
1430 // Emit an error if the values differ.
1431 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1432 std::string Str;
1433 raw_string_ostream(Str)
1434 << "linking module flags '" << ID->getString()
1435 << "': IDs have conflicting values: '" << *SrcOp->getOperand(2)
1436 << "' from " << SrcM->getModuleIdentifier() << ", and '"
1437 << *DstOp->getOperand(2) << "' from " + DstM.getModuleIdentifier();
1438 return stringErr(Str);
1440 continue;
1442 case Module::Warning: {
1443 break;
1445 case Module::Max: {
1446 break;
1448 case Module::Append: {
1449 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1450 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1451 for (const auto &O : SrcValue->operands())
1452 DstValue->push_back(O);
1453 break;
1455 case Module::AppendUnique: {
1456 SmallSetVector<Metadata *, 16> Elts;
1457 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1458 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1459 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1460 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1461 for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1462 DstValue->push_back(Elts[I]);
1463 break;
1469 // For the Min behavior, set the value to 0 if either module does not have the
1470 // flag.
1471 for (auto Idx : Mins) {
1472 MDNode *Op = DstModFlags->getOperand(Idx);
1473 MDString *ID = cast<MDString>(Op->getOperand(1));
1474 if (!SeenMin.count(ID)) {
1475 ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1476 Metadata *FlagOps[] = {
1477 Op->getOperand(0), ID,
1478 ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1479 DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1483 // Check all of the requirements.
1484 for (MDNode *Requirement : Requirements) {
1485 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1486 Metadata *ReqValue = Requirement->getOperand(1);
1488 MDNode *Op = Flags[Flag].first;
1489 if (!Op || Op->getOperand(2) != ReqValue)
1490 return stringErr("linking module flags '" + Flag->getString() +
1491 "': does not have the required value");
1493 return Error::success();
1496 /// Return InlineAsm adjusted with target-specific directives if required.
1497 /// For ARM and Thumb, we have to add directives to select the appropriate ISA
1498 /// to support mixing module-level inline assembly from ARM and Thumb modules.
1499 static std::string adjustInlineAsm(const std::string &InlineAsm,
1500 const Triple &Triple) {
1501 if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
1502 return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1503 if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
1504 return ".text\n.balign 4\n.arm\n" + InlineAsm;
1505 return InlineAsm;
1508 void IRLinker::updateAttributes(GlobalValue &GV) {
1509 /// Remove nocallback attribute while linking, because nocallback attribute
1510 /// indicates that the function is only allowed to jump back into caller's
1511 /// module only by a return or an exception. When modules are linked, this
1512 /// property cannot be guaranteed anymore. For example, the nocallback
1513 /// function may contain a call to another module. But if we merge its caller
1514 /// and callee module here, and not the module containing the nocallback
1515 /// function definition itself, the nocallback property will be violated
1516 /// (since the nocallback function will call back into the newly merged module
1517 /// containing both its caller and callee). This could happen if the module
1518 /// containing the nocallback function definition is native code, so it does
1519 /// not participate in the LTO link. Note if the nocallback function does
1520 /// participate in the LTO link, and thus ends up in the merged module
1521 /// containing its caller and callee, removing the attribute doesn't hurt as
1522 /// it has no effect on definitions in the same module.
1523 if (auto *F = dyn_cast<Function>(&GV)) {
1524 if (!F->isIntrinsic())
1525 F->removeFnAttr(llvm::Attribute::NoCallback);
1527 // Remove nocallback attribute when it is on a call-site.
1528 for (BasicBlock &BB : *F)
1529 for (Instruction &I : BB)
1530 if (CallBase *CI = dyn_cast<CallBase>(&I))
1531 CI->removeFnAttr(Attribute::NoCallback);
1535 Error IRLinker::run() {
1536 // Ensure metadata materialized before value mapping.
1537 if (SrcM->getMaterializer())
1538 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1539 return Err;
1541 // Convert source module to match dest for the duration of the link.
1542 ScopedDbgInfoFormatSetter FormatSetter(*SrcM, DstM.IsNewDbgInfoFormat);
1544 // Inherit the target data from the source module if the destination
1545 // module doesn't have one already.
1546 if (DstM.getDataLayout().isDefault())
1547 DstM.setDataLayout(SrcM->getDataLayout());
1549 // Copy the target triple from the source to dest if the dest's is empty.
1550 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1551 DstM.setTargetTriple(SrcM->getTargetTriple());
1553 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1555 // During CUDA compilation we have to link with the bitcode supplied with
1556 // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1557 // the layout that is different from the one used by LLVM/clang (it does not
1558 // include i128). Issuing a warning is not very helpful as there's not much
1559 // the user can do about it.
1560 bool EnableDLWarning = true;
1561 bool EnableTripleWarning = true;
1562 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1563 bool SrcHasLibDeviceDL =
1564 (SrcM->getDataLayoutStr().empty() ||
1565 SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1566 // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1567 // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1568 // all NVPTX variants.
1569 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1570 SrcTriple.getOSName() == "gpulibs") ||
1571 (SrcTriple.getVendorName() == "unknown" &&
1572 SrcTriple.getOSName() == "unknown");
1573 EnableTripleWarning = !SrcHasLibDeviceTriple;
1574 EnableDLWarning = !(SrcHasLibDeviceTriple && SrcHasLibDeviceDL);
1577 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1578 emitWarning("Linking two modules of different data layouts: '" +
1579 SrcM->getModuleIdentifier() + "' is '" +
1580 SrcM->getDataLayoutStr() + "' whereas '" +
1581 DstM.getModuleIdentifier() + "' is '" +
1582 DstM.getDataLayoutStr() + "'\n");
1585 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1586 !SrcTriple.isCompatibleWith(DstTriple))
1587 emitWarning("Linking two modules of different target triples: '" +
1588 SrcM->getModuleIdentifier() + "' is '" +
1589 SrcM->getTargetTriple() + "' whereas '" +
1590 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1591 "'\n");
1593 DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1595 // Loop over all of the linked values to compute type mappings.
1596 computeTypeMapping();
1598 std::reverse(Worklist.begin(), Worklist.end());
1599 while (!Worklist.empty()) {
1600 GlobalValue *GV = Worklist.back();
1601 Worklist.pop_back();
1603 // Already mapped.
1604 if (ValueMap.find(GV) != ValueMap.end() ||
1605 IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1606 continue;
1608 assert(!GV->isDeclaration());
1609 Mapper.mapValue(*GV);
1610 if (FoundError)
1611 return std::move(*FoundError);
1612 flushRAUWWorklist();
1615 // Note that we are done linking global value bodies. This prevents
1616 // metadata linking from creating new references.
1617 DoneLinkingBodies = true;
1618 Mapper.addFlags(RF_NullMapMissingGlobalValues);
1620 // Remap all of the named MDNodes in Src into the DstM module. We do this
1621 // after linking GlobalValues so that MDNodes that reference GlobalValues
1622 // are properly remapped.
1623 linkNamedMDNodes();
1625 // Clean up any global objects with potentially unmapped metadata.
1626 // Specifically declarations which did not become definitions.
1627 for (GlobalObject *NGO : UnmappedMetadata) {
1628 if (NGO->isDeclaration())
1629 Mapper.remapGlobalObjectMetadata(*NGO);
1632 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1633 // Append the module inline asm string.
1634 DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1635 SrcTriple));
1636 } else if (IsPerformingImport) {
1637 // Import any symver directives for symbols in DstM.
1638 ModuleSymbolTable::CollectAsmSymvers(*SrcM,
1639 [&](StringRef Name, StringRef Alias) {
1640 if (DstM.getNamedValue(Name)) {
1641 SmallString<256> S(".symver ");
1642 S += Name;
1643 S += ", ";
1644 S += Alias;
1645 DstM.appendModuleInlineAsm(S);
1650 // Reorder the globals just added to the destination module to match their
1651 // original order in the source module.
1652 for (GlobalVariable &GV : SrcM->globals()) {
1653 if (GV.hasAppendingLinkage())
1654 continue;
1655 Value *NewValue = Mapper.mapValue(GV);
1656 if (NewValue) {
1657 auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1658 if (NewGV) {
1659 NewGV->removeFromParent();
1660 DstM.insertGlobalVariable(NewGV);
1665 // Merge the module flags into the DstM module.
1666 return linkModuleFlagsMetadata();
1669 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1670 : ETypes(E), IsPacked(P) {}
1672 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1673 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1675 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1676 return IsPacked == That.IsPacked && ETypes == That.ETypes;
1679 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1680 return !this->operator==(That);
1683 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1684 return DenseMapInfo<StructType *>::getEmptyKey();
1687 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1688 return DenseMapInfo<StructType *>::getTombstoneKey();
1691 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1692 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1693 Key.IsPacked);
1696 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1697 return getHashValue(KeyTy(ST));
1700 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1701 const StructType *RHS) {
1702 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1703 return false;
1704 return LHS == KeyTy(RHS);
1707 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1708 const StructType *RHS) {
1709 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1710 return LHS == RHS;
1711 return KeyTy(LHS) == KeyTy(RHS);
1714 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1715 assert(!Ty->isOpaque());
1716 NonOpaqueStructTypes.insert(Ty);
1719 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1720 assert(!Ty->isOpaque());
1721 NonOpaqueStructTypes.insert(Ty);
1722 bool Removed = OpaqueStructTypes.erase(Ty);
1723 (void)Removed;
1724 assert(Removed);
1727 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1728 assert(Ty->isOpaque());
1729 OpaqueStructTypes.insert(Ty);
1732 StructType *
1733 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1734 bool IsPacked) {
1735 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1736 auto I = NonOpaqueStructTypes.find_as(Key);
1737 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1740 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1741 if (Ty->isOpaque())
1742 return OpaqueStructTypes.count(Ty);
1743 auto I = NonOpaqueStructTypes.find(Ty);
1744 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1747 IRMover::IRMover(Module &M) : Composite(M) {
1748 TypeFinder StructTypes;
1749 StructTypes.run(M, /* OnlyNamed */ false);
1750 for (StructType *Ty : StructTypes) {
1751 if (Ty->isOpaque())
1752 IdentifiedStructTypes.addOpaque(Ty);
1753 else
1754 IdentifiedStructTypes.addNonOpaque(Ty);
1756 // Self-map metadatas in the destination module. This is needed when
1757 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1758 // destination module may be reached from the source module.
1759 for (const auto *MD : StructTypes.getVisitedMetadata()) {
1760 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1764 Error IRMover::move(std::unique_ptr<Module> Src,
1765 ArrayRef<GlobalValue *> ValuesToLink,
1766 LazyCallback AddLazyFor, bool IsPerformingImport) {
1767 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1768 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1769 IsPerformingImport);
1770 Error E = TheIRLinker.run();
1771 Composite.dropTriviallyDeadConstantArrays();
1772 return E;