LLVM  mainline
LinkModules.cpp
Go to the documentation of this file.
00001 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LLVM module linker.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Linker/Linker.h"
00015 #include "llvm-c/Linker.h"
00016 #include "llvm/ADT/Hashing.h"
00017 #include "llvm/ADT/Optional.h"
00018 #include "llvm/ADT/SetVector.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/ADT/Triple.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DebugInfo.h"
00024 #include "llvm/IR/DiagnosticInfo.h"
00025 #include "llvm/IR/DiagnosticPrinter.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/TypeFinder.h"
00029 #include "llvm/Support/CommandLine.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include "llvm/Transforms/Utils/Cloning.h"
00033 #include <cctype>
00034 #include <tuple>
00035 using namespace llvm;
00036 
00037 
00038 //===----------------------------------------------------------------------===//
00039 // TypeMap implementation.
00040 //===----------------------------------------------------------------------===//
00041 
00042 namespace {
00043 class TypeMapTy : public ValueMapTypeRemapper {
00044   /// This is a mapping from a source type to a destination type to use.
00045   DenseMap<Type*, Type*> MappedTypes;
00046 
00047   /// When checking to see if two subgraphs are isomorphic, we speculatively
00048   /// add types to MappedTypes, but keep track of them here in case we need to
00049   /// roll back.
00050   SmallVector<Type*, 16> SpeculativeTypes;
00051 
00052   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
00053 
00054   /// This is a list of non-opaque structs in the source module that are mapped
00055   /// to an opaque struct in the destination module.
00056   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
00057 
00058   /// This is the set of opaque types in the destination modules who are
00059   /// getting a body from the source module.
00060   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
00061 
00062 public:
00063   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
00064       : DstStructTypesSet(DstStructTypesSet) {}
00065 
00066   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
00067   /// Indicate that the specified type in the destination module is conceptually
00068   /// equivalent to the specified type in the source module.
00069   void addTypeMapping(Type *DstTy, Type *SrcTy);
00070 
00071   /// Produce a body for an opaque type in the dest module from a type
00072   /// definition in the source module.
00073   void linkDefinedTypeBodies();
00074 
00075   /// Return the mapped type to use for the specified input type from the
00076   /// source module.
00077   Type *get(Type *SrcTy);
00078   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
00079 
00080   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
00081 
00082   FunctionType *get(FunctionType *T) {
00083     return cast<FunctionType>(get((Type *)T));
00084   }
00085 
00086   /// Dump out the type map for debugging purposes.
00087   void dump() const {
00088     for (auto &Pair : MappedTypes) {
00089       dbgs() << "TypeMap: ";
00090       Pair.first->print(dbgs());
00091       dbgs() << " => ";
00092       Pair.second->print(dbgs());
00093       dbgs() << '\n';
00094     }
00095   }
00096 
00097 private:
00098   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
00099 
00100   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
00101 };
00102 }
00103 
00104 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
00105   assert(SpeculativeTypes.empty());
00106   assert(SpeculativeDstOpaqueTypes.empty());
00107 
00108   // Check to see if these types are recursively isomorphic and establish a
00109   // mapping between them if so.
00110   if (!areTypesIsomorphic(DstTy, SrcTy)) {
00111     // Oops, they aren't isomorphic.  Just discard this request by rolling out
00112     // any speculative mappings we've established.
00113     for (Type *Ty : SpeculativeTypes)
00114       MappedTypes.erase(Ty);
00115 
00116     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
00117                                    SpeculativeDstOpaqueTypes.size());
00118     for (StructType *Ty : SpeculativeDstOpaqueTypes)
00119       DstResolvedOpaqueTypes.erase(Ty);
00120   } else {
00121     for (Type *Ty : SpeculativeTypes)
00122       if (auto *STy = dyn_cast<StructType>(Ty))
00123         if (STy->hasName())
00124           STy->setName("");
00125   }
00126   SpeculativeTypes.clear();
00127   SpeculativeDstOpaqueTypes.clear();
00128 }
00129 
00130 /// Recursively walk this pair of types, returning true if they are isomorphic,
00131 /// false if they are not.
00132 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
00133   // Two types with differing kinds are clearly not isomorphic.
00134   if (DstTy->getTypeID() != SrcTy->getTypeID())
00135     return false;
00136 
00137   // If we have an entry in the MappedTypes table, then we have our answer.
00138   Type *&Entry = MappedTypes[SrcTy];
00139   if (Entry)
00140     return Entry == DstTy;
00141 
00142   // Two identical types are clearly isomorphic.  Remember this
00143   // non-speculatively.
00144   if (DstTy == SrcTy) {
00145     Entry = DstTy;
00146     return true;
00147   }
00148 
00149   // Okay, we have two types with identical kinds that we haven't seen before.
00150 
00151   // If this is an opaque struct type, special case it.
00152   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
00153     // Mapping an opaque type to any struct, just keep the dest struct.
00154     if (SSTy->isOpaque()) {
00155       Entry = DstTy;
00156       SpeculativeTypes.push_back(SrcTy);
00157       return true;
00158     }
00159 
00160     // Mapping a non-opaque source type to an opaque dest.  If this is the first
00161     // type that we're mapping onto this destination type then we succeed.  Keep
00162     // the dest, but fill it in later. If this is the second (different) type
00163     // that we're trying to map onto the same opaque type then we fail.
00164     if (cast<StructType>(DstTy)->isOpaque()) {
00165       // We can only map one source type onto the opaque destination type.
00166       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
00167         return false;
00168       SrcDefinitionsToResolve.push_back(SSTy);
00169       SpeculativeTypes.push_back(SrcTy);
00170       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
00171       Entry = DstTy;
00172       return true;
00173     }
00174   }
00175 
00176   // If the number of subtypes disagree between the two types, then we fail.
00177   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
00178     return false;
00179 
00180   // Fail if any of the extra properties (e.g. array size) of the type disagree.
00181   if (isa<IntegerType>(DstTy))
00182     return false;  // bitwidth disagrees.
00183   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
00184     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
00185       return false;
00186 
00187   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
00188     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
00189       return false;
00190   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
00191     StructType *SSTy = cast<StructType>(SrcTy);
00192     if (DSTy->isLiteral() != SSTy->isLiteral() ||
00193         DSTy->isPacked() != SSTy->isPacked())
00194       return false;
00195   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
00196     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
00197       return false;
00198   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
00199     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
00200       return false;
00201   }
00202 
00203   // Otherwise, we speculate that these two types will line up and recursively
00204   // check the subelements.
00205   Entry = DstTy;
00206   SpeculativeTypes.push_back(SrcTy);
00207 
00208   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
00209     if (!areTypesIsomorphic(DstTy->getContainedType(I),
00210                             SrcTy->getContainedType(I)))
00211       return false;
00212 
00213   // If everything seems to have lined up, then everything is great.
00214   return true;
00215 }
00216 
00217 void TypeMapTy::linkDefinedTypeBodies() {
00218   SmallVector<Type*, 16> Elements;
00219   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
00220     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
00221     assert(DstSTy->isOpaque());
00222 
00223     // Map the body of the source type over to a new body for the dest type.
00224     Elements.resize(SrcSTy->getNumElements());
00225     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
00226       Elements[I] = get(SrcSTy->getElementType(I));
00227 
00228     DstSTy->setBody(Elements, SrcSTy->isPacked());
00229     DstStructTypesSet.switchToNonOpaque(DstSTy);
00230   }
00231   SrcDefinitionsToResolve.clear();
00232   DstResolvedOpaqueTypes.clear();
00233 }
00234 
00235 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
00236                            ArrayRef<Type *> ETypes) {
00237   DTy->setBody(ETypes, STy->isPacked());
00238 
00239   // Steal STy's name.
00240   if (STy->hasName()) {
00241     SmallString<16> TmpName = STy->getName();
00242     STy->setName("");
00243     DTy->setName(TmpName);
00244   }
00245 
00246   DstStructTypesSet.addNonOpaque(DTy);
00247 }
00248 
00249 Type *TypeMapTy::get(Type *Ty) {
00250   SmallPtrSet<StructType *, 8> Visited;
00251   return get(Ty, Visited);
00252 }
00253 
00254 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
00255   // If we already have an entry for this type, return it.
00256   Type **Entry = &MappedTypes[Ty];
00257   if (*Entry)
00258     return *Entry;
00259 
00260   // These are types that LLVM itself will unique.
00261   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
00262 
00263 #ifndef NDEBUG
00264   if (!IsUniqued) {
00265     for (auto &Pair : MappedTypes) {
00266       assert(!(Pair.first != Ty && Pair.second == Ty) &&
00267              "mapping to a source type");
00268     }
00269   }
00270 #endif
00271 
00272   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
00273     StructType *DTy = StructType::create(Ty->getContext());
00274     return *Entry = DTy;
00275   }
00276 
00277   // If this is not a recursive type, then just map all of the elements and
00278   // then rebuild the type from inside out.
00279   SmallVector<Type *, 4> ElementTypes;
00280 
00281   // If there are no element types to map, then the type is itself.  This is
00282   // true for the anonymous {} struct, things like 'float', integers, etc.
00283   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
00284     return *Entry = Ty;
00285 
00286   // Remap all of the elements, keeping track of whether any of them change.
00287   bool AnyChange = false;
00288   ElementTypes.resize(Ty->getNumContainedTypes());
00289   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
00290     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
00291     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
00292   }
00293 
00294   // If we found our type while recursively processing stuff, just use it.
00295   Entry = &MappedTypes[Ty];
00296   if (*Entry) {
00297     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
00298       if (DTy->isOpaque()) {
00299         auto *STy = cast<StructType>(Ty);
00300         finishType(DTy, STy, ElementTypes);
00301       }
00302     }
00303     return *Entry;
00304   }
00305 
00306   // If all of the element types mapped directly over and the type is not
00307   // a nomed struct, then the type is usable as-is.
00308   if (!AnyChange && IsUniqued)
00309     return *Entry = Ty;
00310 
00311   // Otherwise, rebuild a modified type.
00312   switch (Ty->getTypeID()) {
00313   default:
00314     llvm_unreachable("unknown derived type to remap");
00315   case Type::ArrayTyID:
00316     return *Entry = ArrayType::get(ElementTypes[0],
00317                                    cast<ArrayType>(Ty)->getNumElements());
00318   case Type::VectorTyID:
00319     return *Entry = VectorType::get(ElementTypes[0],
00320                                     cast<VectorType>(Ty)->getNumElements());
00321   case Type::PointerTyID:
00322     return *Entry = PointerType::get(ElementTypes[0],
00323                                      cast<PointerType>(Ty)->getAddressSpace());
00324   case Type::FunctionTyID:
00325     return *Entry = FunctionType::get(ElementTypes[0],
00326                                       makeArrayRef(ElementTypes).slice(1),
00327                                       cast<FunctionType>(Ty)->isVarArg());
00328   case Type::StructTyID: {
00329     auto *STy = cast<StructType>(Ty);
00330     bool IsPacked = STy->isPacked();
00331     if (IsUniqued)
00332       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
00333 
00334     // If the type is opaque, we can just use it directly.
00335     if (STy->isOpaque()) {
00336       DstStructTypesSet.addOpaque(STy);
00337       return *Entry = Ty;
00338     }
00339 
00340     if (StructType *OldT =
00341             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
00342       STy->setName("");
00343       return *Entry = OldT;
00344     }
00345 
00346     if (!AnyChange) {
00347       DstStructTypesSet.addNonOpaque(STy);
00348       return *Entry = Ty;
00349     }
00350 
00351     StructType *DTy = StructType::create(Ty->getContext());
00352     finishType(DTy, STy, ElementTypes);
00353     return *Entry = DTy;
00354   }
00355   }
00356 }
00357 
00358 //===----------------------------------------------------------------------===//
00359 // ModuleLinker implementation.
00360 //===----------------------------------------------------------------------===//
00361 
00362 namespace {
00363 class ModuleLinker;
00364 
00365 /// Creates prototypes for functions that are lazily linked on the fly. This
00366 /// speeds up linking for modules with many/ lazily linked functions of which
00367 /// few get used.
00368 class ValueMaterializerTy : public ValueMaterializer {
00369   TypeMapTy &TypeMap;
00370   Module *DstM;
00371   std::vector<GlobalValue *> &LazilyLinkGlobalValues;
00372 
00373 public:
00374   ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
00375                       std::vector<GlobalValue *> &LazilyLinkGlobalValues)
00376       : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
00377         LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
00378 
00379   Value *materializeValueFor(Value *V) override;
00380 };
00381 
00382 class LinkDiagnosticInfo : public DiagnosticInfo {
00383   const Twine &Msg;
00384 
00385 public:
00386   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
00387   void print(DiagnosticPrinter &DP) const override;
00388 };
00389 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
00390                                        const Twine &Msg)
00391     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
00392 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
00393 
00394 /// This is an implementation class for the LinkModules function, which is the
00395 /// entrypoint for this file.
00396 class ModuleLinker {
00397   Module *DstM, *SrcM;
00398 
00399   TypeMapTy TypeMap;
00400   ValueMaterializerTy ValMaterializer;
00401 
00402   /// Mapping of values from what they used to be in Src, to what they are now
00403   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
00404   /// due to the use of Value handles which the Linker doesn't actually need,
00405   /// but this allows us to reuse the ValueMapper code.
00406   ValueToValueMapTy ValueMap;
00407 
00408   struct AppendingVarInfo {
00409     GlobalVariable *NewGV;   // New aggregate global in dest module.
00410     const Constant *DstInit; // Old initializer from dest module.
00411     const Constant *SrcInit; // Old initializer from src module.
00412   };
00413 
00414   std::vector<AppendingVarInfo> AppendingVars;
00415 
00416   // Set of items not to link in from source.
00417   SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
00418 
00419   // Vector of GlobalValues to lazily link in.
00420   std::vector<GlobalValue *> LazilyLinkGlobalValues;
00421 
00422   /// Functions that have replaced other functions.
00423   SmallPtrSet<const Function *, 16> OverridingFunctions;
00424 
00425   DiagnosticHandlerFunction DiagnosticHandler;
00426 
00427 public:
00428   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
00429                DiagnosticHandlerFunction DiagnosticHandler)
00430       : DstM(dstM), SrcM(srcM), TypeMap(Set),
00431         ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
00432         DiagnosticHandler(DiagnosticHandler) {}
00433 
00434   bool run();
00435 
00436 private:
00437   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
00438                             const GlobalValue &Src);
00439 
00440   /// Helper method for setting a message and returning an error code.
00441   bool emitError(const Twine &Message) {
00442     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
00443     return true;
00444   }
00445 
00446   void emitWarning(const Twine &Message) {
00447     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
00448   }
00449 
00450   bool getComdatLeader(Module *M, StringRef ComdatName,
00451                        const GlobalVariable *&GVar);
00452   bool computeResultingSelectionKind(StringRef ComdatName,
00453                                      Comdat::SelectionKind Src,
00454                                      Comdat::SelectionKind Dst,
00455                                      Comdat::SelectionKind &Result,
00456                                      bool &LinkFromSrc);
00457   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
00458       ComdatsChosen;
00459   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
00460                        bool &LinkFromSrc);
00461 
00462   /// Given a global in the source module, return the global in the
00463   /// destination module that is being linked to, if any.
00464   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
00465     // If the source has no name it can't link.  If it has local linkage,
00466     // there is no name match-up going on.
00467     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
00468       return nullptr;
00469 
00470     // Otherwise see if we have a match in the destination module's symtab.
00471     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
00472     if (!DGV)
00473       return nullptr;
00474 
00475     // If we found a global with the same name in the dest module, but it has
00476     // internal linkage, we are really not doing any linkage here.
00477     if (DGV->hasLocalLinkage())
00478       return nullptr;
00479 
00480     // Otherwise, we do in fact link to the destination global.
00481     return DGV;
00482   }
00483 
00484   void computeTypeMapping();
00485 
00486   void upgradeMismatchedGlobalArray(StringRef Name);
00487   void upgradeMismatchedGlobals();
00488 
00489   bool linkAppendingVarProto(GlobalVariable *DstGV,
00490                              const GlobalVariable *SrcGV);
00491 
00492   bool linkGlobalValueProto(GlobalValue *GV);
00493   bool linkModuleFlagsMetadata();
00494 
00495   void linkAppendingVarInit(const AppendingVarInfo &AVI);
00496 
00497   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
00498   bool linkFunctionBody(Function &Dst, Function &Src);
00499   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
00500   bool linkGlobalValueBody(GlobalValue &Src);
00501 
00502   void linkNamedMDNodes();
00503   void stripReplacedSubprograms();
00504 };
00505 }
00506 
00507 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
00508 /// table. This is good for all clients except for us. Go through the trouble
00509 /// to force this back.
00510 static void forceRenaming(GlobalValue *GV, StringRef Name) {
00511   // If the global doesn't force its name or if it already has the right name,
00512   // there is nothing for us to do.
00513   if (GV->hasLocalLinkage() || GV->getName() == Name)
00514     return;
00515 
00516   Module *M = GV->getParent();
00517 
00518   // If there is a conflict, rename the conflict.
00519   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
00520     GV->takeName(ConflictGV);
00521     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
00522     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
00523   } else {
00524     GV->setName(Name);              // Force the name back
00525   }
00526 }
00527 
00528 /// copy additional attributes (those not needed to construct a GlobalValue)
00529 /// from the SrcGV to the DestGV.
00530 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
00531   DestGV->copyAttributesFrom(SrcGV);
00532   forceRenaming(DestGV, SrcGV->getName());
00533 }
00534 
00535 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
00536                                GlobalValue::VisibilityTypes b) {
00537   if (a == GlobalValue::HiddenVisibility)
00538     return false;
00539   if (b == GlobalValue::HiddenVisibility)
00540     return true;
00541   if (a == GlobalValue::ProtectedVisibility)
00542     return false;
00543   if (b == GlobalValue::ProtectedVisibility)
00544     return true;
00545   return false;
00546 }
00547 
00548 /// Loop through the global variables in the src module and merge them into the
00549 /// dest module.
00550 static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
00551                                                const GlobalVariable *SGVar) {
00552   // No linking to be performed or linking from the source: simply create an
00553   // identical version of the symbol over in the dest module... the
00554   // initializer will be filled in later by LinkGlobalInits.
00555   GlobalVariable *NewDGV = new GlobalVariable(
00556       DstM, TypeMap.get(SGVar->getType()->getElementType()),
00557       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
00558       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
00559       SGVar->getType()->getAddressSpace());
00560 
00561   return NewDGV;
00562 }
00563 
00564 /// Link the function in the source module into the destination module if
00565 /// needed, setting up mapping information.
00566 static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
00567                                    const Function *SF) {
00568   // If there is no linkage to be performed or we are linking from the source,
00569   // bring SF over.
00570   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
00571                           SF->getName(), &DstM);
00572 }
00573 
00574 /// Set up prototypes for any aliases that come over from the source module.
00575 static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
00576                                          const GlobalAlias *SGA) {
00577   // If there is no linkage to be performed or we're linking from the source,
00578   // bring over SGA.
00579   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
00580   return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
00581                              SGA->getLinkage(), SGA->getName(), &DstM);
00582 }
00583 
00584 static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
00585                                          const GlobalValue *SGV) {
00586   GlobalValue *NewGV;
00587   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
00588     NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
00589   else if (auto *SF = dyn_cast<Function>(SGV))
00590     NewGV = copyFunctionProto(TypeMap, DstM, SF);
00591   else
00592     NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
00593   copyGVAttributes(NewGV, SGV);
00594   return NewGV;
00595 }
00596 
00597 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
00598   auto *SGV = dyn_cast<GlobalValue>(V);
00599   if (!SGV)
00600     return nullptr;
00601 
00602   GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
00603 
00604   if (Comdat *SC = SGV->getComdat()) {
00605     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
00606       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
00607       DGO->setComdat(DC);
00608     }
00609   }
00610 
00611   LazilyLinkGlobalValues.push_back(SGV);
00612   return DGV;
00613 }
00614 
00615 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
00616                                    const GlobalVariable *&GVar) {
00617   const GlobalValue *GVal = M->getNamedValue(ComdatName);
00618   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
00619     GVal = GA->getBaseObject();
00620     if (!GVal)
00621       // We cannot resolve the size of the aliasee yet.
00622       return emitError("Linking COMDATs named '" + ComdatName +
00623                        "': COMDAT key involves incomputable alias size.");
00624   }
00625 
00626   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
00627   if (!GVar)
00628     return emitError(
00629         "Linking COMDATs named '" + ComdatName +
00630         "': GlobalVariable required for data dependent selection!");
00631 
00632   return false;
00633 }
00634 
00635 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
00636                                                  Comdat::SelectionKind Src,
00637                                                  Comdat::SelectionKind Dst,
00638                                                  Comdat::SelectionKind &Result,
00639                                                  bool &LinkFromSrc) {
00640   // The ability to mix Comdat::SelectionKind::Any with
00641   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
00642   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
00643                          Dst == Comdat::SelectionKind::Largest;
00644   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
00645                          Src == Comdat::SelectionKind::Largest;
00646   if (DstAnyOrLargest && SrcAnyOrLargest) {
00647     if (Dst == Comdat::SelectionKind::Largest ||
00648         Src == Comdat::SelectionKind::Largest)
00649       Result = Comdat::SelectionKind::Largest;
00650     else
00651       Result = Comdat::SelectionKind::Any;
00652   } else if (Src == Dst) {
00653     Result = Dst;
00654   } else {
00655     return emitError("Linking COMDATs named '" + ComdatName +
00656                      "': invalid selection kinds!");
00657   }
00658 
00659   switch (Result) {
00660   case Comdat::SelectionKind::Any:
00661     // Go with Dst.
00662     LinkFromSrc = false;
00663     break;
00664   case Comdat::SelectionKind::NoDuplicates:
00665     return emitError("Linking COMDATs named '" + ComdatName +
00666                      "': noduplicates has been violated!");
00667   case Comdat::SelectionKind::ExactMatch:
00668   case Comdat::SelectionKind::Largest:
00669   case Comdat::SelectionKind::SameSize: {
00670     const GlobalVariable *DstGV;
00671     const GlobalVariable *SrcGV;
00672     if (getComdatLeader(DstM, ComdatName, DstGV) ||
00673         getComdatLeader(SrcM, ComdatName, SrcGV))
00674       return true;
00675 
00676     const DataLayout &DstDL = DstM->getDataLayout();
00677     const DataLayout &SrcDL = SrcM->getDataLayout();
00678     uint64_t DstSize =
00679         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
00680     uint64_t SrcSize =
00681         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
00682     if (Result == Comdat::SelectionKind::ExactMatch) {
00683       if (SrcGV->getInitializer() != DstGV->getInitializer())
00684         return emitError("Linking COMDATs named '" + ComdatName +
00685                          "': ExactMatch violated!");
00686       LinkFromSrc = false;
00687     } else if (Result == Comdat::SelectionKind::Largest) {
00688       LinkFromSrc = SrcSize > DstSize;
00689     } else if (Result == Comdat::SelectionKind::SameSize) {
00690       if (SrcSize != DstSize)
00691         return emitError("Linking COMDATs named '" + ComdatName +
00692                          "': SameSize violated!");
00693       LinkFromSrc = false;
00694     } else {
00695       llvm_unreachable("unknown selection kind");
00696     }
00697     break;
00698   }
00699   }
00700 
00701   return false;
00702 }
00703 
00704 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
00705                                    Comdat::SelectionKind &Result,
00706                                    bool &LinkFromSrc) {
00707   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
00708   StringRef ComdatName = SrcC->getName();
00709   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
00710   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
00711 
00712   if (DstCI == ComdatSymTab.end()) {
00713     // Use the comdat if it is only available in one of the modules.
00714     LinkFromSrc = true;
00715     Result = SSK;
00716     return false;
00717   }
00718 
00719   const Comdat *DstC = &DstCI->second;
00720   Comdat::SelectionKind DSK = DstC->getSelectionKind();
00721   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
00722                                        LinkFromSrc);
00723 }
00724 
00725 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
00726                                         const GlobalValue &Dest,
00727                                         const GlobalValue &Src) {
00728   // We always have to add Src if it has appending linkage.
00729   if (Src.hasAppendingLinkage()) {
00730     LinkFromSrc = true;
00731     return false;
00732   }
00733 
00734   bool SrcIsDeclaration = Src.isDeclarationForLinker();
00735   bool DestIsDeclaration = Dest.isDeclarationForLinker();
00736 
00737   if (SrcIsDeclaration) {
00738     // If Src is external or if both Src & Dest are external..  Just link the
00739     // external globals, we aren't adding anything.
00740     if (Src.hasDLLImportStorageClass()) {
00741       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
00742       LinkFromSrc = DestIsDeclaration;
00743       return false;
00744     }
00745     // If the Dest is weak, use the source linkage.
00746     LinkFromSrc = Dest.hasExternalWeakLinkage();
00747     return false;
00748   }
00749 
00750   if (DestIsDeclaration) {
00751     // If Dest is external but Src is not:
00752     LinkFromSrc = true;
00753     return false;
00754   }
00755 
00756   if (Src.hasCommonLinkage()) {
00757     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
00758       LinkFromSrc = true;
00759       return false;
00760     }
00761 
00762     if (!Dest.hasCommonLinkage()) {
00763       LinkFromSrc = false;
00764       return false;
00765     }
00766 
00767     const DataLayout &DL = Dest.getParent()->getDataLayout();
00768     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
00769     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
00770     LinkFromSrc = SrcSize > DestSize;
00771     return false;
00772   }
00773 
00774   if (Src.isWeakForLinker()) {
00775     assert(!Dest.hasExternalWeakLinkage());
00776     assert(!Dest.hasAvailableExternallyLinkage());
00777 
00778     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
00779       LinkFromSrc = true;
00780       return false;
00781     }
00782 
00783     LinkFromSrc = false;
00784     return false;
00785   }
00786 
00787   if (Dest.isWeakForLinker()) {
00788     assert(Src.hasExternalLinkage());
00789     LinkFromSrc = true;
00790     return false;
00791   }
00792 
00793   assert(!Src.hasExternalWeakLinkage());
00794   assert(!Dest.hasExternalWeakLinkage());
00795   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
00796          "Unexpected linkage type!");
00797   return emitError("Linking globals named '" + Src.getName() +
00798                    "': symbol multiply defined!");
00799 }
00800 
00801 /// Loop over all of the linked values to compute type mappings.  For example,
00802 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
00803 /// types 'Foo' but one got renamed when the module was loaded into the same
00804 /// LLVMContext.
00805 void ModuleLinker::computeTypeMapping() {
00806   for (GlobalValue &SGV : SrcM->globals()) {
00807     GlobalValue *DGV = getLinkedToGlobal(&SGV);
00808     if (!DGV)
00809       continue;
00810 
00811     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
00812       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00813       continue;
00814     }
00815 
00816     // Unify the element type of appending arrays.
00817     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
00818     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
00819     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
00820   }
00821 
00822   for (GlobalValue &SGV : *SrcM) {
00823     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
00824       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00825   }
00826 
00827   for (GlobalValue &SGV : SrcM->aliases()) {
00828     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
00829       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00830   }
00831 
00832   // Incorporate types by name, scanning all the types in the source module.
00833   // At this point, the destination module may have a type "%foo = { i32 }" for
00834   // example.  When the source module got loaded into the same LLVMContext, if
00835   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
00836   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
00837   for (StructType *ST : Types) {
00838     if (!ST->hasName())
00839       continue;
00840 
00841     // Check to see if there is a dot in the name followed by a digit.
00842     size_t DotPos = ST->getName().rfind('.');
00843     if (DotPos == 0 || DotPos == StringRef::npos ||
00844         ST->getName().back() == '.' ||
00845         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
00846       continue;
00847 
00848     // Check to see if the destination module has a struct with the prefix name.
00849     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
00850     if (!DST)
00851       continue;
00852 
00853     // Don't use it if this actually came from the source module. They're in
00854     // the same LLVMContext after all. Also don't use it unless the type is
00855     // actually used in the destination module. This can happen in situations
00856     // like this:
00857     //
00858     //      Module A                         Module B
00859     //      --------                         --------
00860     //   %Z = type { %A }                %B = type { %C.1 }
00861     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
00862     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
00863     //   %C = type { i8* }               %B.3 = type { %C.1 }
00864     //
00865     // When we link Module B with Module A, the '%B' in Module B is
00866     // used. However, that would then use '%C.1'. But when we process '%C.1',
00867     // we prefer to take the '%C' version. So we are then left with both
00868     // '%C.1' and '%C' being used for the same types. This leads to some
00869     // variables using one type and some using the other.
00870     if (TypeMap.DstStructTypesSet.hasType(DST))
00871       TypeMap.addTypeMapping(DST, ST);
00872   }
00873 
00874   // Now that we have discovered all of the type equivalences, get a body for
00875   // any 'opaque' types in the dest module that are now resolved.
00876   TypeMap.linkDefinedTypeBodies();
00877 }
00878 
00879 static void upgradeGlobalArray(GlobalVariable *GV) {
00880   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
00881   StructType *OldTy = cast<StructType>(ATy->getElementType());
00882   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
00883 
00884   // Get the upgraded 3 element type.
00885   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
00886   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
00887                   VoidPtrTy};
00888   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
00889 
00890   // Build new constants with a null third field filled in.
00891   Constant *OldInitC = GV->getInitializer();
00892   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
00893   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
00894     // Invalid initializer; give up.
00895     return;
00896   std::vector<Constant *> Initializers;
00897   if (OldInit && OldInit->getNumOperands()) {
00898     Value *Null = Constant::getNullValue(VoidPtrTy);
00899     for (Use &U : OldInit->operands()) {
00900       ConstantStruct *Init = cast<ConstantStruct>(U.get());
00901       Initializers.push_back(ConstantStruct::get(
00902           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
00903     }
00904   }
00905   assert(Initializers.size() == ATy->getNumElements() &&
00906          "Failed to copy all array elements");
00907 
00908   // Replace the old GV with a new one.
00909   ATy = ArrayType::get(NewTy, Initializers.size());
00910   Constant *NewInit = ConstantArray::get(ATy, Initializers);
00911   GlobalVariable *NewGV = new GlobalVariable(
00912       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
00913       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
00914       GV->isExternallyInitialized());
00915   NewGV->copyAttributesFrom(GV);
00916   NewGV->takeName(GV);
00917   assert(GV->use_empty() && "program cannot use initializer list");
00918   GV->eraseFromParent();
00919 }
00920 
00921 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
00922   // Look for the global arrays.
00923   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
00924   if (!DstGV)
00925     return;
00926   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
00927   if (!SrcGV)
00928     return;
00929 
00930   // Check if the types already match.
00931   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00932   auto *SrcTy =
00933       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00934   if (DstTy == SrcTy)
00935     return;
00936 
00937   // Grab the element types.  We can only upgrade an array of a two-field
00938   // struct.  Only bother if the other one has three-fields.
00939   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
00940   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
00941   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
00942     upgradeGlobalArray(DstGV);
00943     return;
00944   }
00945   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
00946     upgradeGlobalArray(SrcGV);
00947 
00948   // We can't upgrade any other differences.
00949 }
00950 
00951 void ModuleLinker::upgradeMismatchedGlobals() {
00952   upgradeMismatchedGlobalArray("llvm.global_ctors");
00953   upgradeMismatchedGlobalArray("llvm.global_dtors");
00954 }
00955 
00956 /// If there were any appending global variables, link them together now.
00957 /// Return true on error.
00958 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
00959                                          const GlobalVariable *SrcGV) {
00960 
00961   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
00962     return emitError("Linking globals named '" + SrcGV->getName() +
00963            "': can only link appending global with another appending global!");
00964 
00965   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00966   ArrayType *SrcTy =
00967     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00968   Type *EltTy = DstTy->getElementType();
00969 
00970   // Check to see that they two arrays agree on type.
00971   if (EltTy != SrcTy->getElementType())
00972     return emitError("Appending variables with different element types!");
00973   if (DstGV->isConstant() != SrcGV->isConstant())
00974     return emitError("Appending variables linked with different const'ness!");
00975 
00976   if (DstGV->getAlignment() != SrcGV->getAlignment())
00977     return emitError(
00978              "Appending variables with different alignment need to be linked!");
00979 
00980   if (DstGV->getVisibility() != SrcGV->getVisibility())
00981     return emitError(
00982             "Appending variables with different visibility need to be linked!");
00983 
00984   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
00985     return emitError(
00986         "Appending variables with different unnamed_addr need to be linked!");
00987 
00988   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
00989     return emitError(
00990           "Appending variables with different section name need to be linked!");
00991 
00992   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
00993   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
00994 
00995   // Create the new global variable.
00996   GlobalVariable *NG =
00997     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
00998                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
00999                        DstGV->getThreadLocalMode(),
01000                        DstGV->getType()->getAddressSpace());
01001 
01002   // Propagate alignment, visibility and section info.
01003   copyGVAttributes(NG, DstGV);
01004 
01005   AppendingVarInfo AVI;
01006   AVI.NewGV = NG;
01007   AVI.DstInit = DstGV->getInitializer();
01008   AVI.SrcInit = SrcGV->getInitializer();
01009   AppendingVars.push_back(AVI);
01010 
01011   // Replace any uses of the two global variables with uses of the new
01012   // global.
01013   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
01014 
01015   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
01016   DstGV->eraseFromParent();
01017 
01018   // Track the source variable so we don't try to link it.
01019   DoNotLinkFromSource.insert(SrcGV);
01020 
01021   return false;
01022 }
01023 
01024 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
01025   GlobalValue *DGV = getLinkedToGlobal(SGV);
01026 
01027   // Handle the ultra special appending linkage case first.
01028   if (DGV && DGV->hasAppendingLinkage())
01029     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
01030                                  cast<GlobalVariable>(SGV));
01031 
01032   bool LinkFromSrc = true;
01033   Comdat *C = nullptr;
01034   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
01035   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
01036 
01037   if (const Comdat *SC = SGV->getComdat()) {
01038     Comdat::SelectionKind SK;
01039     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
01040     C = DstM->getOrInsertComdat(SC->getName());
01041     C->setSelectionKind(SK);
01042   } else if (DGV) {
01043     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
01044       return true;
01045   }
01046 
01047   if (!LinkFromSrc) {
01048     // Track the source global so that we don't attempt to copy it over when
01049     // processing global initializers.
01050     DoNotLinkFromSource.insert(SGV);
01051 
01052     if (DGV)
01053       // Make sure to remember this mapping.
01054       ValueMap[SGV] =
01055           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
01056   }
01057 
01058   if (DGV) {
01059     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
01060                      ? DGV->getVisibility()
01061                      : Visibility;
01062     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
01063   }
01064 
01065   if (!LinkFromSrc && !DGV)
01066     return false;
01067 
01068   GlobalValue *NewGV;
01069   if (!LinkFromSrc) {
01070     NewGV = DGV;
01071   } else {
01072     // If the GV is to be lazily linked, don't create it just yet.
01073     // The ValueMaterializerTy will deal with creating it if it's used.
01074     if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
01075                  SGV->hasAvailableExternallyLinkage())) {
01076       DoNotLinkFromSource.insert(SGV);
01077       return false;
01078     }
01079 
01080     NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
01081 
01082     if (DGV && isa<Function>(DGV))
01083       if (auto *NewF = dyn_cast<Function>(NewGV))
01084         OverridingFunctions.insert(NewF);
01085   }
01086 
01087   NewGV->setUnnamedAddr(HasUnnamedAddr);
01088   NewGV->setVisibility(Visibility);
01089 
01090   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
01091     if (C)
01092       NewGO->setComdat(C);
01093 
01094     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
01095       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
01096   }
01097 
01098   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
01099     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
01100     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
01101     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
01102         (!DGVar->isConstant() || !SGVar->isConstant()))
01103       NewGVar->setConstant(false);
01104   }
01105 
01106   // Make sure to remember this mapping.
01107   if (NewGV != DGV) {
01108     if (DGV) {
01109       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
01110       DGV->eraseFromParent();
01111     }
01112     ValueMap[SGV] = NewGV;
01113   }
01114 
01115   return false;
01116 }
01117 
01118 static void getArrayElements(const Constant *C,
01119                              SmallVectorImpl<Constant *> &Dest) {
01120   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
01121 
01122   for (unsigned i = 0; i != NumElements; ++i)
01123     Dest.push_back(C->getAggregateElement(i));
01124 }
01125 
01126 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
01127   // Merge the initializer.
01128   SmallVector<Constant *, 16> DstElements;
01129   getArrayElements(AVI.DstInit, DstElements);
01130 
01131   SmallVector<Constant *, 16> SrcElements;
01132   getArrayElements(AVI.SrcInit, SrcElements);
01133 
01134   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
01135 
01136   StringRef Name = AVI.NewGV->getName();
01137   bool IsNewStructor =
01138       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
01139       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
01140 
01141   for (auto *V : SrcElements) {
01142     if (IsNewStructor) {
01143       Constant *Key = V->getAggregateElement(2);
01144       if (DoNotLinkFromSource.count(Key))
01145         continue;
01146     }
01147     DstElements.push_back(
01148         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
01149   }
01150   if (IsNewStructor) {
01151     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
01152     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
01153   }
01154 
01155   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
01156 }
01157 
01158 /// Update the initializers in the Dest module now that all globals that may be
01159 /// referenced are in Dest.
01160 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
01161   // Figure out what the initializer looks like in the dest module.
01162   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap,
01163                               &ValMaterializer));
01164 }
01165 
01166 /// Copy the source function over into the dest function and fix up references
01167 /// to values. At this point we know that Dest is an external function, and
01168 /// that Src is not.
01169 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
01170   assert(Dst.isDeclaration() && !Src.isDeclaration());
01171 
01172   // Materialize if needed.
01173   if (std::error_code EC = Src.materialize())
01174     return emitError(EC.message());
01175 
01176   // Link in the prefix data.
01177   if (Src.hasPrefixData())
01178     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap,
01179                                &ValMaterializer));
01180 
01181   // Link in the prologue data.
01182   if (Src.hasPrologueData())
01183     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None,
01184                                  &TypeMap, &ValMaterializer));
01185 
01186   // Go through and convert function arguments over, remembering the mapping.
01187   Function::arg_iterator DI = Dst.arg_begin();
01188   for (Argument &Arg : Src.args()) {
01189     DI->setName(Arg.getName());  // Copy the name over.
01190 
01191     // Add a mapping to our mapping.
01192     ValueMap[&Arg] = DI;
01193     ++DI;
01194   }
01195 
01196   // Splice the body of the source function into the dest function.
01197   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
01198 
01199   // At this point, all of the instructions and values of the function are now
01200   // copied over.  The only problem is that they are still referencing values in
01201   // the Source function as operands.  Loop through all of the operands of the
01202   // functions and patch them up to point to the local versions.
01203   for (BasicBlock &BB : Dst)
01204     for (Instruction &I : BB)
01205       RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
01206                        &ValMaterializer);
01207 
01208   // There is no need to map the arguments anymore.
01209   for (Argument &Arg : Src.args())
01210     ValueMap.erase(&Arg);
01211 
01212   Src.Dematerialize();
01213   return false;
01214 }
01215 
01216 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
01217   Constant *Aliasee = Src.getAliasee();
01218   Constant *Val =
01219       MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01220   Dst.setAliasee(Val);
01221 }
01222 
01223 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
01224   Value *Dst = ValueMap[&Src];
01225   assert(Dst);
01226   if (auto *F = dyn_cast<Function>(&Src))
01227     return linkFunctionBody(cast<Function>(*Dst), *F);
01228   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
01229     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
01230     return false;
01231   }
01232   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
01233   return false;
01234 }
01235 
01236 /// Insert all of the named MDNodes in Src into the Dest module.
01237 void ModuleLinker::linkNamedMDNodes() {
01238   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01239   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
01240        E = SrcM->named_metadata_end(); I != E; ++I) {
01241     // Don't link module flags here. Do them separately.
01242     if (&*I == SrcModFlags) continue;
01243     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
01244     // Add Src elements into Dest node.
01245     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01246       DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None,
01247                                       &TypeMap, &ValMaterializer));
01248   }
01249 }
01250 
01251 /// Drop DISubprograms that have been superseded.
01252 ///
01253 /// FIXME: this creates an asymmetric result: we strip functions from losing
01254 /// subprograms in DstM, but leave losing subprograms in SrcM.
01255 /// TODO: Remove this logic once the backend can correctly determine canonical
01256 /// subprograms.
01257 void ModuleLinker::stripReplacedSubprograms() {
01258   // Avoid quadratic runtime by returning early when there's nothing to do.
01259   if (OverridingFunctions.empty())
01260     return;
01261 
01262   // Move the functions now, so the set gets cleared even on early returns.
01263   auto Functions = std::move(OverridingFunctions);
01264   OverridingFunctions.clear();
01265 
01266   // Drop functions from subprograms if they've been overridden by the new
01267   // compile unit.
01268   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
01269   if (!CompileUnits)
01270     return;
01271   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
01272     DICompileUnit CU(CompileUnits->getOperand(I));
01273     assert(CU && "Expected valid compile unit");
01274 
01275     DITypedArray<DISubprogram> SPs(CU.getSubprograms());
01276     assert(SPs && "Expected valid subprogram array");
01277 
01278     for (unsigned S = 0, SE = SPs.getNumElements(); S != SE; ++S) {
01279       DISubprogram SP = SPs.getElement(S);
01280       if (!SP || !SP.getFunction() || !Functions.count(SP.getFunction()))
01281         continue;
01282 
01283       // Prevent DebugInfoFinder from tagging this as the canonical subprogram,
01284       // since the canonical one is in the incoming module.
01285       SP->replaceFunction(nullptr);
01286     }
01287   }
01288 }
01289 
01290 /// Merge the linker flags in Src into the Dest module.
01291 bool ModuleLinker::linkModuleFlagsMetadata() {
01292   // If the source module has no module flags, we are done.
01293   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01294   if (!SrcModFlags) return false;
01295 
01296   // If the destination module doesn't have module flags yet, then just copy
01297   // over the source module's flags.
01298   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
01299   if (DstModFlags->getNumOperands() == 0) {
01300     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
01301       DstModFlags->addOperand(SrcModFlags->getOperand(I));
01302 
01303     return false;
01304   }
01305 
01306   // First build a map of the existing module flags and requirements.
01307   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
01308   SmallSetVector<MDNode*, 16> Requirements;
01309   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
01310     MDNode *Op = DstModFlags->getOperand(I);
01311     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
01312     MDString *ID = cast<MDString>(Op->getOperand(1));
01313 
01314     if (Behavior->getZExtValue() == Module::Require) {
01315       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
01316     } else {
01317       Flags[ID] = std::make_pair(Op, I);
01318     }
01319   }
01320 
01321   // Merge in the flags from the source module, and also collect its set of
01322   // requirements.
01323   bool HasErr = false;
01324   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
01325     MDNode *SrcOp = SrcModFlags->getOperand(I);
01326     ConstantInt *SrcBehavior =
01327         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
01328     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
01329     MDNode *DstOp;
01330     unsigned DstIndex;
01331     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
01332     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
01333 
01334     // If this is a requirement, add it and continue.
01335     if (SrcBehaviorValue == Module::Require) {
01336       // If the destination module does not already have this requirement, add
01337       // it.
01338       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
01339         DstModFlags->addOperand(SrcOp);
01340       }
01341       continue;
01342     }
01343 
01344     // If there is no existing flag with this ID, just add it.
01345     if (!DstOp) {
01346       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
01347       DstModFlags->addOperand(SrcOp);
01348       continue;
01349     }
01350 
01351     // Otherwise, perform a merge.
01352     ConstantInt *DstBehavior =
01353         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
01354     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
01355 
01356     // If either flag has override behavior, handle it first.
01357     if (DstBehaviorValue == Module::Override) {
01358       // Diagnose inconsistent flags which both have override behavior.
01359       if (SrcBehaviorValue == Module::Override &&
01360           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01361         HasErr |= emitError("linking module flags '" + ID->getString() +
01362                             "': IDs have conflicting override values");
01363       }
01364       continue;
01365     } else if (SrcBehaviorValue == Module::Override) {
01366       // Update the destination flag to that of the source.
01367       DstModFlags->setOperand(DstIndex, SrcOp);
01368       Flags[ID].first = SrcOp;
01369       continue;
01370     }
01371 
01372     // Diagnose inconsistent merge behavior types.
01373     if (SrcBehaviorValue != DstBehaviorValue) {
01374       HasErr |= emitError("linking module flags '" + ID->getString() +
01375                           "': IDs have conflicting behaviors");
01376       continue;
01377     }
01378 
01379     auto replaceDstValue = [&](MDNode *New) {
01380       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
01381       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
01382       DstModFlags->setOperand(DstIndex, Flag);
01383       Flags[ID].first = Flag;
01384     };
01385 
01386     // Perform the merge for standard behavior types.
01387     switch (SrcBehaviorValue) {
01388     case Module::Require:
01389     case Module::Override: llvm_unreachable("not possible");
01390     case Module::Error: {
01391       // Emit an error if the values differ.
01392       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01393         HasErr |= emitError("linking module flags '" + ID->getString() +
01394                             "': IDs have conflicting values");
01395       }
01396       continue;
01397     }
01398     case Module::Warning: {
01399       // Emit a warning if the values differ.
01400       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01401         emitWarning("linking module flags '" + ID->getString() +
01402                     "': IDs have conflicting values");
01403       }
01404       continue;
01405     }
01406     case Module::Append: {
01407       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01408       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01409       SmallVector<Metadata *, 8> MDs;
01410       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
01411       MDs.append(DstValue->op_begin(), DstValue->op_end());
01412       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
01413 
01414       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
01415       break;
01416     }
01417     case Module::AppendUnique: {
01418       SmallSetVector<Metadata *, 16> Elts;
01419       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01420       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01421       Elts.insert(DstValue->op_begin(), DstValue->op_end());
01422       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
01423 
01424       replaceDstValue(MDNode::get(DstM->getContext(),
01425                                   makeArrayRef(Elts.begin(), Elts.end())));
01426       break;
01427     }
01428     }
01429   }
01430 
01431   // Check all of the requirements.
01432   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
01433     MDNode *Requirement = Requirements[I];
01434     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
01435     Metadata *ReqValue = Requirement->getOperand(1);
01436 
01437     MDNode *Op = Flags[Flag].first;
01438     if (!Op || Op->getOperand(2) != ReqValue) {
01439       HasErr |= emitError("linking module flags '" + Flag->getString() +
01440                           "': does not have the required value");
01441       continue;
01442     }
01443   }
01444 
01445   return HasErr;
01446 }
01447 
01448 // This function returns true if the triples match.
01449 static bool triplesMatch(const Triple &T0, const Triple &T1) {
01450   // If vendor is apple, ignore the version number.
01451   if (T0.getVendor() == Triple::Apple)
01452     return T0.getArch() == T1.getArch() &&
01453            T0.getSubArch() == T1.getSubArch() &&
01454            T0.getVendor() == T1.getVendor() &&
01455            T0.getOS() == T1.getOS();
01456 
01457   return T0 == T1;
01458 }
01459 
01460 // This function returns the merged triple.
01461 static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
01462   // If vendor is apple, pick the triple with the larger version number.
01463   if (SrcTriple.getVendor() == Triple::Apple)
01464     if (DstTriple.isOSVersionLT(SrcTriple))
01465       return SrcTriple.str();
01466 
01467   return DstTriple.str();
01468 }
01469 
01470 bool ModuleLinker::run() {
01471   assert(DstM && "Null destination module");
01472   assert(SrcM && "Null source module");
01473 
01474   // Inherit the target data from the source module if the destination module
01475   // doesn't have one already.
01476   if (DstM->getDataLayout().isDefault())
01477     DstM->setDataLayout(SrcM->getDataLayout());
01478 
01479   if (SrcM->getDataLayout() != DstM->getDataLayout()) {
01480     emitWarning("Linking two modules of different data layouts: '" +
01481                 SrcM->getModuleIdentifier() + "' is '" +
01482                 SrcM->getDataLayoutStr() + "' whereas '" +
01483                 DstM->getModuleIdentifier() + "' is '" +
01484                 DstM->getDataLayoutStr() + "'\n");
01485   }
01486 
01487   // Copy the target triple from the source to dest if the dest's is empty.
01488   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
01489     DstM->setTargetTriple(SrcM->getTargetTriple());
01490 
01491   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
01492 
01493   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
01494     emitWarning("Linking two modules of different target triples: " +
01495                 SrcM->getModuleIdentifier() + "' is '" +
01496                 SrcM->getTargetTriple() + "' whereas '" +
01497                 DstM->getModuleIdentifier() + "' is '" +
01498                 DstM->getTargetTriple() + "'\n");
01499 
01500   DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
01501 
01502   // Append the module inline asm string.
01503   if (!SrcM->getModuleInlineAsm().empty()) {
01504     if (DstM->getModuleInlineAsm().empty())
01505       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
01506     else
01507       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
01508                                SrcM->getModuleInlineAsm());
01509   }
01510 
01511   // Loop over all of the linked values to compute type mappings.
01512   computeTypeMapping();
01513 
01514   ComdatsChosen.clear();
01515   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
01516     const Comdat &C = SMEC.getValue();
01517     if (ComdatsChosen.count(&C))
01518       continue;
01519     Comdat::SelectionKind SK;
01520     bool LinkFromSrc;
01521     if (getComdatResult(&C, SK, LinkFromSrc))
01522       return true;
01523     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
01524   }
01525 
01526   // Upgrade mismatched global arrays.
01527   upgradeMismatchedGlobals();
01528 
01529   // Insert all of the globals in src into the DstM module... without linking
01530   // initializers (which could refer to functions not yet mapped over).
01531   for (Module::global_iterator I = SrcM->global_begin(),
01532        E = SrcM->global_end(); I != E; ++I)
01533     if (linkGlobalValueProto(I))
01534       return true;
01535 
01536   // Link the functions together between the two modules, without doing function
01537   // bodies... this just adds external function prototypes to the DstM
01538   // function...  We do this so that when we begin processing function bodies,
01539   // all of the global values that may be referenced are available in our
01540   // ValueMap.
01541   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
01542     if (linkGlobalValueProto(I))
01543       return true;
01544 
01545   // If there were any aliases, link them now.
01546   for (Module::alias_iterator I = SrcM->alias_begin(),
01547        E = SrcM->alias_end(); I != E; ++I)
01548     if (linkGlobalValueProto(I))
01549       return true;
01550 
01551   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
01552     linkAppendingVarInit(AppendingVars[i]);
01553 
01554   for (const auto &Entry : DstM->getComdatSymbolTable()) {
01555     const Comdat &C = Entry.getValue();
01556     if (C.getSelectionKind() == Comdat::Any)
01557       continue;
01558     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
01559     assert(GV);
01560     MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01561   }
01562 
01563   // Strip replaced subprograms before mapping any metadata -- so that we're
01564   // not changing metadata from the source module (note that
01565   // linkGlobalValueBody() eventually calls RemapInstruction() and therefore
01566   // MapMetadata()) -- but after linking global value protocols -- so that
01567   // OverridingFunctions has been built.
01568   stripReplacedSubprograms();
01569 
01570   // Link in the function bodies that are defined in the source module into
01571   // DstM.
01572   for (Function &SF : *SrcM) {
01573     // Skip if no body (function is external).
01574     if (SF.isDeclaration())
01575       continue;
01576 
01577     // Skip if not linking from source.
01578     if (DoNotLinkFromSource.count(&SF))
01579       continue;
01580 
01581     if (linkGlobalValueBody(SF))
01582       return true;
01583   }
01584 
01585   // Resolve all uses of aliases with aliasees.
01586   for (GlobalAlias &Src : SrcM->aliases()) {
01587     if (DoNotLinkFromSource.count(&Src))
01588       continue;
01589     linkGlobalValueBody(Src);
01590   }
01591 
01592   // Remap all of the named MDNodes in Src into the DstM module. We do this
01593   // after linking GlobalValues so that MDNodes that reference GlobalValues
01594   // are properly remapped.
01595   linkNamedMDNodes();
01596 
01597   // Merge the module flags into the DstM module.
01598   if (linkModuleFlagsMetadata())
01599     return true;
01600 
01601   // Update the initializers in the DstM module now that all globals that may
01602   // be referenced are in DstM.
01603   for (GlobalVariable &Src : SrcM->globals()) {
01604     // Only process initialized GV's or ones not already in dest.
01605     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
01606       continue;
01607     linkGlobalValueBody(Src);
01608   }
01609 
01610   // Process vector of lazily linked in functions.
01611   while (!LazilyLinkGlobalValues.empty()) {
01612     GlobalValue *SGV = LazilyLinkGlobalValues.back();
01613     LazilyLinkGlobalValues.pop_back();
01614 
01615     assert(!SGV->isDeclaration() && "users should not pass down decls");
01616     if (linkGlobalValueBody(*SGV))
01617       return true;
01618   }
01619 
01620   return false;
01621 }
01622 
01623 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
01624     : ETypes(E), IsPacked(P) {}
01625 
01626 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
01627     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
01628 
01629 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
01630   if (IsPacked != That.IsPacked)
01631     return false;
01632   if (ETypes != That.ETypes)
01633     return false;
01634   return true;
01635 }
01636 
01637 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
01638   return !this->operator==(That);
01639 }
01640 
01641 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
01642   return DenseMapInfo<StructType *>::getEmptyKey();
01643 }
01644 
01645 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
01646   return DenseMapInfo<StructType *>::getTombstoneKey();
01647 }
01648 
01649 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
01650   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
01651                       Key.IsPacked);
01652 }
01653 
01654 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
01655   return getHashValue(KeyTy(ST));
01656 }
01657 
01658 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
01659                                         const StructType *RHS) {
01660   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
01661     return false;
01662   return LHS == KeyTy(RHS);
01663 }
01664 
01665 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
01666                                         const StructType *RHS) {
01667   if (RHS == getEmptyKey())
01668     return LHS == getEmptyKey();
01669 
01670   if (RHS == getTombstoneKey())
01671     return LHS == getTombstoneKey();
01672 
01673   return KeyTy(LHS) == KeyTy(RHS);
01674 }
01675 
01676 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
01677   assert(!Ty->isOpaque());
01678   NonOpaqueStructTypes.insert(Ty);
01679 }
01680 
01681 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
01682   assert(!Ty->isOpaque());
01683   NonOpaqueStructTypes.insert(Ty);
01684   bool Removed = OpaqueStructTypes.erase(Ty);
01685   (void)Removed;
01686   assert(Removed);
01687 }
01688 
01689 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
01690   assert(Ty->isOpaque());
01691   OpaqueStructTypes.insert(Ty);
01692 }
01693 
01694 StructType *
01695 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
01696                                                bool IsPacked) {
01697   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
01698   auto I = NonOpaqueStructTypes.find_as(Key);
01699   if (I == NonOpaqueStructTypes.end())
01700     return nullptr;
01701   return *I;
01702 }
01703 
01704 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
01705   if (Ty->isOpaque())
01706     return OpaqueStructTypes.count(Ty);
01707   auto I = NonOpaqueStructTypes.find(Ty);
01708   if (I == NonOpaqueStructTypes.end())
01709     return false;
01710   return *I == Ty;
01711 }
01712 
01713 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01714   this->Composite = M;
01715   this->DiagnosticHandler = DiagnosticHandler;
01716 
01717   TypeFinder StructTypes;
01718   StructTypes.run(*M, true);
01719   for (StructType *Ty : StructTypes) {
01720     if (Ty->isOpaque())
01721       IdentifiedStructTypes.addOpaque(Ty);
01722     else
01723       IdentifiedStructTypes.addNonOpaque(Ty);
01724   }
01725 }
01726 
01727 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01728   init(M, DiagnosticHandler);
01729 }
01730 
01731 Linker::Linker(Module *M) {
01732   init(M, [this](const DiagnosticInfo &DI) {
01733     Composite->getContext().diagnose(DI);
01734   });
01735 }
01736 
01737 Linker::~Linker() {
01738 }
01739 
01740 void Linker::deleteModule() {
01741   delete Composite;
01742   Composite = nullptr;
01743 }
01744 
01745 bool Linker::linkInModule(Module *Src) {
01746   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
01747                          DiagnosticHandler);
01748   bool RetCode = TheLinker.run();
01749   Composite->dropTriviallyDeadConstantArrays();
01750   return RetCode;
01751 }
01752 
01753 void Linker::setModule(Module *Dst) {
01754   init(Dst, DiagnosticHandler);
01755 }
01756 
01757 //===----------------------------------------------------------------------===//
01758 // LinkModules entrypoint.
01759 //===----------------------------------------------------------------------===//
01760 
01761 /// This function links two modules together, with the resulting Dest module
01762 /// modified to be the composite of the two input modules. If an error occurs,
01763 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
01764 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
01765 /// relied on to be consistent.
01766 bool Linker::LinkModules(Module *Dest, Module *Src,
01767                          DiagnosticHandlerFunction DiagnosticHandler) {
01768   Linker L(Dest, DiagnosticHandler);
01769   return L.linkInModule(Src);
01770 }
01771 
01772 bool Linker::LinkModules(Module *Dest, Module *Src) {
01773   Linker L(Dest);
01774   return L.linkInModule(Src);
01775 }
01776 
01777 //===----------------------------------------------------------------------===//
01778 // C API.
01779 //===----------------------------------------------------------------------===//
01780 
01781 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
01782                          LLVMLinkerMode Unused, char **OutMessages) {
01783   Module *D = unwrap(Dest);
01784   std::string Message;
01785   raw_string_ostream Stream(Message);
01786   DiagnosticPrinterRawOStream DP(Stream);
01787 
01788   LLVMBool Result = Linker::LinkModules(
01789       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
01790 
01791   if (OutMessages && Result)
01792     *OutMessages = strdup(Message.c_str());
01793   return Result;
01794 }