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