xref: /llvm-project/llvm/lib/Linker/IRMover.cpp (revision 416f1c465db62d829283f6902ef35e027e127aa7)
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/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;
36 
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());
41 }
42 
43 //===----------------------------------------------------------------------===//
44 // TypeMap implementation.
45 //===----------------------------------------------------------------------===//
46 
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;
51 
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;
56 
57   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
58 
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;
62 
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;
66 
67 public:
68   TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
69       : DstStructTypesSet(DstStructTypesSet) {}
70 
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);
75 
76   /// Produce a body for an opaque type in the dest module from a type
77   /// definition in the source module.
78   Error linkDefinedTypeBodies();
79 
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);
84 
85   FunctionType *get(FunctionType *T) {
86     return cast<FunctionType>(get((Type *)T));
87   }
88 
89 private:
90   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
91 
92   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
93 };
94 }
95 
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97   assert(SpeculativeTypes.empty());
98   assert(SpeculativeDstOpaqueTypes.empty());
99 
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);
107 
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("");
123   }
124   SpeculativeTypes.clear();
125   SpeculativeDstOpaqueTypes.clear();
126 }
127 
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;
134 
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;
139 
140   // Two identical types are clearly isomorphic.  Remember this
141   // non-speculatively.
142   if (DstTy == SrcTy) {
143     Entry = DstTy;
144     return true;
145   }
146 
147   // Okay, we have two types with identical kinds that we haven't seen before.
148 
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;
156     }
157 
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;
171     }
172   }
173 
174   // If the number of subtypes disagree between the two types, then we fail.
175   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176     return false;
177 
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;
198   }
199 
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);
204 
205   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
206     if (!areTypesIsomorphic(DstTy->getContainedType(I),
207                             SrcTy->getContainedType(I)))
208       return false;
209 
210   // If everything seems to have lined up, then everything is great.
211   return true;
212 }
213 
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());
219 
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));
224 
225     if (auto E = DstSTy->setBodyOrError(Elements, SrcSTy->isPacked()))
226       return E;
227     DstStructTypesSet.switchToNonOpaque(DstSTy);
228   }
229   SrcDefinitionsToResolve.clear();
230   DstResolvedOpaqueTypes.clear();
231   return Error::success();
232 }
233 
234 Type *TypeMapTy::get(Type *Ty) {
235   SmallPtrSet<StructType *, 8> Visited;
236   return get(Ty, Visited);
237 }
238 
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;
244 
245   // These are types that LLVM itself will unique.
246   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
247 
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");
253     }
254 #endif
255 
256     if (!Visited.insert(cast<StructType>(Ty)).second) {
257       StructType *DTy = StructType::create(Ty->getContext());
258       return *Entry = DTy;
259     }
260   }
261 
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;
265 
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;
270 
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);
277   }
278 
279   // Refresh Entry after recursively processing stuff.
280   Entry = &MappedTypes[Ty];
281   assert(!*Entry && "Recursive type!");
282 
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;
287 
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);
308 
309     // If the type is opaque, we can just use it directly.
310     if (STy->isOpaque()) {
311       DstStructTypesSet.addOpaque(STy);
312       return *Entry = Ty;
313     }
314 
315     if (StructType *OldT =
316             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
317       STy->setName("");
318       return *Entry = OldT;
319     }
320 
321     if (!AnyChange) {
322       DstStructTypesSet.addNonOpaque(STy);
323       return *Entry = Ty;
324     }
325 
326     StructType *DTy =
327         StructType::create(Ty->getContext(), ElementTypes, "", STy->isPacked());
328 
329     // Steal STy's name.
330     if (STy->hasName()) {
331       SmallString<16> TmpName = STy->getName();
332       STy->setName("");
333       DTy->setName(TmpName);
334     }
335 
336     DstStructTypesSet.addNonOpaque(DTy);
337     return *Entry = DTy;
338   }
339   }
340 }
341 
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; }
346 
347 //===----------------------------------------------------------------------===//
348 // IRLinker implementation.
349 //===----------------------------------------------------------------------===//
350 
351 namespace {
352 class IRLinker;
353 
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;
359 
360 public:
361   GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
362   Value *materialize(Value *V) override;
363 };
364 
365 class LocalValueMaterializer final : public ValueMaterializer {
366   IRLinker &TheIRLinker;
367 
368 public:
369   LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
370   Value *materialize(Value *V) override;
371 };
372 
373 /// Type of the Metadata map in \a ValueToValueMapTy.
374 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
375 
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;
381 
382   /// See IRMover::move().
383   IRMover::LazyCallback AddLazyFor;
384 
385   TypeMapTy TypeMap;
386   GlobalValueMaterializer GValMaterializer;
387   LocalValueMaterializer LValMaterializer;
388 
389   /// A metadata map that's shared between IRLinker instances.
390   MDMapT &SharedMDs;
391 
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;
398 
399   DenseSet<GlobalValue *> ValuesToLink;
400   std::vector<GlobalValue *> Worklist;
401   std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
402 
403   /// Set of globals with eagerly copied metadata that may require remapping.
404   /// This remapping is performed after metadata linking.
405   DenseSet<GlobalObject *> UnmappedMetadata;
406 
407   void maybeAdd(GlobalValue *GV) {
408     if (ValuesToLink.insert(GV).second)
409       Worklist.push_back(GV);
410   }
411 
412   /// Whether we are importing globals for ThinLTO, as opposed to linking the
413   /// source module. If this flag is set, it means that we can rely on some
414   /// other object file to define any non-GlobalValue entities defined by the
415   /// source module. This currently causes us to not link retained types in
416   /// debug info metadata and module inline asm.
417   bool IsPerformingImport;
418 
419   /// Set to true when all global value body linking is complete (including
420   /// lazy linking). Used to prevent metadata linking from creating new
421   /// references.
422   bool DoneLinkingBodies = false;
423 
424   /// The Error encountered during materialization. We use an Optional here to
425   /// avoid needing to manage an unconsumed success value.
426   std::optional<Error> FoundError;
427   void setError(Error E) {
428     if (E)
429       FoundError = std::move(E);
430   }
431 
432   /// Entry point for mapping values and alternate context for mapping aliases.
433   ValueMapper Mapper;
434   unsigned IndirectSymbolMCID;
435 
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);
439 
440   void emitWarning(const Twine &Message) {
441     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
442   }
443 
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;
451 
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;
456 
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;
461 
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;
469 
470     // Otherwise, we do in fact link to the destination global.
471     return DGV;
472   }
473 
474   void computeTypeMapping();
475 
476   Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
477                                              const GlobalVariable *SrcGV);
478 
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.
482   ///
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);
487 
488   Error linkModuleFlagsMetadata();
489 
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);
495 
496   /// Replace all types in the source AttributeList with the
497   /// corresponding destination type.
498   AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
499 
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);
505 
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();
513 
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();
519 
520   ///  Update attributes while linking.
521   void updateAttributes(GlobalValue &GV);
522 
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();
540   }
541   ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
542 
543   Error run();
544   Value *materialize(Value *V, bool ForIndirectSymbol);
545 };
546 }
547 
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;
556 
557   Module *M = GV->getParent();
558 
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
566   }
567 }
568 
569 Value *GlobalValueMaterializer::materialize(Value *SGV) {
570   return TheIRLinker.materialize(SGV, false);
571 }
572 
573 Value *LocalValueMaterializer::materialize(Value *SGV) {
574   return TheIRLinker.materialize(SGV, true);
575 }
576 
577 Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
578   auto *SGV = dyn_cast<GlobalValue>(V);
579   if (!SGV)
580     return nullptr;
581 
582   // If SGV is from dest, it was already materialized when dest was loaded.
583   if (SGV->getParent() == &DstM)
584     return nullptr;
585 
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;
592 
593   Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
594   if (!NewProto) {
595     setError(NewProto.takeError());
596     return nullptr;
597   }
598   if (!*NewProto)
599     return nullptr;
600 
601   GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
602   if (!New)
603     return *NewProto;
604 
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");
620   }
621 
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;
633 
634   if (ForIndirectSymbol || shouldLink(New, *SGV))
635     setError(linkGlobalValueBody(*New, *SGV));
636 
637   updateAttributes(*New);
638   return New;
639 }
640 
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;
656 }
657 
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;
669         }
670       }
671     }
672   }
673   return Attrs;
674 }
675 
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;
688 }
689 
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());
696 
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;
703   }
704 
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;
711   }
712 
713   llvm_unreachable("Invalid source global value type");
714 }
715 
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());
738   }
739 
740   if (ForDefinition)
741     NewGV->setLinkage(SGV->getLinkage());
742   else if (SGV->hasExternalWeakLinkage())
743     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
744 
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);
751     }
752   }
753 
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);
761   }
762 
763   return NewGV;
764 }
765 
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);
772 }
773 
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;
783 
784     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
785       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
786       continue;
787     }
788 
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());
793   }
794 
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;
804       }
805 
806       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
807     }
808 
809   for (GlobalValue &SGV : SrcM->aliases())
810     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
811       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
812 
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;
821 
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;
828     }
829 
830     auto STTypePrefix = getTypeNamePrefix(ST->getName());
831     if (STTypePrefix.size() == ST->getName().size())
832       continue;
833 
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;
838 
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:
843     //
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 }
850     //
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);
858   }
859 
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());
863 }
864 
865 static void getArrayElements(const Constant *C,
866                              SmallVectorImpl<Constant *> &Dest) {
867   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
868 
869   for (unsigned i = 0; i != NumElements; ++i)
870     Dest.push_back(C->getAggregateElement(i));
871 }
872 
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!");
884 
885     if (DstGV->isConstant() != SrcGV->isConstant())
886       return stringErr("Appending variables linked with different const'ness!");
887 
888     if (DstGV->getAlign() != SrcGV->getAlign())
889       return stringErr(
890           "Appending variables with different alignment need to be linked!");
891 
892     if (DstGV->getVisibility() != SrcGV->getVisibility())
893       return stringErr(
894           "Appending variables with different visibility need to be linked!");
895 
896     if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
897       return stringErr(
898           "Appending variables with different unnamed_addr need to be linked!");
899 
900     if (DstGV->getSection() != SrcGV->getSection())
901       return stringErr(
902           "Appending variables with different section name need to be linked!");
903 
904     if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
905       return stringErr("Appending variables with different address spaces need "
906                        "to be linked!");
907   }
908 
909   // Do not need to do anything if source is a declaration.
910   if (SrcGV->isDeclaration())
911     return DstGV;
912 
913   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
914                     ->getElementType();
915 
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;
928   }
929 
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);
935   }
936 
937   uint64_t DstNumElements = 0;
938   if (DstGV && !DstGV->isDeclaration()) {
939     ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
940     DstNumElements = DstTy->getNumElements();
941 
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!");
945   }
946 
947   SmallVector<Constant *, 16> SrcElements;
948   getArrayElements(SrcGV->getInitializer(), SrcElements);
949 
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);
958     });
959   }
960   uint64_t NewSize = DstNumElements + SrcElements.size();
961   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
962 
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());
968 
969   NG->copyAttributesFrom(SrcGV);
970   forceRenaming(NG, SrcGV->getName());
971 
972   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
973 
974   Mapper.scheduleMapAppendingVariable(
975       *NG,
976       (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
977       IsOldStructor, SrcElements);
978 
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));
983   }
984 
985   return Ret;
986 }
987 
988 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
989   if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
990     return true;
991 
992   if (DGV && !DGV->isDeclarationForLinker())
993     return false;
994 
995   if (SGV.isDeclaration() || DoneLinkingBodies)
996     return false;
997 
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;
1005     });
1006   return LazilyAdded;
1007 }
1008 
1009 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1010                                                     bool ForIndirectSymbol) {
1011   GlobalValue *DGV = getLinkedToGlobal(SGV);
1012 
1013   bool ShouldLink = shouldLink(DGV, *SGV);
1014 
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);
1020 
1021     I = IndirectSymbolValueMap.find(SGV);
1022     if (I != IndirectSymbolValueMap.end())
1023       return cast<Constant>(I->second);
1024   }
1025 
1026   if (!ShouldLink && ForIndirectSymbol)
1027     DGV = nullptr;
1028 
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));
1033 
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;
1044 
1045     NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1046     if (ShouldLink || !ForIndirectSymbol)
1047       NeedsRenaming = true;
1048   }
1049 
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;
1062     }
1063 
1064   if (NeedsRenaming)
1065     forceRenaming(NewGV, SGV->getName());
1066 
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);
1073       }
1074     }
1075   }
1076 
1077   if (!ShouldLink && ForIndirectSymbol)
1078     NewGV->setLinkage(GlobalValue::InternalLinkage);
1079 
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()));
1089   }
1090 
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())));
1098   }
1099 
1100   return C;
1101 }
1102 
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());
1108 }
1109 
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());
1115 
1116   // Materialize if needed.
1117   if (Error Err = Src.materialize())
1118     return Err;
1119 
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);
1128 
1129   // Copy over the metadata attachments without remapping.
1130   Dst.copyMetadata(&Src, 0);
1131 
1132   // Steal arguments and splice the body of Src into Dst.
1133   Dst.stealArgumentListFrom(Src);
1134   Dst.splice(Dst.end(), &Src);
1135 
1136   // Everything has been moved over.  Remap it.
1137   Mapper.scheduleRemapFunction(Dst);
1138   return Error::success();
1139 }
1140 
1141 void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1142   Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1143 }
1144 
1145 void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1146   Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1147 }
1148 
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();
1155   }
1156   if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1157     linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1158     return Error::success();
1159   }
1160   linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1161   return Error::success();
1162 }
1163 
1164 void IRLinker::flushRAUWWorklist() {
1165   for (const auto &Elem : RAUWWorklist) {
1166     GlobalValue *Old;
1167     Value *New;
1168     std::tie(Old, New) = Elem;
1169 
1170     Old->replaceAllUsesWith(New);
1171     Old->eraseFromParent();
1172   }
1173   RAUWWorklist.clear();
1174 }
1175 
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);
1192 
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);
1203 
1204     CU->replaceImportedEntities(nullptr);
1205   }
1206 }
1207 
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;
1225     }
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;
1230 
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));
1235   }
1236 }
1237 
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();
1244 
1245   // Check for module flag for updates before do anything.
1246   UpgradeModuleFlags(*SrcM);
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   SmallVector<unsigned, 0> Mins;
1262   DenseSet<MDString *> SeenMin;
1263   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1264     MDNode *Op = DstModFlags->getOperand(I);
1265     uint64_t Behavior =
1266         mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1267     MDString *ID = cast<MDString>(Op->getOperand(1));
1268 
1269     if (Behavior == Module::Require) {
1270       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1271     } else {
1272       if (Behavior == Module::Min)
1273         Mins.push_back(I);
1274       Flags[ID] = std::make_pair(Op, I);
1275     }
1276   }
1277 
1278   // Merge in the flags from the source module, and also collect its set of
1279   // requirements.
1280   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1281     MDNode *SrcOp = SrcModFlags->getOperand(I);
1282     ConstantInt *SrcBehavior =
1283         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1284     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1285     MDNode *DstOp;
1286     unsigned DstIndex;
1287     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1288     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1289     SeenMin.insert(ID);
1290 
1291     // If this is a requirement, add it and continue.
1292     if (SrcBehaviorValue == Module::Require) {
1293       // If the destination module does not already have this requirement, add
1294       // it.
1295       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1296         DstModFlags->addOperand(SrcOp);
1297       }
1298       continue;
1299     }
1300 
1301     // If there is no existing flag with this ID, just add it.
1302     if (!DstOp) {
1303       if (SrcBehaviorValue == Module::Min) {
1304         Mins.push_back(DstModFlags->getNumOperands());
1305         SeenMin.erase(ID);
1306       }
1307       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1308       DstModFlags->addOperand(SrcOp);
1309       continue;
1310     }
1311 
1312     // Otherwise, perform a merge.
1313     ConstantInt *DstBehavior =
1314         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1315     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1316 
1317     auto overrideDstValue = [&]() {
1318       DstModFlags->setOperand(DstIndex, SrcOp);
1319       Flags[ID].first = SrcOp;
1320     };
1321 
1322     // If either flag has override behavior, handle it first.
1323     if (DstBehaviorValue == Module::Override) {
1324       // Diagnose inconsistent flags which both have override behavior.
1325       if (SrcBehaviorValue == Module::Override &&
1326           SrcOp->getOperand(2) != DstOp->getOperand(2))
1327         return stringErr("linking module flags '" + ID->getString() +
1328                          "': IDs have conflicting override values in '" +
1329                          SrcM->getModuleIdentifier() + "' and '" +
1330                          DstM.getModuleIdentifier() + "'");
1331       continue;
1332     } else if (SrcBehaviorValue == Module::Override) {
1333       // Update the destination flag to that of the source.
1334       overrideDstValue();
1335       continue;
1336     }
1337 
1338     // Diagnose inconsistent merge behavior types.
1339     if (SrcBehaviorValue != DstBehaviorValue) {
1340       bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1341                          DstBehaviorValue == Module::Warning) ||
1342                         (DstBehaviorValue == Module::Min &&
1343                          SrcBehaviorValue == Module::Warning);
1344       bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1345                          DstBehaviorValue == Module::Warning) ||
1346                         (DstBehaviorValue == Module::Max &&
1347                          SrcBehaviorValue == Module::Warning);
1348       if (!(MaxAndWarn || MinAndWarn))
1349         return stringErr("linking module flags '" + ID->getString() +
1350                          "': IDs have conflicting behaviors in '" +
1351                          SrcM->getModuleIdentifier() + "' and '" +
1352                          DstM.getModuleIdentifier() + "'");
1353     }
1354 
1355     auto ensureDistinctOp = [&](MDNode *DstValue) {
1356       assert(isa<MDTuple>(DstValue) &&
1357              "Expected MDTuple when appending module flags");
1358       if (DstValue->isDistinct())
1359         return dyn_cast<MDTuple>(DstValue);
1360       ArrayRef<MDOperand> DstOperands = DstValue->operands();
1361       MDTuple *New = MDTuple::getDistinct(
1362           DstM.getContext(), SmallVector<Metadata *, 4>(DstOperands));
1363       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1364       MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1365       DstModFlags->setOperand(DstIndex, Flag);
1366       Flags[ID].first = Flag;
1367       return New;
1368     };
1369 
1370     // Emit a warning if the values differ and either source or destination
1371     // request Warning behavior.
1372     if ((DstBehaviorValue == Module::Warning ||
1373          SrcBehaviorValue == Module::Warning) &&
1374         SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1375       std::string Str;
1376       raw_string_ostream(Str)
1377           << "linking module flags '" << ID->getString()
1378           << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1379           << "' from " << SrcM->getModuleIdentifier() << " with '"
1380           << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1381           << ')';
1382       emitWarning(Str);
1383     }
1384 
1385     // Choose the minimum if either source or destination request Min behavior.
1386     if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1387       ConstantInt *DstValue =
1388           mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1389       ConstantInt *SrcValue =
1390           mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1391 
1392       // The resulting flag should have a Min behavior, and contain the minimum
1393       // value from between the source and destination values.
1394       Metadata *FlagOps[] = {
1395           (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1396           (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1397               ->getOperand(2)};
1398       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1399       DstModFlags->setOperand(DstIndex, Flag);
1400       Flags[ID].first = Flag;
1401       continue;
1402     }
1403 
1404     // Choose the maximum if either source or destination request Max behavior.
1405     if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1406       ConstantInt *DstValue =
1407           mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1408       ConstantInt *SrcValue =
1409           mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1410 
1411       // The resulting flag should have a Max behavior, and contain the maximum
1412       // value from between the source and destination values.
1413       Metadata *FlagOps[] = {
1414           (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1415           (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1416               ->getOperand(2)};
1417       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1418       DstModFlags->setOperand(DstIndex, Flag);
1419       Flags[ID].first = Flag;
1420       continue;
1421     }
1422 
1423     // Perform the merge for standard behavior types.
1424     switch (SrcBehaviorValue) {
1425     case Module::Require:
1426     case Module::Override:
1427       llvm_unreachable("not possible");
1428     case Module::Error: {
1429       // Emit an error if the values differ.
1430       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1431         std::string Str;
1432         raw_string_ostream(Str)
1433             << "linking module flags '" << ID->getString()
1434             << "': IDs have conflicting values: '" << *SrcOp->getOperand(2)
1435             << "' from " << SrcM->getModuleIdentifier() << ", and '"
1436             << *DstOp->getOperand(2) << "' from " + DstM.getModuleIdentifier();
1437         return stringErr(Str);
1438       }
1439       continue;
1440     }
1441     case Module::Warning: {
1442       break;
1443     }
1444     case Module::Max: {
1445       break;
1446     }
1447     case Module::Append: {
1448       MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1449       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1450       for (const auto &O : SrcValue->operands())
1451         DstValue->push_back(O);
1452       break;
1453     }
1454     case Module::AppendUnique: {
1455       SmallSetVector<Metadata *, 16> Elts;
1456       MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1457       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1458       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1459       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1460       for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1461         DstValue->push_back(Elts[I]);
1462       break;
1463     }
1464     }
1465 
1466   }
1467 
1468   // For the Min behavior, set the value to 0 if either module does not have the
1469   // flag.
1470   for (auto Idx : Mins) {
1471     MDNode *Op = DstModFlags->getOperand(Idx);
1472     MDString *ID = cast<MDString>(Op->getOperand(1));
1473     if (!SeenMin.count(ID)) {
1474       ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1475       Metadata *FlagOps[] = {
1476           Op->getOperand(0), ID,
1477           ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1478       DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1479     }
1480   }
1481 
1482   // Check all of the requirements.
1483   for (MDNode *Requirement : Requirements) {
1484     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1485     Metadata *ReqValue = Requirement->getOperand(1);
1486 
1487     MDNode *Op = Flags[Flag].first;
1488     if (!Op || Op->getOperand(2) != ReqValue)
1489       return stringErr("linking module flags '" + Flag->getString() +
1490                        "': does not have the required value");
1491   }
1492   return Error::success();
1493 }
1494 
1495 /// Return InlineAsm adjusted with target-specific directives if required.
1496 /// For ARM and Thumb, we have to add directives to select the appropriate ISA
1497 /// to support mixing module-level inline assembly from ARM and Thumb modules.
1498 static std::string adjustInlineAsm(const std::string &InlineAsm,
1499                                    const Triple &Triple) {
1500   if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
1501     return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1502   if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
1503     return ".text\n.balign 4\n.arm\n" + InlineAsm;
1504   return InlineAsm;
1505 }
1506 
1507 void IRLinker::updateAttributes(GlobalValue &GV) {
1508   /// Remove nocallback attribute while linking, because nocallback attribute
1509   /// indicates that the function is only allowed to jump back into caller's
1510   /// module only by a return or an exception. When modules are linked, this
1511   /// property cannot be guaranteed anymore. For example, the nocallback
1512   /// function may contain a call to another module. But if we merge its caller
1513   /// and callee module here, and not the module containing the nocallback
1514   /// function definition itself, the nocallback property will be violated
1515   /// (since the nocallback function will call back into the newly merged module
1516   /// containing both its caller and callee). This could happen if the module
1517   /// containing the nocallback function definition is native code, so it does
1518   /// not participate in the LTO link. Note if the nocallback function does
1519   /// participate in the LTO link, and thus ends up in the merged module
1520   /// containing its caller and callee, removing the attribute doesn't hurt as
1521   /// it has no effect on definitions in the same module.
1522   if (auto *F = dyn_cast<Function>(&GV)) {
1523     if (!F->isIntrinsic())
1524       F->removeFnAttr(llvm::Attribute::NoCallback);
1525 
1526     // Remove nocallback attribute when it is on a call-site.
1527     for (BasicBlock &BB : *F)
1528       for (Instruction &I : BB)
1529         if (CallBase *CI = dyn_cast<CallBase>(&I))
1530           CI->removeFnAttr(Attribute::NoCallback);
1531   }
1532 }
1533 
1534 Error IRLinker::run() {
1535   // Ensure metadata materialized before value mapping.
1536   if (SrcM->getMaterializer())
1537     if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1538       return Err;
1539 
1540   // Convert source module to match dest for the duration of the link.
1541   ScopedDbgInfoFormatSetter FormatSetter(*SrcM, DstM.IsNewDbgInfoFormat);
1542 
1543   // Inherit the target data from the source module if the destination
1544   // module doesn't have one already.
1545   if (DstM.getDataLayout().isDefault())
1546     DstM.setDataLayout(SrcM->getDataLayout());
1547 
1548   // Copy the target triple from the source to dest if the dest's is empty.
1549   if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1550     DstM.setTargetTriple(SrcM->getTargetTriple());
1551 
1552   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1553 
1554   // During CUDA compilation we have to link with the bitcode supplied with
1555   // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1556   // the layout that is different from the one used by LLVM/clang (it does not
1557   // include i128). Issuing a warning is not very helpful as there's not much
1558   // the user can do about it.
1559   bool EnableDLWarning = true;
1560   bool EnableTripleWarning = true;
1561   if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1562     bool SrcHasLibDeviceDL =
1563         (SrcM->getDataLayoutStr().empty() ||
1564          SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1565     // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1566     // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1567     // all NVPTX variants.
1568     bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1569                                   SrcTriple.getOSName() == "gpulibs") ||
1570                                  (SrcTriple.getVendorName() == "unknown" &&
1571                                   SrcTriple.getOSName() == "unknown");
1572     EnableTripleWarning = !SrcHasLibDeviceTriple;
1573     EnableDLWarning = !(SrcHasLibDeviceTriple && SrcHasLibDeviceDL);
1574   }
1575 
1576   if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1577     emitWarning("Linking two modules of different data layouts: '" +
1578                 SrcM->getModuleIdentifier() + "' is '" +
1579                 SrcM->getDataLayoutStr() + "' whereas '" +
1580                 DstM.getModuleIdentifier() + "' is '" +
1581                 DstM.getDataLayoutStr() + "'\n");
1582   }
1583 
1584   if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1585       !SrcTriple.isCompatibleWith(DstTriple))
1586     emitWarning("Linking two modules of different target triples: '" +
1587                 SrcM->getModuleIdentifier() + "' is '" +
1588                 SrcM->getTargetTriple() + "' whereas '" +
1589                 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1590                 "'\n");
1591 
1592   DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1593 
1594   // Loop over all of the linked values to compute type mappings.
1595   computeTypeMapping();
1596 
1597   std::reverse(Worklist.begin(), Worklist.end());
1598   while (!Worklist.empty()) {
1599     GlobalValue *GV = Worklist.back();
1600     Worklist.pop_back();
1601 
1602     // Already mapped.
1603     if (ValueMap.find(GV) != ValueMap.end() ||
1604         IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1605       continue;
1606 
1607     assert(!GV->isDeclaration());
1608     Mapper.mapValue(*GV);
1609     if (FoundError)
1610       return std::move(*FoundError);
1611     flushRAUWWorklist();
1612   }
1613 
1614   // Note that we are done linking global value bodies. This prevents
1615   // metadata linking from creating new references.
1616   DoneLinkingBodies = true;
1617   Mapper.addFlags(RF_NullMapMissingGlobalValues);
1618 
1619   // Remap all of the named MDNodes in Src into the DstM module. We do this
1620   // after linking GlobalValues so that MDNodes that reference GlobalValues
1621   // are properly remapped.
1622   linkNamedMDNodes();
1623 
1624   // Clean up any global objects with potentially unmapped metadata.
1625   // Specifically declarations which did not become definitions.
1626   for (GlobalObject *NGO : UnmappedMetadata) {
1627     if (NGO->isDeclaration())
1628       Mapper.remapGlobalObjectMetadata(*NGO);
1629   }
1630 
1631   if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1632     // Append the module inline asm string.
1633     DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1634                                                SrcTriple));
1635   } else if (IsPerformingImport) {
1636     // Import any symver directives for symbols in DstM.
1637     ModuleSymbolTable::CollectAsmSymvers(*SrcM,
1638                                          [&](StringRef Name, StringRef Alias) {
1639       if (DstM.getNamedValue(Name)) {
1640         SmallString<256> S(".symver ");
1641         S += Name;
1642         S += ", ";
1643         S += Alias;
1644         DstM.appendModuleInlineAsm(S);
1645       }
1646     });
1647   }
1648 
1649   // Reorder the globals just added to the destination module to match their
1650   // original order in the source module.
1651   for (GlobalVariable &GV : SrcM->globals()) {
1652     if (GV.hasAppendingLinkage())
1653       continue;
1654     Value *NewValue = Mapper.mapValue(GV);
1655     if (NewValue) {
1656       auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1657       if (NewGV) {
1658         NewGV->removeFromParent();
1659         DstM.insertGlobalVariable(NewGV);
1660       }
1661     }
1662   }
1663 
1664   // Merge the module flags into the DstM module.
1665   return linkModuleFlagsMetadata();
1666 }
1667 
1668 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1669     : ETypes(E), IsPacked(P) {}
1670 
1671 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1672     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1673 
1674 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1675   return IsPacked == That.IsPacked && ETypes == That.ETypes;
1676 }
1677 
1678 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1679   return !this->operator==(That);
1680 }
1681 
1682 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1683   return DenseMapInfo<StructType *>::getEmptyKey();
1684 }
1685 
1686 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1687   return DenseMapInfo<StructType *>::getTombstoneKey();
1688 }
1689 
1690 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1691   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1692                       Key.IsPacked);
1693 }
1694 
1695 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1696   return getHashValue(KeyTy(ST));
1697 }
1698 
1699 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1700                                          const StructType *RHS) {
1701   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1702     return false;
1703   return LHS == KeyTy(RHS);
1704 }
1705 
1706 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1707                                          const StructType *RHS) {
1708   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1709     return LHS == RHS;
1710   return KeyTy(LHS) == KeyTy(RHS);
1711 }
1712 
1713 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1714   assert(!Ty->isOpaque());
1715   NonOpaqueStructTypes.insert(Ty);
1716 }
1717 
1718 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1719   assert(!Ty->isOpaque());
1720   NonOpaqueStructTypes.insert(Ty);
1721   bool Removed = OpaqueStructTypes.erase(Ty);
1722   (void)Removed;
1723   assert(Removed);
1724 }
1725 
1726 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1727   assert(Ty->isOpaque());
1728   OpaqueStructTypes.insert(Ty);
1729 }
1730 
1731 StructType *
1732 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1733                                                 bool IsPacked) {
1734   IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1735   auto I = NonOpaqueStructTypes.find_as(Key);
1736   return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1737 }
1738 
1739 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1740   if (Ty->isOpaque())
1741     return OpaqueStructTypes.count(Ty);
1742   auto I = NonOpaqueStructTypes.find(Ty);
1743   return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1744 }
1745 
1746 IRMover::IRMover(Module &M) : Composite(M) {
1747   TypeFinder StructTypes;
1748   StructTypes.run(M, /* OnlyNamed */ false);
1749   for (StructType *Ty : StructTypes) {
1750     if (Ty->isOpaque())
1751       IdentifiedStructTypes.addOpaque(Ty);
1752     else
1753       IdentifiedStructTypes.addNonOpaque(Ty);
1754   }
1755   // Self-map metadatas in the destination module. This is needed when
1756   // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1757   // destination module may be reached from the source module.
1758   for (const auto *MD : StructTypes.getVisitedMetadata()) {
1759     SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1760   }
1761 }
1762 
1763 Error IRMover::move(std::unique_ptr<Module> Src,
1764                     ArrayRef<GlobalValue *> ValuesToLink,
1765                     LazyCallback AddLazyFor, bool IsPerformingImport) {
1766   IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1767                        std::move(Src), ValuesToLink, std::move(AddLazyFor),
1768                        IsPerformingImport);
1769   Error E = TheIRLinker.run();
1770   Composite.dropTriviallyDeadConstantArrays();
1771   return E;
1772 }
1773