]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/Linker/LinkModules.cpp
f9fba5e0a8008d8c14b489c0c159a2a0f8ef1d19
[opencl/llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
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 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/TypeFinder.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/Cloning.h"
32 #include <cctype>
33 #include <tuple>
34 using namespace llvm;
37 //===----------------------------------------------------------------------===//
38 // TypeMap implementation.
39 //===----------------------------------------------------------------------===//
41 namespace {
42 class TypeMapTy : public ValueMapTypeRemapper {
43   /// This is a mapping from a source type to a destination type to use.
44   DenseMap<Type*, Type*> MappedTypes;
46   /// When checking to see if two subgraphs are isomorphic, we speculatively
47   /// add types to MappedTypes, but keep track of them here in case we need to
48   /// roll back.
49   SmallVector<Type*, 16> SpeculativeTypes;
51   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
53   /// This is a list of non-opaque structs in the source module that are mapped
54   /// to an opaque struct in the destination module.
55   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
57   /// This is the set of opaque types in the destination modules who are
58   /// getting a body from the source module.
59   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
61 public:
62   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
63       : DstStructTypesSet(DstStructTypesSet) {}
65   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
66   /// Indicate that the specified type in the destination module is conceptually
67   /// equivalent to the specified type in the source module.
68   void addTypeMapping(Type *DstTy, Type *SrcTy);
70   /// Produce a body for an opaque type in the dest module from a type
71   /// definition in the source module.
72   void linkDefinedTypeBodies();
74   /// Return the mapped type to use for the specified input type from the
75   /// source module.
76   Type *get(Type *SrcTy);
77   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
79   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
81   FunctionType *get(FunctionType *T) {
82     return cast<FunctionType>(get((Type *)T));
83   }
85   /// Dump out the type map for debugging purposes.
86   void dump() const {
87     for (auto &Pair : MappedTypes) {
88       dbgs() << "TypeMap: ";
89       Pair.first->print(dbgs());
90       dbgs() << " => ";
91       Pair.second->print(dbgs());
92       dbgs() << '\n';
93     }
94   }
96 private:
97   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
99   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
100 };
103 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
104   assert(SpeculativeTypes.empty());
105   assert(SpeculativeDstOpaqueTypes.empty());
107   // Check to see if these types are recursively isomorphic and establish a
108   // mapping between them if so.
109   if (!areTypesIsomorphic(DstTy, SrcTy)) {
110     // Oops, they aren't isomorphic.  Just discard this request by rolling out
111     // any speculative mappings we've established.
112     for (Type *Ty : SpeculativeTypes)
113       MappedTypes.erase(Ty);
115     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
116                                    SpeculativeDstOpaqueTypes.size());
117     for (StructType *Ty : SpeculativeDstOpaqueTypes)
118       DstResolvedOpaqueTypes.erase(Ty);
119   } else {
120     for (Type *Ty : SpeculativeTypes)
121       if (auto *STy = dyn_cast<StructType>(Ty))
122         if (STy->hasName())
123           STy->setName("");
124   }
125   SpeculativeTypes.clear();
126   SpeculativeDstOpaqueTypes.clear();
129 /// Recursively walk this pair of types, returning true if they are isomorphic,
130 /// false if they are not.
131 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
132   // Two types with differing kinds are clearly not isomorphic.
133   if (DstTy->getTypeID() != SrcTy->getTypeID())
134     return false;
136   // If we have an entry in the MappedTypes table, then we have our answer.
137   Type *&Entry = MappedTypes[SrcTy];
138   if (Entry)
139     return Entry == DstTy;
141   // Two identical types are clearly isomorphic.  Remember this
142   // non-speculatively.
143   if (DstTy == SrcTy) {
144     Entry = DstTy;
145     return true;
146   }
148   // Okay, we have two types with identical kinds that we haven't seen before.
150   // If this is an opaque struct type, special case it.
151   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
152     // Mapping an opaque type to any struct, just keep the dest struct.
153     if (SSTy->isOpaque()) {
154       Entry = DstTy;
155       SpeculativeTypes.push_back(SrcTy);
156       return true;
157     }
159     // Mapping a non-opaque source type to an opaque dest.  If this is the first
160     // type that we're mapping onto this destination type then we succeed.  Keep
161     // the dest, but fill it in later. If this is the second (different) type
162     // that we're trying to map onto the same opaque type then we fail.
163     if (cast<StructType>(DstTy)->isOpaque()) {
164       // We can only map one source type onto the opaque destination type.
165       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
166         return false;
167       SrcDefinitionsToResolve.push_back(SSTy);
168       SpeculativeTypes.push_back(SrcTy);
169       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
170       Entry = DstTy;
171       return true;
172     }
173   }
175   // If the number of subtypes disagree between the two types, then we fail.
176   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
177     return false;
179   // Fail if any of the extra properties (e.g. array size) of the type disagree.
180   if (isa<IntegerType>(DstTy))
181     return false;  // bitwidth disagrees.
182   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
183     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
184       return false;
186   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
187     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
188       return false;
189   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
190     StructType *SSTy = cast<StructType>(SrcTy);
191     if (DSTy->isLiteral() != SSTy->isLiteral() ||
192         DSTy->isPacked() != SSTy->isPacked())
193       return false;
194   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
195     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
196       return false;
197   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
198     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
199       return false;
200   }
202   // Otherwise, we speculate that these two types will line up and recursively
203   // check the subelements.
204   Entry = DstTy;
205   SpeculativeTypes.push_back(SrcTy);
207   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
208     if (!areTypesIsomorphic(DstTy->getContainedType(I),
209                             SrcTy->getContainedType(I)))
210       return false;
212   // If everything seems to have lined up, then everything is great.
213   return true;
216 void TypeMapTy::linkDefinedTypeBodies() {
217   SmallVector<Type*, 16> Elements;
218   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
219     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
220     assert(DstSTy->isOpaque());
222     // Map the body of the source type over to a new body for the dest type.
223     Elements.resize(SrcSTy->getNumElements());
224     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
225       Elements[I] = get(SrcSTy->getElementType(I));
227     DstSTy->setBody(Elements, SrcSTy->isPacked());
228   }
229   SrcDefinitionsToResolve.clear();
230   DstResolvedOpaqueTypes.clear();
233 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
234                            ArrayRef<Type *> ETypes) {
235   DTy->setBody(ETypes, STy->isPacked());
237   // Steal STy's name.
238   if (STy->hasName()) {
239     SmallString<16> TmpName = STy->getName();
240     STy->setName("");
241     DTy->setName(TmpName);
242   }
244   DstStructTypesSet.addNonOpaque(DTy);
247 Type *TypeMapTy::get(Type *Ty) {
248   SmallPtrSet<StructType *, 8> Visited;
249   return get(Ty, Visited);
252 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
253   // If we already have an entry for this type, return it.
254   Type **Entry = &MappedTypes[Ty];
255   if (*Entry)
256     return *Entry;
258   // These are types that LLVM itself will unique.
259   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
261 #ifndef NDEBUG
262   if (!IsUniqued) {
263     for (auto &Pair : MappedTypes) {
264       assert(!(Pair.first != Ty && Pair.second == Ty) &&
265              "mapping to a source type");
266     }
267   }
268 #endif
270   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
271     StructType *DTy = StructType::create(Ty->getContext());
272     return *Entry = DTy;
273   }
275   // If this is not a recursive type, then just map all of the elements and
276   // then rebuild the type from inside out.
277   SmallVector<Type *, 4> ElementTypes;
279   // If there are no element types to map, then the type is itself.  This is
280   // true for the anonymous {} struct, things like 'float', integers, etc.
281   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
282     return *Entry = Ty;
284   // Remap all of the elements, keeping track of whether any of them change.
285   bool AnyChange = false;
286   ElementTypes.resize(Ty->getNumContainedTypes());
287   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
288     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
289     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
290   }
292   // If we found our type while recursively processing stuff, just use it.
293   Entry = &MappedTypes[Ty];
294   if (*Entry) {
295     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
296       if (DTy->isOpaque()) {
297         auto *STy = cast<StructType>(Ty);
298         finishType(DTy, STy, ElementTypes);
299       }
300     }
301     return *Entry;
302   }
304   // If all of the element types mapped directly over and the type is not
305   // a nomed struct, then the type is usable as-is.
306   if (!AnyChange && IsUniqued)
307     return *Entry = Ty;
309   // Otherwise, rebuild a modified type.
310   switch (Ty->getTypeID()) {
311   default:
312     llvm_unreachable("unknown derived type to remap");
313   case Type::ArrayTyID:
314     return *Entry = ArrayType::get(ElementTypes[0],
315                                    cast<ArrayType>(Ty)->getNumElements());
316   case Type::VectorTyID:
317     return *Entry = VectorType::get(ElementTypes[0],
318                                     cast<VectorType>(Ty)->getNumElements());
319   case Type::PointerTyID:
320     return *Entry = PointerType::get(ElementTypes[0],
321                                      cast<PointerType>(Ty)->getAddressSpace());
322   case Type::FunctionTyID:
323     return *Entry = FunctionType::get(ElementTypes[0],
324                                       makeArrayRef(ElementTypes).slice(1),
325                                       cast<FunctionType>(Ty)->isVarArg());
326   case Type::StructTyID: {
327     auto *STy = cast<StructType>(Ty);
328     bool IsPacked = STy->isPacked();
329     if (IsUniqued)
330       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
332     // If the type is opaque, we can just use it directly.
333     if (STy->isOpaque()) {
334       DstStructTypesSet.addOpaque(STy);
335       return *Entry = Ty;
336     }
338     if (StructType *OldT =
339             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
340       STy->setName("");
341       return *Entry = OldT;
342     }
344     if (!AnyChange) {
345       DstStructTypesSet.addNonOpaque(STy);
346       return *Entry = Ty;
347     }
349     StructType *DTy = StructType::create(Ty->getContext());
350     finishType(DTy, STy, ElementTypes);
351     return *Entry = DTy;
352   }
353   }
356 //===----------------------------------------------------------------------===//
357 // ModuleLinker implementation.
358 //===----------------------------------------------------------------------===//
360 namespace {
361 class ModuleLinker;
363 /// Creates prototypes for functions that are lazily linked on the fly. This
364 /// speeds up linking for modules with many/ lazily linked functions of which
365 /// few get used.
366 class ValueMaterializerTy : public ValueMaterializer {
367   TypeMapTy &TypeMap;
368   Module *DstM;
369   std::vector<GlobalValue *> &LazilyLinkGlobalValues;
371 public:
372   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
373                       std::vector<GlobalValue *> &LazilyLinkGlobalValues)
374       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
375         LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
377   Value *materializeValueFor(Value *V) override;
378 };
380 class LinkDiagnosticInfo : public DiagnosticInfo {
381   const Twine &Msg;
383 public:
384   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
385   void print(DiagnosticPrinter &DP) const override;
386 };
387 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
388                                        const Twine &Msg)
389     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
390 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
392 /// This is an implementation class for the LinkModules function, which is the
393 /// entrypoint for this file.
394 class ModuleLinker {
395   Module *DstM, *SrcM;
397   TypeMapTy TypeMap;
398   ValueMaterializerTy ValMaterializer;
400   /// Mapping of values from what they used to be in Src, to what they are now
401   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
402   /// due to the use of Value handles which the Linker doesn't actually need,
403   /// but this allows us to reuse the ValueMapper code.
404   ValueToValueMapTy ValueMap;
406   struct AppendingVarInfo {
407     GlobalVariable *NewGV;   // New aggregate global in dest module.
408     const Constant *DstInit; // Old initializer from dest module.
409     const Constant *SrcInit; // Old initializer from src module.
410   };
412   std::vector<AppendingVarInfo> AppendingVars;
414   // Set of items not to link in from source.
415   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
417   // Vector of GlobalValues to lazily link in.
418   std::vector<GlobalValue *> LazilyLinkGlobalValues;
420   /// Functions that have replaced other functions.
421   SmallPtrSet<const Function *, 16> OverridingFunctions;
423   Linker::DiagnosticHandlerFunction DiagnosticHandler;
425 public:
426   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
427                Linker::DiagnosticHandlerFunction DiagnosticHandler)
428       : DstM(dstM), SrcM(srcM), TypeMap(Set),
429         ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
430         DiagnosticHandler(DiagnosticHandler) {}
432   bool run();
434 private:
435   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
436                             const GlobalValue &Src);
438   /// Helper method for setting a message and returning an error code.
439   bool emitError(const Twine &Message) {
440     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
441     return true;
442   }
444   void emitWarning(const Twine &Message) {
445     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
446   }
448   bool getComdatLeader(Module *M, StringRef ComdatName,
449                        const GlobalVariable *&GVar);
450   bool computeResultingSelectionKind(StringRef ComdatName,
451                                      Comdat::SelectionKind Src,
452                                      Comdat::SelectionKind Dst,
453                                      Comdat::SelectionKind &Result,
454                                      bool &LinkFromSrc);
455   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
456       ComdatsChosen;
457   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
458                        bool &LinkFromSrc);
460   /// Given a global in the source module, return the global in the
461   /// destination module that is being linked to, if any.
462   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
463     // If the source has no name it can't link.  If it has local linkage,
464     // there is no name match-up going on.
465     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
466       return nullptr;
468     // Otherwise see if we have a match in the destination module's symtab.
469     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
470     if (!DGV)
471       return nullptr;
473     // If we found a global with the same name in the dest module, but it has
474     // internal linkage, we are really not doing any linkage here.
475     if (DGV->hasLocalLinkage())
476       return nullptr;
478     // Otherwise, we do in fact link to the destination global.
479     return DGV;
480   }
482   void computeTypeMapping();
484   void upgradeMismatchedGlobalArray(StringRef Name);
485   void upgradeMismatchedGlobals();
487   bool linkAppendingVarProto(GlobalVariable *DstGV,
488                              const GlobalVariable *SrcGV);
490   bool linkGlobalValueProto(GlobalValue *GV);
491   bool linkModuleFlagsMetadata();
493   void linkAppendingVarInit(const AppendingVarInfo &AVI);
495   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496   bool linkFunctionBody(Function &Dst, Function &Src);
497   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498   bool linkGlobalValueBody(GlobalValue &Src);
500   void linkNamedMDNodes();
501   void stripReplacedSubprograms();
502 };
505 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
506 /// table. This is good for all clients except for us. Go through the trouble
507 /// to force this back.
508 static void forceRenaming(GlobalValue *GV, StringRef Name) {
509   // If the global doesn't force its name or if it already has the right name,
510   // there is nothing for us to do.
511   if (GV->hasLocalLinkage() || GV->getName() == Name)
512     return;
514   Module *M = GV->getParent();
516   // If there is a conflict, rename the conflict.
517   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
518     GV->takeName(ConflictGV);
519     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
520     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
521   } else {
522     GV->setName(Name);              // Force the name back
523   }
526 /// copy additional attributes (those not needed to construct a GlobalValue)
527 /// from the SrcGV to the DestGV.
528 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
529   DestGV->copyAttributesFrom(SrcGV);
530   forceRenaming(DestGV, SrcGV->getName());
533 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
534                                GlobalValue::VisibilityTypes b) {
535   if (a == GlobalValue::HiddenVisibility)
536     return false;
537   if (b == GlobalValue::HiddenVisibility)
538     return true;
539   if (a == GlobalValue::ProtectedVisibility)
540     return false;
541   if (b == GlobalValue::ProtectedVisibility)
542     return true;
543   return false;
546 /// Loop through the global variables in the src module and merge them into the
547 /// dest module.
548 static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
549                                                const GlobalVariable *SGVar) {
550   // No linking to be performed or linking from the source: simply create an
551   // identical version of the symbol over in the dest module... the
552   // initializer will be filled in later by LinkGlobalInits.
553   GlobalVariable *NewDGV = new GlobalVariable(
554       DstM, TypeMap.get(SGVar->getType()->getElementType()),
555       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
556       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
557       SGVar->getType()->getAddressSpace());
559   return NewDGV;
562 /// Link the function in the source module into the destination module if
563 /// needed, setting up mapping information.
564 static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
565                                    const Function *SF) {
566   // If there is no linkage to be performed or we are linking from the source,
567   // bring SF over.
568   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
569                           SF->getName(), &DstM);
572 /// Set up prototypes for any aliases that come over from the source module.
573 static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
574                                          const GlobalAlias *SGA) {
575   // If there is no linkage to be performed or we're linking from the source,
576   // bring over SGA.
577   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
578   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
579                              SGA->getLinkage(), SGA->getName(), &DstM);
582 static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
583                                          const GlobalValue *SGV) {
584   GlobalValue *NewGV;
585   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
586     NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
587   else if (auto *SF = dyn_cast<Function>(SGV))
588     NewGV = copyFunctionProto(TypeMap, DstM, SF);
589   else
590     NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
591   copyGVAttributes(NewGV, SGV);
592   return NewGV;
595 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
596   auto *SGV = dyn_cast<GlobalValue>(V);
597   if (!SGV)
598     return nullptr;
600   GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
602   if (Comdat *SC = SGV->getComdat()) {
603     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
604       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
605       DGO->setComdat(DC);
606     }
607   }
609   LazilyLinkGlobalValues.push_back(SGV);
610   return DGV;
613 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
614                                    const GlobalVariable *&GVar) {
615   const GlobalValue *GVal = M->getNamedValue(ComdatName);
616   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
617     GVal = GA->getBaseObject();
618     if (!GVal)
619       // We cannot resolve the size of the aliasee yet.
620       return emitError("Linking COMDATs named '" + ComdatName +
621                        "': COMDAT key involves incomputable alias size.");
622   }
624   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
625   if (!GVar)
626     return emitError(
627         "Linking COMDATs named '" + ComdatName +
628         "': GlobalVariable required for data dependent selection!");
630   return false;
633 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
634                                                  Comdat::SelectionKind Src,
635                                                  Comdat::SelectionKind Dst,
636                                                  Comdat::SelectionKind &Result,
637                                                  bool &LinkFromSrc) {
638   // The ability to mix Comdat::SelectionKind::Any with
639   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
640   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
641                          Dst == Comdat::SelectionKind::Largest;
642   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
643                          Src == Comdat::SelectionKind::Largest;
644   if (DstAnyOrLargest && SrcAnyOrLargest) {
645     if (Dst == Comdat::SelectionKind::Largest ||
646         Src == Comdat::SelectionKind::Largest)
647       Result = Comdat::SelectionKind::Largest;
648     else
649       Result = Comdat::SelectionKind::Any;
650   } else if (Src == Dst) {
651     Result = Dst;
652   } else {
653     return emitError("Linking COMDATs named '" + ComdatName +
654                      "': invalid selection kinds!");
655   }
657   switch (Result) {
658   case Comdat::SelectionKind::Any:
659     // Go with Dst.
660     LinkFromSrc = false;
661     break;
662   case Comdat::SelectionKind::NoDuplicates:
663     return emitError("Linking COMDATs named '" + ComdatName +
664                      "': noduplicates has been violated!");
665   case Comdat::SelectionKind::ExactMatch:
666   case Comdat::SelectionKind::Largest:
667   case Comdat::SelectionKind::SameSize: {
668     const GlobalVariable *DstGV;
669     const GlobalVariable *SrcGV;
670     if (getComdatLeader(DstM, ComdatName, DstGV) ||
671         getComdatLeader(SrcM, ComdatName, SrcGV))
672       return true;
674     const DataLayout *DstDL = DstM->getDataLayout();
675     const DataLayout *SrcDL = SrcM->getDataLayout();
676     if (!DstDL || !SrcDL) {
677       return emitError(
678           "Linking COMDATs named '" + ComdatName +
679           "': can't do size dependent selection without DataLayout!");
680     }
681     uint64_t DstSize =
682         DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
683     uint64_t SrcSize =
684         SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
685     if (Result == Comdat::SelectionKind::ExactMatch) {
686       if (SrcGV->getInitializer() != DstGV->getInitializer())
687         return emitError("Linking COMDATs named '" + ComdatName +
688                          "': ExactMatch violated!");
689       LinkFromSrc = false;
690     } else if (Result == Comdat::SelectionKind::Largest) {
691       LinkFromSrc = SrcSize > DstSize;
692     } else if (Result == Comdat::SelectionKind::SameSize) {
693       if (SrcSize != DstSize)
694         return emitError("Linking COMDATs named '" + ComdatName +
695                          "': SameSize violated!");
696       LinkFromSrc = false;
697     } else {
698       llvm_unreachable("unknown selection kind");
699     }
700     break;
701   }
702   }
704   return false;
707 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
708                                    Comdat::SelectionKind &Result,
709                                    bool &LinkFromSrc) {
710   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
711   StringRef ComdatName = SrcC->getName();
712   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
713   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
715   if (DstCI == ComdatSymTab.end()) {
716     // Use the comdat if it is only available in one of the modules.
717     LinkFromSrc = true;
718     Result = SSK;
719     return false;
720   }
722   const Comdat *DstC = &DstCI->second;
723   Comdat::SelectionKind DSK = DstC->getSelectionKind();
724   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
725                                        LinkFromSrc);
728 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
729                                         const GlobalValue &Dest,
730                                         const GlobalValue &Src) {
731   // We always have to add Src if it has appending linkage.
732   if (Src.hasAppendingLinkage()) {
733     LinkFromSrc = true;
734     return false;
735   }
737   bool SrcIsDeclaration = Src.isDeclarationForLinker();
738   bool DestIsDeclaration = Dest.isDeclarationForLinker();
740   if (SrcIsDeclaration) {
741     // If Src is external or if both Src & Dest are external..  Just link the
742     // external globals, we aren't adding anything.
743     if (Src.hasDLLImportStorageClass()) {
744       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
745       LinkFromSrc = DestIsDeclaration;
746       return false;
747     }
748     // If the Dest is weak, use the source linkage.
749     LinkFromSrc = Dest.hasExternalWeakLinkage();
750     return false;
751   }
753   if (DestIsDeclaration) {
754     // If Dest is external but Src is not:
755     LinkFromSrc = true;
756     return false;
757   }
759   if (Src.hasCommonLinkage()) {
760     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
761       LinkFromSrc = true;
762       return false;
763     }
765     if (!Dest.hasCommonLinkage()) {
766       LinkFromSrc = false;
767       return false;
768     }
770     // FIXME: Make datalayout mandatory and just use getDataLayout().
771     DataLayout DL(Dest.getParent());
773     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
774     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
775     LinkFromSrc = SrcSize > DestSize;
776     return false;
777   }
779   if (Src.isWeakForLinker()) {
780     assert(!Dest.hasExternalWeakLinkage());
781     assert(!Dest.hasAvailableExternallyLinkage());
783     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
784       LinkFromSrc = true;
785       return false;
786     }
788     LinkFromSrc = false;
789     return false;
790   }
792   if (Dest.isWeakForLinker()) {
793     assert(Src.hasExternalLinkage());
794     LinkFromSrc = true;
795     return false;
796   }
798   assert(!Src.hasExternalWeakLinkage());
799   assert(!Dest.hasExternalWeakLinkage());
800   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
801          "Unexpected linkage type!");
802   return emitError("Linking globals named '" + Src.getName() +
803                    "': symbol multiply defined!");
806 /// Loop over all of the linked values to compute type mappings.  For example,
807 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
808 /// types 'Foo' but one got renamed when the module was loaded into the same
809 /// LLVMContext.
810 void ModuleLinker::computeTypeMapping() {
811   for (GlobalValue &SGV : SrcM->globals()) {
812     GlobalValue *DGV = getLinkedToGlobal(&SGV);
813     if (!DGV)
814       continue;
816     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
817       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
818       continue;
819     }
821     // Unify the element type of appending arrays.
822     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
823     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
824     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
825   }
827   for (GlobalValue &SGV : *SrcM) {
828     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
829       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
830   }
832   for (GlobalValue &SGV : SrcM->aliases()) {
833     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
834       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
835   }
837   // Incorporate types by name, scanning all the types in the source module.
838   // At this point, the destination module may have a type "%foo = { i32 }" for
839   // example.  When the source module got loaded into the same LLVMContext, if
840   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
841   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
842   for (StructType *ST : Types) {
843     if (!ST->hasName())
844       continue;
846     // Check to see if there is a dot in the name followed by a digit.
847     size_t DotPos = ST->getName().rfind('.');
848     if (DotPos == 0 || DotPos == StringRef::npos ||
849         ST->getName().back() == '.' ||
850         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
851       continue;
853     // Check to see if the destination module has a struct with the prefix name.
854     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
855     if (!DST)
856       continue;
858     // Don't use it if this actually came from the source module. They're in
859     // the same LLVMContext after all. Also don't use it unless the type is
860     // actually used in the destination module. This can happen in situations
861     // like this:
862     //
863     //      Module A                         Module B
864     //      --------                         --------
865     //   %Z = type { %A }                %B = type { %C.1 }
866     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
867     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
868     //   %C = type { i8* }               %B.3 = type { %C.1 }
869     //
870     // When we link Module B with Module A, the '%B' in Module B is
871     // used. However, that would then use '%C.1'. But when we process '%C.1',
872     // we prefer to take the '%C' version. So we are then left with both
873     // '%C.1' and '%C' being used for the same types. This leads to some
874     // variables using one type and some using the other.
875     if (TypeMap.DstStructTypesSet.hasType(DST))
876       TypeMap.addTypeMapping(DST, ST);
877   }
879   // Now that we have discovered all of the type equivalences, get a body for
880   // any 'opaque' types in the dest module that are now resolved.
881   TypeMap.linkDefinedTypeBodies();
884 static void upgradeGlobalArray(GlobalVariable *GV) {
885   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
886   StructType *OldTy = cast<StructType>(ATy->getElementType());
887   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
889   // Get the upgraded 3 element type.
890   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
891   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
892                   VoidPtrTy};
893   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
895   // Build new constants with a null third field filled in.
896   Constant *OldInitC = GV->getInitializer();
897   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
898   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
899     // Invalid initializer; give up.
900     return;
901   std::vector<Constant *> Initializers;
902   if (OldInit && OldInit->getNumOperands()) {
903     Value *Null = Constant::getNullValue(VoidPtrTy);
904     for (Use &U : OldInit->operands()) {
905       ConstantStruct *Init = cast<ConstantStruct>(U.get());
906       Initializers.push_back(ConstantStruct::get(
907           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
908     }
909   }
910   assert(Initializers.size() == ATy->getNumElements() &&
911          "Failed to copy all array elements");
913   // Replace the old GV with a new one.
914   ATy = ArrayType::get(NewTy, Initializers.size());
915   Constant *NewInit = ConstantArray::get(ATy, Initializers);
916   GlobalVariable *NewGV = new GlobalVariable(
917       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
918       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
919       GV->isExternallyInitialized());
920   NewGV->copyAttributesFrom(GV);
921   NewGV->takeName(GV);
922   assert(GV->use_empty() && "program cannot use initializer list");
923   GV->eraseFromParent();
926 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
927   // Look for the global arrays.
928   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
929   if (!DstGV)
930     return;
931   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
932   if (!SrcGV)
933     return;
935   // Check if the types already match.
936   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
937   auto *SrcTy =
938       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
939   if (DstTy == SrcTy)
940     return;
942   // Grab the element types.  We can only upgrade an array of a two-field
943   // struct.  Only bother if the other one has three-fields.
944   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
945   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
946   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
947     upgradeGlobalArray(DstGV);
948     return;
949   }
950   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
951     upgradeGlobalArray(SrcGV);
953   // We can't upgrade any other differences.
956 void ModuleLinker::upgradeMismatchedGlobals() {
957   upgradeMismatchedGlobalArray("llvm.global_ctors");
958   upgradeMismatchedGlobalArray("llvm.global_dtors");
961 /// If there were any appending global variables, link them together now.
962 /// Return true on error.
963 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
964                                          const GlobalVariable *SrcGV) {
966   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
967     return emitError("Linking globals named '" + SrcGV->getName() +
968            "': can only link appending global with another appending global!");
970   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
971   ArrayType *SrcTy =
972     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
973   Type *EltTy = DstTy->getElementType();
975   // Check to see that they two arrays agree on type.
976   if (EltTy != SrcTy->getElementType())
977     return emitError("Appending variables with different element types!");
978   if (DstGV->isConstant() != SrcGV->isConstant())
979     return emitError("Appending variables linked with different const'ness!");
981   if (DstGV->getAlignment() != SrcGV->getAlignment())
982     return emitError(
983              "Appending variables with different alignment need to be linked!");
985   if (DstGV->getVisibility() != SrcGV->getVisibility())
986     return emitError(
987             "Appending variables with different visibility need to be linked!");
989   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
990     return emitError(
991         "Appending variables with different unnamed_addr need to be linked!");
993   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
994     return emitError(
995           "Appending variables with different section name need to be linked!");
997   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
998   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1000   // Create the new global variable.
1001   GlobalVariable *NG =
1002     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
1003                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
1004                        DstGV->getThreadLocalMode(),
1005                        DstGV->getType()->getAddressSpace());
1007   // Propagate alignment, visibility and section info.
1008   copyGVAttributes(NG, DstGV);
1010   AppendingVarInfo AVI;
1011   AVI.NewGV = NG;
1012   AVI.DstInit = DstGV->getInitializer();
1013   AVI.SrcInit = SrcGV->getInitializer();
1014   AppendingVars.push_back(AVI);
1016   // Replace any uses of the two global variables with uses of the new
1017   // global.
1018   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1020   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1021   DstGV->eraseFromParent();
1023   // Track the source variable so we don't try to link it.
1024   DoNotLinkFromSource.insert(SrcGV);
1026   return false;
1029 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1030   GlobalValue *DGV = getLinkedToGlobal(SGV);
1032   // Handle the ultra special appending linkage case first.
1033   if (DGV && DGV->hasAppendingLinkage())
1034     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1035                                  cast<GlobalVariable>(SGV));
1037   bool LinkFromSrc = true;
1038   Comdat *C = nullptr;
1039   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
1040   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1042   if (const Comdat *SC = SGV->getComdat()) {
1043     Comdat::SelectionKind SK;
1044     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1045     C = DstM->getOrInsertComdat(SC->getName());
1046     C->setSelectionKind(SK);
1047   } else if (DGV) {
1048     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1049       return true;
1050   }
1052   if (!LinkFromSrc) {
1053     // Track the source global so that we don't attempt to copy it over when
1054     // processing global initializers.
1055     DoNotLinkFromSource.insert(SGV);
1057     if (DGV)
1058       // Make sure to remember this mapping.
1059       ValueMap[SGV] =
1060           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1061   }
1063   if (DGV) {
1064     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1065                      ? DGV->getVisibility()
1066                      : Visibility;
1067     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1068   }
1070   if (!LinkFromSrc && !DGV)
1071     return false;
1073   GlobalValue *NewGV;
1074   if (!LinkFromSrc) {
1075     NewGV = DGV;
1076   } else {
1077     // If the GV is to be lazily linked, don't create it just yet.
1078     // The ValueMaterializerTy will deal with creating it if it's used.
1079     if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1080                  SGV->hasAvailableExternallyLinkage())) {
1081       DoNotLinkFromSource.insert(SGV);
1082       return false;
1083     }
1085     NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
1087     if (DGV && isa<Function>(DGV))
1088       if (auto *NewF = dyn_cast<Function>(NewGV))
1089         OverridingFunctions.insert(NewF);
1090   }
1092   NewGV->setUnnamedAddr(HasUnnamedAddr);
1093   NewGV->setVisibility(Visibility);
1095   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1096     if (C)
1097       NewGO->setComdat(C);
1099     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1100       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1101   }
1103   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1104     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1105     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1106     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1107         (!DGVar->isConstant() || !SGVar->isConstant()))
1108       NewGVar->setConstant(false);
1109   }
1111   // Make sure to remember this mapping.
1112   if (NewGV != DGV) {
1113     if (DGV) {
1114       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1115       DGV->eraseFromParent();
1116     }
1117     ValueMap[SGV] = NewGV;
1118   }
1120   return false;
1123 static void getArrayElements(const Constant *C,
1124                              SmallVectorImpl<Constant *> &Dest) {
1125   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1127   for (unsigned i = 0; i != NumElements; ++i)
1128     Dest.push_back(C->getAggregateElement(i));
1131 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1132   // Merge the initializer.
1133   SmallVector<Constant *, 16> DstElements;
1134   getArrayElements(AVI.DstInit, DstElements);
1136   SmallVector<Constant *, 16> SrcElements;
1137   getArrayElements(AVI.SrcInit, SrcElements);
1139   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1141   StringRef Name = AVI.NewGV->getName();
1142   bool IsNewStructor =
1143       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1144       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1146   for (auto *V : SrcElements) {
1147     if (IsNewStructor) {
1148       Constant *Key = V->getAggregateElement(2);
1149       if (DoNotLinkFromSource.count(Key))
1150         continue;
1151     }
1152     DstElements.push_back(
1153         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1154   }
1155   if (IsNewStructor) {
1156     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1157     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1158   }
1160   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1163 /// Update the initializers in the Dest module now that all globals that may be
1164 /// referenced are in Dest.
1165 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1166   // Figure out what the initializer looks like in the dest module.
1167   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap,
1168                               &ValMaterializer));
1171 /// Copy the source function over into the dest function and fix up references
1172 /// to values. At this point we know that Dest is an external function, and
1173 /// that Src is not.
1174 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1175   assert(Dst.isDeclaration() && !Src.isDeclaration());
1177   // Materialize if needed.
1178   if (std::error_code EC = Src.materialize())
1179     return emitError(EC.message());
1181   // Link in the prefix data.
1182   if (Src.hasPrefixData())
1183     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap,
1184                                &ValMaterializer));
1186   // Link in the prologue data.
1187   if (Src.hasPrologueData())
1188     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None,
1189                                  &TypeMap, &ValMaterializer));
1191   // Go through and convert function arguments over, remembering the mapping.
1192   Function::arg_iterator DI = Dst.arg_begin();
1193   for (Argument &Arg : Src.args()) {
1194     DI->setName(Arg.getName());  // Copy the name over.
1196     // Add a mapping to our mapping.
1197     ValueMap[&Arg] = DI;
1198     ++DI;
1199   }
1201   // Splice the body of the source function into the dest function.
1202   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1204   // At this point, all of the instructions and values of the function are now
1205   // copied over.  The only problem is that they are still referencing values in
1206   // the Source function as operands.  Loop through all of the operands of the
1207   // functions and patch them up to point to the local versions.
1208   for (BasicBlock &BB : Dst)
1209     for (Instruction &I : BB)
1210       RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1211                        &ValMaterializer);
1213   // There is no need to map the arguments anymore.
1214   for (Argument &Arg : Src.args())
1215     ValueMap.erase(&Arg);
1217   Src.Dematerialize();
1218   return false;
1221 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1222   Constant *Aliasee = Src.getAliasee();
1223   Constant *Val =
1224       MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1225   Dst.setAliasee(Val);
1228 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1229   Value *Dst = ValueMap[&Src];
1230   assert(Dst);
1231   if (auto *F = dyn_cast<Function>(&Src))
1232     return linkFunctionBody(cast<Function>(*Dst), *F);
1233   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1234     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1235     return false;
1236   }
1237   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1238   return false;
1241 /// Insert all of the named MDNodes in Src into the Dest module.
1242 void ModuleLinker::linkNamedMDNodes() {
1243   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1244   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1245        E = SrcM->named_metadata_end(); I != E; ++I) {
1246     // Don't link module flags here. Do them separately.
1247     if (&*I == SrcModFlags) continue;
1248     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1249     // Add Src elements into Dest node.
1250     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1251       DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None,
1252                                       &TypeMap, &ValMaterializer));
1253   }
1256 /// Drop DISubprograms that have been superseded.
1257 ///
1258 /// FIXME: this creates an asymmetric result: we strip losing subprograms from
1259 /// DstM, but leave losing subprograms in SrcM.  Instead we should also strip
1260 /// losers from SrcM, but this requires extra plumbing in MapMetadata.
1261 void ModuleLinker::stripReplacedSubprograms() {
1262   // Avoid quadratic runtime by returning early when there's nothing to do.
1263   if (OverridingFunctions.empty())
1264     return;
1266   // Move the functions now, so the set gets cleared even on early returns.
1267   auto Functions = std::move(OverridingFunctions);
1268   OverridingFunctions.clear();
1270   // Drop subprograms whose functions have been overridden by the new compile
1271   // unit.
1272   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
1273   if (!CompileUnits)
1274     return;
1275   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1276     DICompileUnit CU(CompileUnits->getOperand(I));
1277     assert(CU && "Expected valid compile unit");
1279     DITypedArray<DISubprogram> SPs(CU.getSubprograms());
1280     assert(SPs && "Expected valid subprogram array");
1282     SmallVector<Metadata *, 16> NewSPs;
1283     NewSPs.reserve(SPs.getNumElements());
1284     for (unsigned S = 0, SE = SPs.getNumElements(); S != SE; ++S) {
1285       DISubprogram SP = SPs.getElement(S);
1286       if (SP && SP.getFunction() && Functions.count(SP.getFunction()))
1287         continue;
1289       NewSPs.push_back(SP);
1290     }
1292     // Redirect operand to the overriding subprogram.
1293     if (NewSPs.size() != SPs.getNumElements())
1294       CU.replaceSubprograms(DIArray(MDNode::get(DstM->getContext(), NewSPs)));
1295   }
1298 /// Merge the linker flags in Src into the Dest module.
1299 bool ModuleLinker::linkModuleFlagsMetadata() {
1300   // If the source module has no module flags, we are done.
1301   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1302   if (!SrcModFlags) return false;
1304   // If the destination module doesn't have module flags yet, then just copy
1305   // over the source module's flags.
1306   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1307   if (DstModFlags->getNumOperands() == 0) {
1308     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1309       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1311     return false;
1312   }
1314   // First build a map of the existing module flags and requirements.
1315   DenseMap<MDString*, MDNode*> Flags;
1316   SmallSetVector<MDNode*, 16> Requirements;
1317   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1318     MDNode *Op = DstModFlags->getOperand(I);
1319     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1320     MDString *ID = cast<MDString>(Op->getOperand(1));
1322     if (Behavior->getZExtValue() == Module::Require) {
1323       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1324     } else {
1325       Flags[ID] = Op;
1326     }
1327   }
1329   // Merge in the flags from the source module, and also collect its set of
1330   // requirements.
1331   bool HasErr = false;
1332   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1333     MDNode *SrcOp = SrcModFlags->getOperand(I);
1334     ConstantInt *SrcBehavior =
1335         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1336     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1337     MDNode *DstOp = Flags.lookup(ID);
1338     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1340     // If this is a requirement, add it and continue.
1341     if (SrcBehaviorValue == Module::Require) {
1342       // If the destination module does not already have this requirement, add
1343       // it.
1344       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1345         DstModFlags->addOperand(SrcOp);
1346       }
1347       continue;
1348     }
1350     // If there is no existing flag with this ID, just add it.
1351     if (!DstOp) {
1352       Flags[ID] = SrcOp;
1353       DstModFlags->addOperand(SrcOp);
1354       continue;
1355     }
1357     // Otherwise, perform a merge.
1358     ConstantInt *DstBehavior =
1359         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1360     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1362     // If either flag has override behavior, handle it first.
1363     if (DstBehaviorValue == Module::Override) {
1364       // Diagnose inconsistent flags which both have override behavior.
1365       if (SrcBehaviorValue == Module::Override &&
1366           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1367         HasErr |= emitError("linking module flags '" + ID->getString() +
1368                             "': IDs have conflicting override values");
1369       }
1370       continue;
1371     } else if (SrcBehaviorValue == Module::Override) {
1372       // Update the destination flag to that of the source.
1373       DstOp->replaceOperandWith(0, ConstantAsMetadata::get(SrcBehavior));
1374       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1375       continue;
1376     }
1378     // Diagnose inconsistent merge behavior types.
1379     if (SrcBehaviorValue != DstBehaviorValue) {
1380       HasErr |= emitError("linking module flags '" + ID->getString() +
1381                           "': IDs have conflicting behaviors");
1382       continue;
1383     }
1385     // Perform the merge for standard behavior types.
1386     switch (SrcBehaviorValue) {
1387     case Module::Require:
1388     case Module::Override: llvm_unreachable("not possible");
1389     case Module::Error: {
1390       // Emit an error if the values differ.
1391       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1392         HasErr |= emitError("linking module flags '" + ID->getString() +
1393                             "': IDs have conflicting values");
1394       }
1395       continue;
1396     }
1397     case Module::Warning: {
1398       // Emit a warning if the values differ.
1399       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1400         emitWarning("linking module flags '" + ID->getString() +
1401                     "': IDs have conflicting values");
1402       }
1403       continue;
1404     }
1405     case Module::Append: {
1406       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1407       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1408       SmallVector<Metadata *, 8> MDs;
1409       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1410       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1411         MDs.push_back(DstValue->getOperand(i));
1412       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1413         MDs.push_back(SrcValue->getOperand(i));
1414       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), MDs));
1415       break;
1416     }
1417     case Module::AppendUnique: {
1418       SmallSetVector<Metadata *, 16> Elts;
1419       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1420       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1421       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1422         Elts.insert(DstValue->getOperand(i));
1423       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1424         Elts.insert(SrcValue->getOperand(i));
1425       DstOp->replaceOperandWith(
1426           2, MDNode::get(DstM->getContext(),
1427                          makeArrayRef(Elts.begin(), Elts.end())));
1428       break;
1429     }
1430     }
1431   }
1433   // Check all of the requirements.
1434   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1435     MDNode *Requirement = Requirements[I];
1436     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1437     Metadata *ReqValue = Requirement->getOperand(1);
1439     MDNode *Op = Flags[Flag];
1440     if (!Op || Op->getOperand(2) != ReqValue) {
1441       HasErr |= emitError("linking module flags '" + Flag->getString() +
1442                           "': does not have the required value");
1443       continue;
1444     }
1445   }
1447   return HasErr;
1450 bool ModuleLinker::run() {
1451   assert(DstM && "Null destination module");
1452   assert(SrcM && "Null source module");
1454   // Inherit the target data from the source module if the destination module
1455   // doesn't have one already.
1456   if (!DstM->getDataLayout() && SrcM->getDataLayout())
1457     DstM->setDataLayout(SrcM->getDataLayout());
1459   // Copy the target triple from the source to dest if the dest's is empty.
1460   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1461     DstM->setTargetTriple(SrcM->getTargetTriple());
1463   if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1464       *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1465     emitWarning("Linking two modules of different data layouts: '" +
1466                 SrcM->getModuleIdentifier() + "' is '" +
1467                 SrcM->getDataLayoutStr() + "' whereas '" +
1468                 DstM->getModuleIdentifier() + "' is '" +
1469                 DstM->getDataLayoutStr() + "'\n");
1470   }
1471   if (!SrcM->getTargetTriple().empty() &&
1472       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1473     emitWarning("Linking two modules of different target triples: " +
1474                 SrcM->getModuleIdentifier() + "' is '" +
1475                 SrcM->getTargetTriple() + "' whereas '" +
1476                 DstM->getModuleIdentifier() + "' is '" +
1477                 DstM->getTargetTriple() + "'\n");
1478   }
1480   // Append the module inline asm string.
1481   if (!SrcM->getModuleInlineAsm().empty()) {
1482     if (DstM->getModuleInlineAsm().empty())
1483       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1484     else
1485       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1486                                SrcM->getModuleInlineAsm());
1487   }
1489   // Loop over all of the linked values to compute type mappings.
1490   computeTypeMapping();
1492   ComdatsChosen.clear();
1493   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1494     const Comdat &C = SMEC.getValue();
1495     if (ComdatsChosen.count(&C))
1496       continue;
1497     Comdat::SelectionKind SK;
1498     bool LinkFromSrc;
1499     if (getComdatResult(&C, SK, LinkFromSrc))
1500       return true;
1501     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1502   }
1504   // Upgrade mismatched global arrays.
1505   upgradeMismatchedGlobals();
1507   // Insert all of the globals in src into the DstM module... without linking
1508   // initializers (which could refer to functions not yet mapped over).
1509   for (Module::global_iterator I = SrcM->global_begin(),
1510        E = SrcM->global_end(); I != E; ++I)
1511     if (linkGlobalValueProto(I))
1512       return true;
1514   // Link the functions together between the two modules, without doing function
1515   // bodies... this just adds external function prototypes to the DstM
1516   // function...  We do this so that when we begin processing function bodies,
1517   // all of the global values that may be referenced are available in our
1518   // ValueMap.
1519   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1520     if (linkGlobalValueProto(I))
1521       return true;
1523   // If there were any aliases, link them now.
1524   for (Module::alias_iterator I = SrcM->alias_begin(),
1525        E = SrcM->alias_end(); I != E; ++I)
1526     if (linkGlobalValueProto(I))
1527       return true;
1529   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1530     linkAppendingVarInit(AppendingVars[i]);
1532   for (const auto &Entry : DstM->getComdatSymbolTable()) {
1533     const Comdat &C = Entry.getValue();
1534     if (C.getSelectionKind() == Comdat::Any)
1535       continue;
1536     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1537     assert(GV);
1538     MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1539   }
1541   // Link in the function bodies that are defined in the source module into
1542   // DstM.
1543   for (Function &SF : *SrcM) {
1544     // Skip if no body (function is external).
1545     if (SF.isDeclaration())
1546       continue;
1548     // Skip if not linking from source.
1549     if (DoNotLinkFromSource.count(&SF))
1550       continue;
1552     if (linkGlobalValueBody(SF))
1553       return true;
1554   }
1556   // Resolve all uses of aliases with aliasees.
1557   for (GlobalAlias &Src : SrcM->aliases()) {
1558     if (DoNotLinkFromSource.count(&Src))
1559       continue;
1560     linkGlobalValueBody(Src);
1561   }
1563   // Strip replaced subprograms before linking together compile units.
1564   stripReplacedSubprograms();
1566   // Remap all of the named MDNodes in Src into the DstM module. We do this
1567   // after linking GlobalValues so that MDNodes that reference GlobalValues
1568   // are properly remapped.
1569   linkNamedMDNodes();
1571   // Merge the module flags into the DstM module.
1572   if (linkModuleFlagsMetadata())
1573     return true;
1575   // Update the initializers in the DstM module now that all globals that may
1576   // be referenced are in DstM.
1577   for (GlobalVariable &Src : SrcM->globals()) {
1578     // Only process initialized GV's or ones not already in dest.
1579     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1580       continue;
1581     linkGlobalValueBody(Src);
1582   }
1584   // Process vector of lazily linked in functions.
1585   while (!LazilyLinkGlobalValues.empty()) {
1586     GlobalValue *SGV = LazilyLinkGlobalValues.back();
1587     LazilyLinkGlobalValues.pop_back();
1589     assert(!SGV->isDeclaration() && "users should not pass down decls");
1590     if (linkGlobalValueBody(*SGV))
1591       return true;
1592   }
1594   return false;
1597 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1598     : ETypes(E), IsPacked(P) {}
1600 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1601     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1603 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1604   if (IsPacked != That.IsPacked)
1605     return false;
1606   if (ETypes != That.ETypes)
1607     return false;
1608   return true;
1611 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1612   return !this->operator==(That);
1615 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1616   return DenseMapInfo<StructType *>::getEmptyKey();
1619 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1620   return DenseMapInfo<StructType *>::getTombstoneKey();
1623 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1624   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1625                       Key.IsPacked);
1628 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1629   return getHashValue(KeyTy(ST));
1632 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1633                                         const StructType *RHS) {
1634   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1635     return false;
1636   return LHS == KeyTy(RHS);
1639 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1640                                         const StructType *RHS) {
1641   if (RHS == getEmptyKey())
1642     return LHS == getEmptyKey();
1644   if (RHS == getTombstoneKey())
1645     return LHS == getTombstoneKey();
1647   return KeyTy(LHS) == KeyTy(RHS);
1650 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1651   assert(!Ty->isOpaque());
1652   NonOpaqueStructTypes.insert(Ty);
1655 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1656   assert(Ty->isOpaque());
1657   OpaqueStructTypes.insert(Ty);
1660 StructType *
1661 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1662                                                bool IsPacked) {
1663   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1664   auto I = NonOpaqueStructTypes.find_as(Key);
1665   if (I == NonOpaqueStructTypes.end())
1666     return nullptr;
1667   return *I;
1670 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1671   if (Ty->isOpaque())
1672     return OpaqueStructTypes.count(Ty);
1673   auto I = NonOpaqueStructTypes.find(Ty);
1674   if (I == NonOpaqueStructTypes.end())
1675     return false;
1676   return *I == Ty;
1679 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1680   this->Composite = M;
1681   this->DiagnosticHandler = DiagnosticHandler;
1683   TypeFinder StructTypes;
1684   StructTypes.run(*M, true);
1685   for (StructType *Ty : StructTypes) {
1686     if (Ty->isOpaque())
1687       IdentifiedStructTypes.addOpaque(Ty);
1688     else
1689       IdentifiedStructTypes.addNonOpaque(Ty);
1690   }
1693 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1694   init(M, DiagnosticHandler);
1697 Linker::Linker(Module *M) {
1698   init(M, [this](const DiagnosticInfo &DI) {
1699     Composite->getContext().diagnose(DI);
1700   });
1703 Linker::~Linker() {
1706 void Linker::deleteModule() {
1707   delete Composite;
1708   Composite = nullptr;
1711 bool Linker::linkInModule(Module *Src) {
1712   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1713                          DiagnosticHandler);
1714   return TheLinker.run();
1717 //===----------------------------------------------------------------------===//
1718 // LinkModules entrypoint.
1719 //===----------------------------------------------------------------------===//
1721 /// This function links two modules together, with the resulting Dest module
1722 /// modified to be the composite of the two input modules. If an error occurs,
1723 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1724 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1725 /// relied on to be consistent.
1726 bool Linker::LinkModules(Module *Dest, Module *Src,
1727                          DiagnosticHandlerFunction DiagnosticHandler) {
1728   Linker L(Dest, DiagnosticHandler);
1729   return L.linkInModule(Src);
1732 bool Linker::LinkModules(Module *Dest, Module *Src) {
1733   Linker L(Dest);
1734   return L.linkInModule(Src);
1737 //===----------------------------------------------------------------------===//
1738 // C API.
1739 //===----------------------------------------------------------------------===//
1741 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1742                          unsigned Unused, char **OutMessages) {
1743   Module *D = unwrap(Dest);
1744   std::string Message;
1745   raw_string_ostream Stream(Message);
1746   DiagnosticPrinterRawOStream DP(Stream);
1748   LLVMBool Result = Linker::LinkModules(
1749       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1751   if (OutMessages && Result)
1752     *OutMessages = strdup(Message.c_str());
1753   return Result;