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/Support/Error.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include <utility>
23 using namespace llvm;
24 
25 //===----------------------------------------------------------------------===//
26 // TypeMap implementation.
27 //===----------------------------------------------------------------------===//
28 
29 namespace {
30 class TypeMapTy : public ValueMapTypeRemapper {
31   /// This is a mapping from a source type to a destination type to use.
32   DenseMap<Type *, Type *> MappedTypes;
33 
34   /// When checking to see if two subgraphs are isomorphic, we speculatively
35   /// add types to MappedTypes, but keep track of them here in case we need to
36   /// roll back.
37   SmallVector<Type *, 16> SpeculativeTypes;
38 
39   SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
40 
41   /// This is a list of non-opaque structs in the source module that are mapped
42   /// to an opaque struct in the destination module.
43   SmallVector<StructType *, 16> SrcDefinitionsToResolve;
44 
45   /// This is the set of opaque types in the destination modules who are
46   /// getting a body from the source module.
47   SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
48 
49 public:
50   TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
51       : DstStructTypesSet(DstStructTypesSet) {}
52 
53   IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
54   /// Indicate that the specified type in the destination module is conceptually
55   /// equivalent to the specified type in the source module.
56   void addTypeMapping(Type *DstTy, Type *SrcTy);
57 
58   /// Produce a body for an opaque type in the dest module from a type
59   /// definition in the source module.
60   void linkDefinedTypeBodies();
61 
62   /// Return the mapped type to use for the specified input type from the
63   /// source module.
64   Type *get(Type *SrcTy);
65   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
66 
67   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
68 
69   FunctionType *get(FunctionType *T) {
70     return cast<FunctionType>(get((Type *)T));
71   }
72 
73 private:
74   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
75 
76   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
77 };
78 }
79 
80 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81   assert(SpeculativeTypes.empty());
82   assert(SpeculativeDstOpaqueTypes.empty());
83 
84   // Check to see if these types are recursively isomorphic and establish a
85   // mapping between them if so.
86   if (!areTypesIsomorphic(DstTy, SrcTy)) {
87     // Oops, they aren't isomorphic.  Just discard this request by rolling out
88     // any speculative mappings we've established.
89     for (Type *Ty : SpeculativeTypes)
90       MappedTypes.erase(Ty);
91 
92     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
93                                    SpeculativeDstOpaqueTypes.size());
94     for (StructType *Ty : SpeculativeDstOpaqueTypes)
95       DstResolvedOpaqueTypes.erase(Ty);
96   } else {
97     for (Type *Ty : SpeculativeTypes)
98       if (auto *STy = dyn_cast<StructType>(Ty))
99         if (STy->hasName())
100           STy->setName("");
101   }
102   SpeculativeTypes.clear();
103   SpeculativeDstOpaqueTypes.clear();
104 }
105 
106 /// Recursively walk this pair of types, returning true if they are isomorphic,
107 /// false if they are not.
108 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
109   // Two types with differing kinds are clearly not isomorphic.
110   if (DstTy->getTypeID() != SrcTy->getTypeID())
111     return false;
112 
113   // If we have an entry in the MappedTypes table, then we have our answer.
114   Type *&Entry = MappedTypes[SrcTy];
115   if (Entry)
116     return Entry == DstTy;
117 
118   // Two identical types are clearly isomorphic.  Remember this
119   // non-speculatively.
120   if (DstTy == SrcTy) {
121     Entry = DstTy;
122     return true;
123   }
124 
125   // Okay, we have two types with identical kinds that we haven't seen before.
126 
127   // If this is an opaque struct type, special case it.
128   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
129     // Mapping an opaque type to any struct, just keep the dest struct.
130     if (SSTy->isOpaque()) {
131       Entry = DstTy;
132       SpeculativeTypes.push_back(SrcTy);
133       return true;
134     }
135 
136     // Mapping a non-opaque source type to an opaque dest.  If this is the first
137     // type that we're mapping onto this destination type then we succeed.  Keep
138     // the dest, but fill it in later. If this is the second (different) type
139     // that we're trying to map onto the same opaque type then we fail.
140     if (cast<StructType>(DstTy)->isOpaque()) {
141       // We can only map one source type onto the opaque destination type.
142       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
143         return false;
144       SrcDefinitionsToResolve.push_back(SSTy);
145       SpeculativeTypes.push_back(SrcTy);
146       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
147       Entry = DstTy;
148       return true;
149     }
150   }
151 
152   // If the number of subtypes disagree between the two types, then we fail.
153   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
154     return false;
155 
156   // Fail if any of the extra properties (e.g. array size) of the type disagree.
157   if (isa<IntegerType>(DstTy))
158     return false; // bitwidth disagrees.
159   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
160     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
161       return false;
162 
163   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
164     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
165       return false;
166   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
167     StructType *SSTy = cast<StructType>(SrcTy);
168     if (DSTy->isLiteral() != SSTy->isLiteral() ||
169         DSTy->isPacked() != SSTy->isPacked())
170       return false;
171   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
172     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
173       return false;
174   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
175     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
176       return false;
177   }
178 
179   // Otherwise, we speculate that these two types will line up and recursively
180   // check the subelements.
181   Entry = DstTy;
182   SpeculativeTypes.push_back(SrcTy);
183 
184   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
185     if (!areTypesIsomorphic(DstTy->getContainedType(I),
186                             SrcTy->getContainedType(I)))
187       return false;
188 
189   // If everything seems to have lined up, then everything is great.
190   return true;
191 }
192 
193 void TypeMapTy::linkDefinedTypeBodies() {
194   SmallVector<Type *, 16> Elements;
195   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
196     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
197     assert(DstSTy->isOpaque());
198 
199     // Map the body of the source type over to a new body for the dest type.
200     Elements.resize(SrcSTy->getNumElements());
201     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
202       Elements[I] = get(SrcSTy->getElementType(I));
203 
204     DstSTy->setBody(Elements, SrcSTy->isPacked());
205     DstStructTypesSet.switchToNonOpaque(DstSTy);
206   }
207   SrcDefinitionsToResolve.clear();
208   DstResolvedOpaqueTypes.clear();
209 }
210 
211 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
212                            ArrayRef<Type *> ETypes) {
213   DTy->setBody(ETypes, STy->isPacked());
214 
215   // Steal STy's name.
216   if (STy->hasName()) {
217     SmallString<16> TmpName = STy->getName();
218     STy->setName("");
219     DTy->setName(TmpName);
220   }
221 
222   DstStructTypesSet.addNonOpaque(DTy);
223 }
224 
225 Type *TypeMapTy::get(Type *Ty) {
226   SmallPtrSet<StructType *, 8> Visited;
227   return get(Ty, Visited);
228 }
229 
230 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
231   // If we already have an entry for this type, return it.
232   Type **Entry = &MappedTypes[Ty];
233   if (*Entry)
234     return *Entry;
235 
236   // These are types that LLVM itself will unique.
237   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
238 
239 #ifndef NDEBUG
240   if (!IsUniqued) {
241     for (auto &Pair : MappedTypes) {
242       assert(!(Pair.first != Ty && Pair.second == Ty) &&
243              "mapping to a source type");
244     }
245   }
246 #endif
247 
248   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
249     StructType *DTy = StructType::create(Ty->getContext());
250     return *Entry = DTy;
251   }
252 
253   // If this is not a recursive type, then just map all of the elements and
254   // then rebuild the type from inside out.
255   SmallVector<Type *, 4> ElementTypes;
256 
257   // If there are no element types to map, then the type is itself.  This is
258   // true for the anonymous {} struct, things like 'float', integers, etc.
259   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
260     return *Entry = Ty;
261 
262   // Remap all of the elements, keeping track of whether any of them change.
263   bool AnyChange = false;
264   ElementTypes.resize(Ty->getNumContainedTypes());
265   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
266     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
267     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
268   }
269 
270   // If we found our type while recursively processing stuff, just use it.
271   Entry = &MappedTypes[Ty];
272   if (*Entry) {
273     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
274       if (DTy->isOpaque()) {
275         auto *STy = cast<StructType>(Ty);
276         finishType(DTy, STy, ElementTypes);
277       }
278     }
279     return *Entry;
280   }
281 
282   // If all of the element types mapped directly over and the type is not
283   // a nomed struct, then the type is usable as-is.
284   if (!AnyChange && IsUniqued)
285     return *Entry = Ty;
286 
287   // Otherwise, rebuild a modified type.
288   switch (Ty->getTypeID()) {
289   default:
290     llvm_unreachable("unknown derived type to remap");
291   case Type::ArrayTyID:
292     return *Entry = ArrayType::get(ElementTypes[0],
293                                    cast<ArrayType>(Ty)->getNumElements());
294   case Type::VectorTyID:
295     return *Entry = VectorType::get(ElementTypes[0],
296                                     cast<VectorType>(Ty)->getNumElements());
297   case Type::PointerTyID:
298     return *Entry = PointerType::get(ElementTypes[0],
299                                      cast<PointerType>(Ty)->getAddressSpace());
300   case Type::FunctionTyID:
301     return *Entry = FunctionType::get(ElementTypes[0],
302                                       makeArrayRef(ElementTypes).slice(1),
303                                       cast<FunctionType>(Ty)->isVarArg());
304   case Type::StructTyID: {
305     auto *STy = cast<StructType>(Ty);
306     bool IsPacked = STy->isPacked();
307     if (IsUniqued)
308       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
309 
310     // If the type is opaque, we can just use it directly.
311     if (STy->isOpaque()) {
312       DstStructTypesSet.addOpaque(STy);
313       return *Entry = Ty;
314     }
315 
316     if (StructType *OldT =
317             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
318       STy->setName("");
319       return *Entry = OldT;
320     }
321 
322     if (!AnyChange) {
323       DstStructTypesSet.addNonOpaque(STy);
324       return *Entry = Ty;
325     }
326 
327     StructType *DTy = StructType::create(Ty->getContext());
328     finishType(DTy, STy, ElementTypes);
329     return *Entry = DTy;
330   }
331   }
332 }
333 
334 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
335                                        const Twine &Msg)
336     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
337 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
338 
339 //===----------------------------------------------------------------------===//
340 // IRLinker implementation.
341 //===----------------------------------------------------------------------===//
342 
343 namespace {
344 class IRLinker;
345 
346 /// Creates prototypes for functions that are lazily linked on the fly. This
347 /// speeds up linking for modules with many/ lazily linked functions of which
348 /// few get used.
349 class GlobalValueMaterializer final : public ValueMaterializer {
350   IRLinker &TheIRLinker;
351 
352 public:
353   GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
354   Value *materialize(Value *V) override;
355 };
356 
357 class LocalValueMaterializer final : public ValueMaterializer {
358   IRLinker &TheIRLinker;
359 
360 public:
361   LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
362   Value *materialize(Value *V) override;
363 };
364 
365 /// Type of the Metadata map in \a ValueToValueMapTy.
366 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
367 
368 /// This is responsible for keeping track of the state used for moving data
369 /// from SrcM to DstM.
370 class IRLinker {
371   Module &DstM;
372   std::unique_ptr<Module> SrcM;
373 
374   /// See IRMover::move().
375   std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
376 
377   TypeMapTy TypeMap;
378   GlobalValueMaterializer GValMaterializer;
379   LocalValueMaterializer LValMaterializer;
380 
381   /// A metadata map that's shared between IRLinker instances.
382   MDMapT &SharedMDs;
383 
384   /// Mapping of values from what they used to be in Src, to what they are now
385   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
386   /// due to the use of Value handles which the Linker doesn't actually need,
387   /// but this allows us to reuse the ValueMapper code.
388   ValueToValueMapTy ValueMap;
389   ValueToValueMapTy AliasValueMap;
390 
391   DenseSet<GlobalValue *> ValuesToLink;
392   std::vector<GlobalValue *> Worklist;
393 
394   void maybeAdd(GlobalValue *GV) {
395     if (ValuesToLink.insert(GV).second)
396       Worklist.push_back(GV);
397   }
398 
399   /// Set to true when all global value body linking is complete (including
400   /// lazy linking). Used to prevent metadata linking from creating new
401   /// references.
402   bool DoneLinkingBodies = false;
403 
404   /// The Error encountered during materialization. We use an Optional here to
405   /// avoid needing to manage an unconsumed success value.
406   Optional<Error> FoundError;
407   void setError(Error E) {
408     if (E)
409       FoundError = std::move(E);
410   }
411 
412   /// Most of the errors produced by this module are inconvertible StringErrors.
413   /// This convenience function lets us return one of those more easily.
414   Error stringErr(const Twine &T) {
415     return make_error<StringError>(T, inconvertibleErrorCode());
416   }
417 
418   /// Entry point for mapping values and alternate context for mapping aliases.
419   ValueMapper Mapper;
420   unsigned AliasMCID;
421 
422   /// Handles cloning of a global values from the source module into
423   /// the destination module, including setting the attributes and visibility.
424   GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
425 
426   void emitWarning(const Twine &Message) {
427     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
428   }
429 
430   /// Given a global in the source module, return the global in the
431   /// destination module that is being linked to, if any.
432   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
433     // If the source has no name it can't link.  If it has local linkage,
434     // there is no name match-up going on.
435     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
436       return nullptr;
437 
438     // Otherwise see if we have a match in the destination module's symtab.
439     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
440     if (!DGV)
441       return nullptr;
442 
443     // If we found a global with the same name in the dest module, but it has
444     // internal linkage, we are really not doing any linkage here.
445     if (DGV->hasLocalLinkage())
446       return nullptr;
447 
448     // Otherwise, we do in fact link to the destination global.
449     return DGV;
450   }
451 
452   void computeTypeMapping();
453 
454   Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
455                                              const GlobalVariable *SrcGV);
456 
457   /// Given the GlobaValue \p SGV in the source module, and the matching
458   /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
459   /// into the destination module.
460   ///
461   /// Note this code may call the client-provided \p AddLazyFor.
462   bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
463   Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
464 
465   Error linkModuleFlagsMetadata();
466 
467   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
468   Error linkFunctionBody(Function &Dst, Function &Src);
469   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
470   Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
471 
472   /// Functions that take care of cloning a specific global value type
473   /// into the destination module.
474   GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
475   Function *copyFunctionProto(const Function *SF);
476   GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
477 
478   void linkNamedMDNodes();
479 
480 public:
481   IRLinker(Module &DstM, MDMapT &SharedMDs,
482            IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
483            ArrayRef<GlobalValue *> ValuesToLink,
484            std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
485       : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
486         TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
487         SharedMDs(SharedMDs),
488         Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
489                &GValMaterializer),
490         AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
491                                                          &LValMaterializer)) {
492     ValueMap.getMDMap() = std::move(SharedMDs);
493     for (GlobalValue *GV : ValuesToLink)
494       maybeAdd(GV);
495   }
496   ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
497 
498   Error run();
499   Value *materialize(Value *V, bool ForAlias);
500 };
501 }
502 
503 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
504 /// table. This is good for all clients except for us. Go through the trouble
505 /// to force this back.
506 static void forceRenaming(GlobalValue *GV, StringRef Name) {
507   // If the global doesn't force its name or if it already has the right name,
508   // there is nothing for us to do.
509   if (GV->hasLocalLinkage() || GV->getName() == Name)
510     return;
511 
512   Module *M = GV->getParent();
513 
514   // If there is a conflict, rename the conflict.
515   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
516     GV->takeName(ConflictGV);
517     ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
518     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
519   } else {
520     GV->setName(Name); // Force the name back
521   }
522 }
523 
524 Value *GlobalValueMaterializer::materialize(Value *SGV) {
525   return TheIRLinker.materialize(SGV, false);
526 }
527 
528 Value *LocalValueMaterializer::materialize(Value *SGV) {
529   return TheIRLinker.materialize(SGV, true);
530 }
531 
532 Value *IRLinker::materialize(Value *V, bool ForAlias) {
533   auto *SGV = dyn_cast<GlobalValue>(V);
534   if (!SGV)
535     return nullptr;
536 
537   Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
538   if (!NewProto) {
539     setError(NewProto.takeError());
540     return nullptr;
541   }
542   if (!*NewProto)
543     return nullptr;
544 
545   GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
546   if (!New)
547     return *NewProto;
548 
549   // If we already created the body, just return.
550   if (auto *F = dyn_cast<Function>(New)) {
551     if (!F->isDeclaration())
552       return New;
553   } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
554     if (V->hasInitializer() || V->hasAppendingLinkage())
555       return New;
556   } else {
557     auto *A = cast<GlobalAlias>(New);
558     if (A->getAliasee())
559       return New;
560   }
561 
562   // When linking a global for an alias, it will always be linked. However we
563   // need to check if it was not already scheduled to satify a reference from a
564   // regular global value initializer. We know if it has been schedule if the
565   // "New" GlobalValue that is mapped here for the alias is the same as the one
566   // already mapped. If there is an entry in the ValueMap but the value is
567   // different, it means that the value already had a definition in the
568   // destination module (linkonce for instance), but we need a new definition
569   // for the alias ("New" will be different.
570   if (ForAlias && ValueMap.lookup(SGV) == New)
571     return New;
572 
573   if (ForAlias || shouldLink(New, *SGV))
574     setError(linkGlobalValueBody(*New, *SGV));
575 
576   return New;
577 }
578 
579 /// Loop through the global variables in the src module and merge them into the
580 /// dest module.
581 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
582   // No linking to be performed or linking from the source: simply create an
583   // identical version of the symbol over in the dest module... the
584   // initializer will be filled in later by LinkGlobalInits.
585   GlobalVariable *NewDGV =
586       new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
587                          SGVar->isConstant(), GlobalValue::ExternalLinkage,
588                          /*init*/ nullptr, SGVar->getName(),
589                          /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
590                          SGVar->getType()->getAddressSpace());
591   NewDGV->setAlignment(SGVar->getAlignment());
592   return NewDGV;
593 }
594 
595 /// Link the function in the source module into the destination module if
596 /// needed, setting up mapping information.
597 Function *IRLinker::copyFunctionProto(const Function *SF) {
598   // If there is no linkage to be performed or we are linking from the source,
599   // bring SF over.
600   return Function::Create(TypeMap.get(SF->getFunctionType()),
601                           GlobalValue::ExternalLinkage, SF->getName(), &DstM);
602 }
603 
604 /// Set up prototypes for any aliases that come over from the source module.
605 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
606   // If there is no linkage to be performed or we're linking from the source,
607   // bring over SGA.
608   auto *Ty = TypeMap.get(SGA->getValueType());
609   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
610                              GlobalValue::ExternalLinkage, SGA->getName(),
611                              &DstM);
612 }
613 
614 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
615                                             bool ForDefinition) {
616   GlobalValue *NewGV;
617   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
618     NewGV = copyGlobalVariableProto(SGVar);
619   } else if (auto *SF = dyn_cast<Function>(SGV)) {
620     NewGV = copyFunctionProto(SF);
621   } else {
622     if (ForDefinition)
623       NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
624     else
625       NewGV = new GlobalVariable(
626           DstM, TypeMap.get(SGV->getValueType()),
627           /*isConstant*/ false, GlobalValue::ExternalLinkage,
628           /*init*/ nullptr, SGV->getName(),
629           /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
630           SGV->getType()->getAddressSpace());
631   }
632 
633   if (ForDefinition)
634     NewGV->setLinkage(SGV->getLinkage());
635   else if (SGV->hasExternalWeakLinkage())
636     NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
637 
638   NewGV->copyAttributesFrom(SGV);
639 
640   // Don't copy the comdat, it's from the original module. We'll handle it
641   // later.
642   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV))
643     NewGO->setComdat(nullptr);
644 
645   // Remove these copied constants in case this stays a declaration, since
646   // they point to the source module. If the def is linked the values will
647   // be mapped in during linkFunctionBody.
648   if (auto *NewF = dyn_cast<Function>(NewGV)) {
649     NewF->setPersonalityFn(nullptr);
650     NewF->setPrefixData(nullptr);
651     NewF->setPrologueData(nullptr);
652   }
653 
654   return NewGV;
655 }
656 
657 /// Loop over all of the linked values to compute type mappings.  For example,
658 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
659 /// types 'Foo' but one got renamed when the module was loaded into the same
660 /// LLVMContext.
661 void IRLinker::computeTypeMapping() {
662   for (GlobalValue &SGV : SrcM->globals()) {
663     GlobalValue *DGV = getLinkedToGlobal(&SGV);
664     if (!DGV)
665       continue;
666 
667     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
668       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
669       continue;
670     }
671 
672     // Unify the element type of appending arrays.
673     ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
674     ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
675     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
676   }
677 
678   for (GlobalValue &SGV : *SrcM)
679     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
680       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
681 
682   for (GlobalValue &SGV : SrcM->aliases())
683     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
684       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
685 
686   // Incorporate types by name, scanning all the types in the source module.
687   // At this point, the destination module may have a type "%foo = { i32 }" for
688   // example.  When the source module got loaded into the same LLVMContext, if
689   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
690   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
691   for (StructType *ST : Types) {
692     if (!ST->hasName())
693       continue;
694 
695     // Check to see if there is a dot in the name followed by a digit.
696     size_t DotPos = ST->getName().rfind('.');
697     if (DotPos == 0 || DotPos == StringRef::npos ||
698         ST->getName().back() == '.' ||
699         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
700       continue;
701 
702     // Check to see if the destination module has a struct with the prefix name.
703     StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
704     if (!DST)
705       continue;
706 
707     // Don't use it if this actually came from the source module. They're in
708     // the same LLVMContext after all. Also don't use it unless the type is
709     // actually used in the destination module. This can happen in situations
710     // like this:
711     //
712     //      Module A                         Module B
713     //      --------                         --------
714     //   %Z = type { %A }                %B = type { %C.1 }
715     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
716     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
717     //   %C = type { i8* }               %B.3 = type { %C.1 }
718     //
719     // When we link Module B with Module A, the '%B' in Module B is
720     // used. However, that would then use '%C.1'. But when we process '%C.1',
721     // we prefer to take the '%C' version. So we are then left with both
722     // '%C.1' and '%C' being used for the same types. This leads to some
723     // variables using one type and some using the other.
724     if (TypeMap.DstStructTypesSet.hasType(DST))
725       TypeMap.addTypeMapping(DST, ST);
726   }
727 
728   // Now that we have discovered all of the type equivalences, get a body for
729   // any 'opaque' types in the dest module that are now resolved.
730   TypeMap.linkDefinedTypeBodies();
731 }
732 
733 static void getArrayElements(const Constant *C,
734                              SmallVectorImpl<Constant *> &Dest) {
735   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
736 
737   for (unsigned i = 0; i != NumElements; ++i)
738     Dest.push_back(C->getAggregateElement(i));
739 }
740 
741 /// If there were any appending global variables, link them together now.
742 Expected<Constant *>
743 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
744                                 const GlobalVariable *SrcGV) {
745   Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
746                     ->getElementType();
747 
748   // FIXME: This upgrade is done during linking to support the C API.  Once the
749   // old form is deprecated, we should move this upgrade to
750   // llvm::UpgradeGlobalVariable() and simplify the logic here and in
751   // Mapper::mapAppendingVariable() in ValueMapper.cpp.
752   StringRef Name = SrcGV->getName();
753   bool IsNewStructor = false;
754   bool IsOldStructor = false;
755   if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
756     if (cast<StructType>(EltTy)->getNumElements() == 3)
757       IsNewStructor = true;
758     else
759       IsOldStructor = true;
760   }
761 
762   PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
763   if (IsOldStructor) {
764     auto &ST = *cast<StructType>(EltTy);
765     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
766     EltTy = StructType::get(SrcGV->getContext(), Tys, false);
767   }
768 
769   uint64_t DstNumElements = 0;
770   if (DstGV) {
771     ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
772     DstNumElements = DstTy->getNumElements();
773 
774     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
775       return stringErr(
776           "Linking globals named '" + SrcGV->getName() +
777           "': can only link appending global with another appending "
778           "global!");
779 
780     // Check to see that they two arrays agree on type.
781     if (EltTy != DstTy->getElementType())
782       return stringErr("Appending variables with different element types!");
783     if (DstGV->isConstant() != SrcGV->isConstant())
784       return stringErr("Appending variables linked with different const'ness!");
785 
786     if (DstGV->getAlignment() != SrcGV->getAlignment())
787       return stringErr(
788           "Appending variables with different alignment need to be linked!");
789 
790     if (DstGV->getVisibility() != SrcGV->getVisibility())
791       return stringErr(
792           "Appending variables with different visibility need to be linked!");
793 
794     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
795       return stringErr(
796           "Appending variables with different unnamed_addr need to be linked!");
797 
798     if (DstGV->getSection() != SrcGV->getSection())
799       return stringErr(
800           "Appending variables with different section name need to be linked!");
801   }
802 
803   SmallVector<Constant *, 16> SrcElements;
804   getArrayElements(SrcGV->getInitializer(), SrcElements);
805 
806   if (IsNewStructor)
807     SrcElements.erase(
808         std::remove_if(SrcElements.begin(), SrcElements.end(),
809                        [this](Constant *E) {
810                          auto *Key = dyn_cast<GlobalValue>(
811                              E->getAggregateElement(2)->stripPointerCasts());
812                          if (!Key)
813                            return false;
814                          GlobalValue *DGV = getLinkedToGlobal(Key);
815                          return !shouldLink(DGV, *Key);
816                        }),
817         SrcElements.end());
818   uint64_t NewSize = DstNumElements + SrcElements.size();
819   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
820 
821   // Create the new global variable.
822   GlobalVariable *NG = new GlobalVariable(
823       DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
824       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
825       SrcGV->getType()->getAddressSpace());
826 
827   NG->copyAttributesFrom(SrcGV);
828   forceRenaming(NG, SrcGV->getName());
829 
830   Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
831 
832   Mapper.scheduleMapAppendingVariable(*NG,
833                                       DstGV ? DstGV->getInitializer() : nullptr,
834                                       IsOldStructor, SrcElements);
835 
836   // Replace any uses of the two global variables with uses of the new
837   // global.
838   if (DstGV) {
839     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
840     DstGV->eraseFromParent();
841   }
842 
843   return Ret;
844 }
845 
846 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
847   if (ValuesToLink.count(&SGV))
848     return true;
849 
850   if (SGV.hasLocalLinkage())
851     return true;
852 
853   if (DGV && !DGV->isDeclarationForLinker())
854     return false;
855 
856   if (SGV.hasAvailableExternallyLinkage())
857     return true;
858 
859   if (SGV.isDeclaration())
860     return false;
861 
862   if (DoneLinkingBodies)
863     return false;
864 
865   // Callback to the client to give a chance to lazily add the Global to the
866   // list of value to link.
867   bool LazilyAdded = false;
868   AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
869     maybeAdd(&GV);
870     LazilyAdded = true;
871   });
872   return LazilyAdded;
873 }
874 
875 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
876                                                     bool ForAlias) {
877   GlobalValue *DGV = getLinkedToGlobal(SGV);
878 
879   bool ShouldLink = shouldLink(DGV, *SGV);
880 
881   // just missing from map
882   if (ShouldLink) {
883     auto I = ValueMap.find(SGV);
884     if (I != ValueMap.end())
885       return cast<Constant>(I->second);
886 
887     I = AliasValueMap.find(SGV);
888     if (I != AliasValueMap.end())
889       return cast<Constant>(I->second);
890   }
891 
892   if (!ShouldLink && ForAlias)
893     DGV = nullptr;
894 
895   // Handle the ultra special appending linkage case first.
896   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
897   if (SGV->hasAppendingLinkage())
898     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
899                                  cast<GlobalVariable>(SGV));
900 
901   GlobalValue *NewGV;
902   if (DGV && !ShouldLink) {
903     NewGV = DGV;
904   } else {
905     // If we are done linking global value bodies (i.e. we are performing
906     // metadata linking), don't link in the global value due to this
907     // reference, simply map it to null.
908     if (DoneLinkingBodies)
909       return nullptr;
910 
911     NewGV = copyGlobalValueProto(SGV, ShouldLink);
912     if (ShouldLink || !ForAlias)
913       forceRenaming(NewGV, SGV->getName());
914   }
915   if (ShouldLink || ForAlias) {
916     if (const Comdat *SC = SGV->getComdat()) {
917       if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
918         Comdat *DC = DstM.getOrInsertComdat(SC->getName());
919         DC->setSelectionKind(SC->getSelectionKind());
920         GO->setComdat(DC);
921       }
922     }
923   }
924 
925   if (!ShouldLink && ForAlias)
926     NewGV->setLinkage(GlobalValue::InternalLinkage);
927 
928   Constant *C = NewGV;
929   if (DGV)
930     C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
931 
932   if (DGV && NewGV != DGV) {
933     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
934     DGV->eraseFromParent();
935   }
936 
937   return C;
938 }
939 
940 /// Update the initializers in the Dest module now that all globals that may be
941 /// referenced are in Dest.
942 void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
943   // Figure out what the initializer looks like in the dest module.
944   Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
945 }
946 
947 /// Copy the source function over into the dest function and fix up references
948 /// to values. At this point we know that Dest is an external function, and
949 /// that Src is not.
950 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
951   assert(Dst.isDeclaration() && !Src.isDeclaration());
952 
953   // Materialize if needed.
954   if (std::error_code EC = Src.materialize())
955     return errorCodeToError(EC);
956 
957   // Link in the operands without remapping.
958   if (Src.hasPrefixData())
959     Dst.setPrefixData(Src.getPrefixData());
960   if (Src.hasPrologueData())
961     Dst.setPrologueData(Src.getPrologueData());
962   if (Src.hasPersonalityFn())
963     Dst.setPersonalityFn(Src.getPersonalityFn());
964 
965   // Copy over the metadata attachments without remapping.
966   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
967   Src.getAllMetadata(MDs);
968   for (const auto &I : MDs)
969     Dst.setMetadata(I.first, I.second);
970 
971   // Steal arguments and splice the body of Src into Dst.
972   Dst.stealArgumentListFrom(Src);
973   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
974 
975   // Everything has been moved over.  Remap it.
976   Mapper.scheduleRemapFunction(Dst);
977   return Error::success();
978 }
979 
980 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
981   Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
982 }
983 
984 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
985   if (auto *F = dyn_cast<Function>(&Src))
986     return linkFunctionBody(cast<Function>(Dst), *F);
987   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
988     linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
989     return Error::success();
990   }
991   linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
992   return Error::success();
993 }
994 
995 /// Insert all of the named MDNodes in Src into the Dest module.
996 void IRLinker::linkNamedMDNodes() {
997   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
998   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
999     // Don't link module flags here. Do them separately.
1000     if (&NMD == SrcModFlags)
1001       continue;
1002     NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1003     // Add Src elements into Dest node.
1004     for (const MDNode *Op : NMD.operands())
1005       DestNMD->addOperand(Mapper.mapMDNode(*Op));
1006   }
1007 }
1008 
1009 /// Merge the linker flags in Src into the Dest module.
1010 Error IRLinker::linkModuleFlagsMetadata() {
1011   // If the source module has no module flags, we are done.
1012   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1013   if (!SrcModFlags)
1014     return Error::success();
1015 
1016   // If the destination module doesn't have module flags yet, then just copy
1017   // over the source module's flags.
1018   NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1019   if (DstModFlags->getNumOperands() == 0) {
1020     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1021       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1022 
1023     return Error::success();
1024   }
1025 
1026   // First build a map of the existing module flags and requirements.
1027   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1028   SmallSetVector<MDNode *, 16> Requirements;
1029   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1030     MDNode *Op = DstModFlags->getOperand(I);
1031     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1032     MDString *ID = cast<MDString>(Op->getOperand(1));
1033 
1034     if (Behavior->getZExtValue() == Module::Require) {
1035       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1036     } else {
1037       Flags[ID] = std::make_pair(Op, I);
1038     }
1039   }
1040 
1041   // Merge in the flags from the source module, and also collect its set of
1042   // requirements.
1043   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1044     MDNode *SrcOp = SrcModFlags->getOperand(I);
1045     ConstantInt *SrcBehavior =
1046         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1047     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1048     MDNode *DstOp;
1049     unsigned DstIndex;
1050     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1051     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1052 
1053     // If this is a requirement, add it and continue.
1054     if (SrcBehaviorValue == Module::Require) {
1055       // If the destination module does not already have this requirement, add
1056       // it.
1057       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1058         DstModFlags->addOperand(SrcOp);
1059       }
1060       continue;
1061     }
1062 
1063     // If there is no existing flag with this ID, just add it.
1064     if (!DstOp) {
1065       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1066       DstModFlags->addOperand(SrcOp);
1067       continue;
1068     }
1069 
1070     // Otherwise, perform a merge.
1071     ConstantInt *DstBehavior =
1072         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1073     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1074 
1075     // If either flag has override behavior, handle it first.
1076     if (DstBehaviorValue == Module::Override) {
1077       // Diagnose inconsistent flags which both have override behavior.
1078       if (SrcBehaviorValue == Module::Override &&
1079           SrcOp->getOperand(2) != DstOp->getOperand(2))
1080         return stringErr("linking module flags '" + ID->getString() +
1081                          "': IDs have conflicting override values");
1082       continue;
1083     } else if (SrcBehaviorValue == Module::Override) {
1084       // Update the destination flag to that of the source.
1085       DstModFlags->setOperand(DstIndex, SrcOp);
1086       Flags[ID].first = SrcOp;
1087       continue;
1088     }
1089 
1090     // Diagnose inconsistent merge behavior types.
1091     if (SrcBehaviorValue != DstBehaviorValue)
1092       return stringErr("linking module flags '" + ID->getString() +
1093                        "': IDs have conflicting behaviors");
1094 
1095     auto replaceDstValue = [&](MDNode *New) {
1096       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1097       MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1098       DstModFlags->setOperand(DstIndex, Flag);
1099       Flags[ID].first = Flag;
1100     };
1101 
1102     // Perform the merge for standard behavior types.
1103     switch (SrcBehaviorValue) {
1104     case Module::Require:
1105     case Module::Override:
1106       llvm_unreachable("not possible");
1107     case Module::Error: {
1108       // Emit an error if the values differ.
1109       if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1110         return stringErr("linking module flags '" + ID->getString() +
1111                          "': IDs have conflicting values");
1112       continue;
1113     }
1114     case Module::Warning: {
1115       // Emit a warning if the values differ.
1116       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1117         emitWarning("linking module flags '" + ID->getString() +
1118                     "': IDs have conflicting values");
1119       }
1120       continue;
1121     }
1122     case Module::Append: {
1123       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1124       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1125       SmallVector<Metadata *, 8> MDs;
1126       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1127       MDs.append(DstValue->op_begin(), DstValue->op_end());
1128       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1129 
1130       replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1131       break;
1132     }
1133     case Module::AppendUnique: {
1134       SmallSetVector<Metadata *, 16> Elts;
1135       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1136       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1137       Elts.insert(DstValue->op_begin(), DstValue->op_end());
1138       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1139 
1140       replaceDstValue(MDNode::get(DstM.getContext(),
1141                                   makeArrayRef(Elts.begin(), Elts.end())));
1142       break;
1143     }
1144     }
1145   }
1146 
1147   // Check all of the requirements.
1148   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1149     MDNode *Requirement = Requirements[I];
1150     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1151     Metadata *ReqValue = Requirement->getOperand(1);
1152 
1153     MDNode *Op = Flags[Flag].first;
1154     if (!Op || Op->getOperand(2) != ReqValue)
1155       return stringErr("linking module flags '" + Flag->getString() +
1156                        "': does not have the required value");
1157   }
1158   return Error::success();
1159 }
1160 
1161 // This function returns true if the triples match.
1162 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1163   // If vendor is apple, ignore the version number.
1164   if (T0.getVendor() == Triple::Apple)
1165     return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1166            T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1167 
1168   return T0 == T1;
1169 }
1170 
1171 // This function returns the merged triple.
1172 static std::string mergeTriples(const Triple &SrcTriple,
1173                                 const Triple &DstTriple) {
1174   // If vendor is apple, pick the triple with the larger version number.
1175   if (SrcTriple.getVendor() == Triple::Apple)
1176     if (DstTriple.isOSVersionLT(SrcTriple))
1177       return SrcTriple.str();
1178 
1179   return DstTriple.str();
1180 }
1181 
1182 Error IRLinker::run() {
1183   // Ensure metadata materialized before value mapping.
1184   if (SrcM->getMaterializer())
1185     if (std::error_code EC = SrcM->getMaterializer()->materializeMetadata())
1186       return errorCodeToError(EC);
1187 
1188   // Inherit the target data from the source module if the destination module
1189   // doesn't have one already.
1190   if (DstM.getDataLayout().isDefault())
1191     DstM.setDataLayout(SrcM->getDataLayout());
1192 
1193   if (SrcM->getDataLayout() != DstM.getDataLayout()) {
1194     emitWarning("Linking two modules of different data layouts: '" +
1195                 SrcM->getModuleIdentifier() + "' is '" +
1196                 SrcM->getDataLayoutStr() + "' whereas '" +
1197                 DstM.getModuleIdentifier() + "' is '" +
1198                 DstM.getDataLayoutStr() + "'\n");
1199   }
1200 
1201   // Copy the target triple from the source to dest if the dest's is empty.
1202   if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1203     DstM.setTargetTriple(SrcM->getTargetTriple());
1204 
1205   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1206 
1207   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1208     emitWarning("Linking two modules of different target triples: " +
1209                 SrcM->getModuleIdentifier() + "' is '" +
1210                 SrcM->getTargetTriple() + "' whereas '" +
1211                 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1212                 "'\n");
1213 
1214   DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1215 
1216   // Append the module inline asm string.
1217   if (!SrcM->getModuleInlineAsm().empty()) {
1218     if (DstM.getModuleInlineAsm().empty())
1219       DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
1220     else
1221       DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1222                               SrcM->getModuleInlineAsm());
1223   }
1224 
1225   // Loop over all of the linked values to compute type mappings.
1226   computeTypeMapping();
1227 
1228   std::reverse(Worklist.begin(), Worklist.end());
1229   while (!Worklist.empty()) {
1230     GlobalValue *GV = Worklist.back();
1231     Worklist.pop_back();
1232 
1233     // Already mapped.
1234     if (ValueMap.find(GV) != ValueMap.end() ||
1235         AliasValueMap.find(GV) != AliasValueMap.end())
1236       continue;
1237 
1238     assert(!GV->isDeclaration());
1239     Mapper.mapValue(*GV);
1240     if (FoundError)
1241       return std::move(*FoundError);
1242   }
1243 
1244   // Note that we are done linking global value bodies. This prevents
1245   // metadata linking from creating new references.
1246   DoneLinkingBodies = true;
1247   Mapper.addFlags(RF_NullMapMissingGlobalValues);
1248 
1249   // Remap all of the named MDNodes in Src into the DstM module. We do this
1250   // after linking GlobalValues so that MDNodes that reference GlobalValues
1251   // are properly remapped.
1252   linkNamedMDNodes();
1253 
1254   // Merge the module flags into the DstM module.
1255   return linkModuleFlagsMetadata();
1256 }
1257 
1258 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1259     : ETypes(E), IsPacked(P) {}
1260 
1261 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1262     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1263 
1264 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1265   if (IsPacked != That.IsPacked)
1266     return false;
1267   if (ETypes != That.ETypes)
1268     return false;
1269   return true;
1270 }
1271 
1272 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1273   return !this->operator==(That);
1274 }
1275 
1276 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1277   return DenseMapInfo<StructType *>::getEmptyKey();
1278 }
1279 
1280 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1281   return DenseMapInfo<StructType *>::getTombstoneKey();
1282 }
1283 
1284 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1285   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1286                       Key.IsPacked);
1287 }
1288 
1289 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1290   return getHashValue(KeyTy(ST));
1291 }
1292 
1293 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1294                                          const StructType *RHS) {
1295   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1296     return false;
1297   return LHS == KeyTy(RHS);
1298 }
1299 
1300 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1301                                          const StructType *RHS) {
1302   if (RHS == getEmptyKey())
1303     return LHS == getEmptyKey();
1304 
1305   if (RHS == getTombstoneKey())
1306     return LHS == getTombstoneKey();
1307 
1308   return KeyTy(LHS) == KeyTy(RHS);
1309 }
1310 
1311 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1312   assert(!Ty->isOpaque());
1313   NonOpaqueStructTypes.insert(Ty);
1314 }
1315 
1316 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1317   assert(!Ty->isOpaque());
1318   NonOpaqueStructTypes.insert(Ty);
1319   bool Removed = OpaqueStructTypes.erase(Ty);
1320   (void)Removed;
1321   assert(Removed);
1322 }
1323 
1324 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1325   assert(Ty->isOpaque());
1326   OpaqueStructTypes.insert(Ty);
1327 }
1328 
1329 StructType *
1330 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1331                                                 bool IsPacked) {
1332   IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1333   auto I = NonOpaqueStructTypes.find_as(Key);
1334   if (I == NonOpaqueStructTypes.end())
1335     return nullptr;
1336   return *I;
1337 }
1338 
1339 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1340   if (Ty->isOpaque())
1341     return OpaqueStructTypes.count(Ty);
1342   auto I = NonOpaqueStructTypes.find(Ty);
1343   if (I == NonOpaqueStructTypes.end())
1344     return false;
1345   return *I == Ty;
1346 }
1347 
1348 IRMover::IRMover(Module &M) : Composite(M) {
1349   TypeFinder StructTypes;
1350   StructTypes.run(M, true);
1351   for (StructType *Ty : StructTypes) {
1352     if (Ty->isOpaque())
1353       IdentifiedStructTypes.addOpaque(Ty);
1354     else
1355       IdentifiedStructTypes.addNonOpaque(Ty);
1356   }
1357 }
1358 
1359 Error IRMover::move(
1360     std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
1361     std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
1362   IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1363                        std::move(Src), ValuesToLink, AddLazyFor);
1364   Error E = TheIRLinker.run();
1365   Composite.dropTriviallyDeadConstantArrays();
1366   return E;
1367 }
1368