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