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