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