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   /// For symbol clashes, prefer those from Src.
00428   bool OverrideFromSrc;
00429 
00430 public:
00431   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
00432                DiagnosticHandlerFunction DiagnosticHandler,
00433                bool OverrideFromSrc)
00434       : DstM(dstM), SrcM(srcM), TypeMap(Set),
00435         ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
00436         DiagnosticHandler(DiagnosticHandler), OverrideFromSrc(OverrideFromSrc) {
00437   }
00438 
00439   bool run();
00440 
00441 private:
00442   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
00443                             const GlobalValue &Src);
00444 
00445   /// Helper method for setting a message and returning an error code.
00446   bool emitError(const Twine &Message) {
00447     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
00448     return true;
00449   }
00450 
00451   void emitWarning(const Twine &Message) {
00452     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
00453   }
00454 
00455   bool getComdatLeader(Module *M, StringRef ComdatName,
00456                        const GlobalVariable *&GVar);
00457   bool computeResultingSelectionKind(StringRef ComdatName,
00458                                      Comdat::SelectionKind Src,
00459                                      Comdat::SelectionKind Dst,
00460                                      Comdat::SelectionKind &Result,
00461                                      bool &LinkFromSrc);
00462   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
00463       ComdatsChosen;
00464   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
00465                        bool &LinkFromSrc);
00466 
00467   /// Given a global in the source module, return the global in the
00468   /// destination module that is being linked to, if any.
00469   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
00470     // If the source has no name it can't link.  If it has local linkage,
00471     // there is no name match-up going on.
00472     if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
00473       return nullptr;
00474 
00475     // Otherwise see if we have a match in the destination module's symtab.
00476     GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
00477     if (!DGV)
00478       return nullptr;
00479 
00480     // If we found a global with the same name in the dest module, but it has
00481     // internal linkage, we are really not doing any linkage here.
00482     if (DGV->hasLocalLinkage())
00483       return nullptr;
00484 
00485     // Otherwise, we do in fact link to the destination global.
00486     return DGV;
00487   }
00488 
00489   void computeTypeMapping();
00490 
00491   void upgradeMismatchedGlobalArray(StringRef Name);
00492   void upgradeMismatchedGlobals();
00493 
00494   bool linkAppendingVarProto(GlobalVariable *DstGV,
00495                              const GlobalVariable *SrcGV);
00496 
00497   bool linkGlobalValueProto(GlobalValue *GV);
00498   bool linkModuleFlagsMetadata();
00499 
00500   void linkAppendingVarInit(const AppendingVarInfo &AVI);
00501 
00502   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
00503   bool linkFunctionBody(Function &Dst, Function &Src);
00504   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
00505   bool linkGlobalValueBody(GlobalValue &Src);
00506 
00507   void linkNamedMDNodes();
00508   void stripReplacedSubprograms();
00509 };
00510 }
00511 
00512 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
00513 /// table. This is good for all clients except for us. Go through the trouble
00514 /// to force this back.
00515 static void forceRenaming(GlobalValue *GV, StringRef Name) {
00516   // If the global doesn't force its name or if it already has the right name,
00517   // there is nothing for us to do.
00518   if (GV->hasLocalLinkage() || GV->getName() == Name)
00519     return;
00520 
00521   Module *M = GV->getParent();
00522 
00523   // If there is a conflict, rename the conflict.
00524   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
00525     GV->takeName(ConflictGV);
00526     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
00527     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
00528   } else {
00529     GV->setName(Name);              // Force the name back
00530   }
00531 }
00532 
00533 /// copy additional attributes (those not needed to construct a GlobalValue)
00534 /// from the SrcGV to the DestGV.
00535 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
00536   DestGV->copyAttributesFrom(SrcGV);
00537   forceRenaming(DestGV, SrcGV->getName());
00538 }
00539 
00540 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
00541                                GlobalValue::VisibilityTypes b) {
00542   if (a == GlobalValue::HiddenVisibility)
00543     return false;
00544   if (b == GlobalValue::HiddenVisibility)
00545     return true;
00546   if (a == GlobalValue::ProtectedVisibility)
00547     return false;
00548   if (b == GlobalValue::ProtectedVisibility)
00549     return true;
00550   return false;
00551 }
00552 
00553 /// Loop through the global variables in the src module and merge them into the
00554 /// dest module.
00555 static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM,
00556                                                const GlobalVariable *SGVar) {
00557   // No linking to be performed or linking from the source: simply create an
00558   // identical version of the symbol over in the dest module... the
00559   // initializer will be filled in later by LinkGlobalInits.
00560   GlobalVariable *NewDGV = new GlobalVariable(
00561       DstM, TypeMap.get(SGVar->getType()->getElementType()),
00562       SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
00563       SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
00564       SGVar->getType()->getAddressSpace());
00565 
00566   return NewDGV;
00567 }
00568 
00569 /// Link the function in the source module into the destination module if
00570 /// needed, setting up mapping information.
00571 static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM,
00572                                    const Function *SF) {
00573   // If there is no linkage to be performed or we are linking from the source,
00574   // bring SF over.
00575   return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
00576                           SF->getName(), &DstM);
00577 }
00578 
00579 /// Set up prototypes for any aliases that come over from the source module.
00580 static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM,
00581                                          const GlobalAlias *SGA) {
00582   // If there is no linkage to be performed or we're linking from the source,
00583   // bring over SGA.
00584   auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
00585   return GlobalAlias::create(PTy, SGA->getLinkage(), SGA->getName(), &DstM);
00586 }
00587 
00588 static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM,
00589                                          const GlobalValue *SGV) {
00590   GlobalValue *NewGV;
00591   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
00592     NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar);
00593   else if (auto *SF = dyn_cast<Function>(SGV))
00594     NewGV = copyFunctionProto(TypeMap, DstM, SF);
00595   else
00596     NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV));
00597   copyGVAttributes(NewGV, SGV);
00598   return NewGV;
00599 }
00600 
00601 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
00602   auto *SGV = dyn_cast<GlobalValue>(V);
00603   if (!SGV)
00604     return nullptr;
00605 
00606   GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
00607 
00608   if (Comdat *SC = SGV->getComdat()) {
00609     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
00610       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
00611       DGO->setComdat(DC);
00612     }
00613   }
00614 
00615   LazilyLinkGlobalValues.push_back(SGV);
00616   return DGV;
00617 }
00618 
00619 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
00620                                    const GlobalVariable *&GVar) {
00621   const GlobalValue *GVal = M->getNamedValue(ComdatName);
00622   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
00623     GVal = GA->getBaseObject();
00624     if (!GVal)
00625       // We cannot resolve the size of the aliasee yet.
00626       return emitError("Linking COMDATs named '" + ComdatName +
00627                        "': COMDAT key involves incomputable alias size.");
00628   }
00629 
00630   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
00631   if (!GVar)
00632     return emitError(
00633         "Linking COMDATs named '" + ComdatName +
00634         "': GlobalVariable required for data dependent selection!");
00635 
00636   return false;
00637 }
00638 
00639 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
00640                                                  Comdat::SelectionKind Src,
00641                                                  Comdat::SelectionKind Dst,
00642                                                  Comdat::SelectionKind &Result,
00643                                                  bool &LinkFromSrc) {
00644   // The ability to mix Comdat::SelectionKind::Any with
00645   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
00646   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
00647                          Dst == Comdat::SelectionKind::Largest;
00648   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
00649                          Src == Comdat::SelectionKind::Largest;
00650   if (DstAnyOrLargest && SrcAnyOrLargest) {
00651     if (Dst == Comdat::SelectionKind::Largest ||
00652         Src == Comdat::SelectionKind::Largest)
00653       Result = Comdat::SelectionKind::Largest;
00654     else
00655       Result = Comdat::SelectionKind::Any;
00656   } else if (Src == Dst) {
00657     Result = Dst;
00658   } else {
00659     return emitError("Linking COMDATs named '" + ComdatName +
00660                      "': invalid selection kinds!");
00661   }
00662 
00663   switch (Result) {
00664   case Comdat::SelectionKind::Any:
00665     // Go with Dst.
00666     LinkFromSrc = false;
00667     break;
00668   case Comdat::SelectionKind::NoDuplicates:
00669     return emitError("Linking COMDATs named '" + ComdatName +
00670                      "': noduplicates has been violated!");
00671   case Comdat::SelectionKind::ExactMatch:
00672   case Comdat::SelectionKind::Largest:
00673   case Comdat::SelectionKind::SameSize: {
00674     const GlobalVariable *DstGV;
00675     const GlobalVariable *SrcGV;
00676     if (getComdatLeader(DstM, ComdatName, DstGV) ||
00677         getComdatLeader(SrcM, ComdatName, SrcGV))
00678       return true;
00679 
00680     const DataLayout &DstDL = DstM->getDataLayout();
00681     const DataLayout &SrcDL = SrcM->getDataLayout();
00682     uint64_t DstSize =
00683         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
00684     uint64_t SrcSize =
00685         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
00686     if (Result == Comdat::SelectionKind::ExactMatch) {
00687       if (SrcGV->getInitializer() != DstGV->getInitializer())
00688         return emitError("Linking COMDATs named '" + ComdatName +
00689                          "': ExactMatch violated!");
00690       LinkFromSrc = false;
00691     } else if (Result == Comdat::SelectionKind::Largest) {
00692       LinkFromSrc = SrcSize > DstSize;
00693     } else if (Result == Comdat::SelectionKind::SameSize) {
00694       if (SrcSize != DstSize)
00695         return emitError("Linking COMDATs named '" + ComdatName +
00696                          "': SameSize violated!");
00697       LinkFromSrc = false;
00698     } else {
00699       llvm_unreachable("unknown selection kind");
00700     }
00701     break;
00702   }
00703   }
00704 
00705   return false;
00706 }
00707 
00708 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
00709                                    Comdat::SelectionKind &Result,
00710                                    bool &LinkFromSrc) {
00711   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
00712   StringRef ComdatName = SrcC->getName();
00713   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
00714   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
00715 
00716   if (DstCI == ComdatSymTab.end()) {
00717     // Use the comdat if it is only available in one of the modules.
00718     LinkFromSrc = true;
00719     Result = SSK;
00720     return false;
00721   }
00722 
00723   const Comdat *DstC = &DstCI->second;
00724   Comdat::SelectionKind DSK = DstC->getSelectionKind();
00725   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
00726                                        LinkFromSrc);
00727 }
00728 
00729 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
00730                                         const GlobalValue &Dest,
00731                                         const GlobalValue &Src) {
00732   // Should we unconditionally use the Src?
00733   if (OverrideFromSrc) {
00734     LinkFromSrc = true;
00735     return false;
00736   }
00737 
00738   // We always have to add Src if it has appending linkage.
00739   if (Src.hasAppendingLinkage()) {
00740     LinkFromSrc = true;
00741     return false;
00742   }
00743 
00744   bool SrcIsDeclaration = Src.isDeclarationForLinker();
00745   bool DestIsDeclaration = Dest.isDeclarationForLinker();
00746 
00747   if (SrcIsDeclaration) {
00748     // If Src is external or if both Src & Dest are external..  Just link the
00749     // external globals, we aren't adding anything.
00750     if (Src.hasDLLImportStorageClass()) {
00751       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
00752       LinkFromSrc = DestIsDeclaration;
00753       return false;
00754     }
00755     // If the Dest is weak, use the source linkage.
00756     LinkFromSrc = Dest.hasExternalWeakLinkage();
00757     return false;
00758   }
00759 
00760   if (DestIsDeclaration) {
00761     // If Dest is external but Src is not:
00762     LinkFromSrc = true;
00763     return false;
00764   }
00765 
00766   if (Src.hasCommonLinkage()) {
00767     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
00768       LinkFromSrc = true;
00769       return false;
00770     }
00771 
00772     if (!Dest.hasCommonLinkage()) {
00773       LinkFromSrc = false;
00774       return false;
00775     }
00776 
00777     const DataLayout &DL = Dest.getParent()->getDataLayout();
00778     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
00779     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
00780     LinkFromSrc = SrcSize > DestSize;
00781     return false;
00782   }
00783 
00784   if (Src.isWeakForLinker()) {
00785     assert(!Dest.hasExternalWeakLinkage());
00786     assert(!Dest.hasAvailableExternallyLinkage());
00787 
00788     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
00789       LinkFromSrc = true;
00790       return false;
00791     }
00792 
00793     LinkFromSrc = false;
00794     return false;
00795   }
00796 
00797   if (Dest.isWeakForLinker()) {
00798     assert(Src.hasExternalLinkage());
00799     LinkFromSrc = true;
00800     return false;
00801   }
00802 
00803   assert(!Src.hasExternalWeakLinkage());
00804   assert(!Dest.hasExternalWeakLinkage());
00805   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
00806          "Unexpected linkage type!");
00807   return emitError("Linking globals named '" + Src.getName() +
00808                    "': symbol multiply defined!");
00809 }
00810 
00811 /// Loop over all of the linked values to compute type mappings.  For example,
00812 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
00813 /// types 'Foo' but one got renamed when the module was loaded into the same
00814 /// LLVMContext.
00815 void ModuleLinker::computeTypeMapping() {
00816   for (GlobalValue &SGV : SrcM->globals()) {
00817     GlobalValue *DGV = getLinkedToGlobal(&SGV);
00818     if (!DGV)
00819       continue;
00820 
00821     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
00822       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00823       continue;
00824     }
00825 
00826     // Unify the element type of appending arrays.
00827     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
00828     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
00829     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
00830   }
00831 
00832   for (GlobalValue &SGV : *SrcM) {
00833     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
00834       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00835   }
00836 
00837   for (GlobalValue &SGV : SrcM->aliases()) {
00838     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
00839       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
00840   }
00841 
00842   // Incorporate types by name, scanning all the types in the source module.
00843   // At this point, the destination module may have a type "%foo = { i32 }" for
00844   // example.  When the source module got loaded into the same LLVMContext, if
00845   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
00846   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
00847   for (StructType *ST : Types) {
00848     if (!ST->hasName())
00849       continue;
00850 
00851     // Check to see if there is a dot in the name followed by a digit.
00852     size_t DotPos = ST->getName().rfind('.');
00853     if (DotPos == 0 || DotPos == StringRef::npos ||
00854         ST->getName().back() == '.' ||
00855         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
00856       continue;
00857 
00858     // Check to see if the destination module has a struct with the prefix name.
00859     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
00860     if (!DST)
00861       continue;
00862 
00863     // Don't use it if this actually came from the source module. They're in
00864     // the same LLVMContext after all. Also don't use it unless the type is
00865     // actually used in the destination module. This can happen in situations
00866     // like this:
00867     //
00868     //      Module A                         Module B
00869     //      --------                         --------
00870     //   %Z = type { %A }                %B = type { %C.1 }
00871     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
00872     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
00873     //   %C = type { i8* }               %B.3 = type { %C.1 }
00874     //
00875     // When we link Module B with Module A, the '%B' in Module B is
00876     // used. However, that would then use '%C.1'. But when we process '%C.1',
00877     // we prefer to take the '%C' version. So we are then left with both
00878     // '%C.1' and '%C' being used for the same types. This leads to some
00879     // variables using one type and some using the other.
00880     if (TypeMap.DstStructTypesSet.hasType(DST))
00881       TypeMap.addTypeMapping(DST, ST);
00882   }
00883 
00884   // Now that we have discovered all of the type equivalences, get a body for
00885   // any 'opaque' types in the dest module that are now resolved.
00886   TypeMap.linkDefinedTypeBodies();
00887 }
00888 
00889 static void upgradeGlobalArray(GlobalVariable *GV) {
00890   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
00891   StructType *OldTy = cast<StructType>(ATy->getElementType());
00892   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
00893 
00894   // Get the upgraded 3 element type.
00895   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
00896   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
00897                   VoidPtrTy};
00898   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
00899 
00900   // Build new constants with a null third field filled in.
00901   Constant *OldInitC = GV->getInitializer();
00902   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
00903   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
00904     // Invalid initializer; give up.
00905     return;
00906   std::vector<Constant *> Initializers;
00907   if (OldInit && OldInit->getNumOperands()) {
00908     Value *Null = Constant::getNullValue(VoidPtrTy);
00909     for (Use &U : OldInit->operands()) {
00910       ConstantStruct *Init = cast<ConstantStruct>(U.get());
00911       Initializers.push_back(ConstantStruct::get(
00912           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
00913     }
00914   }
00915   assert(Initializers.size() == ATy->getNumElements() &&
00916          "Failed to copy all array elements");
00917 
00918   // Replace the old GV with a new one.
00919   ATy = ArrayType::get(NewTy, Initializers.size());
00920   Constant *NewInit = ConstantArray::get(ATy, Initializers);
00921   GlobalVariable *NewGV = new GlobalVariable(
00922       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
00923       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
00924       GV->isExternallyInitialized());
00925   NewGV->copyAttributesFrom(GV);
00926   NewGV->takeName(GV);
00927   assert(GV->use_empty() && "program cannot use initializer list");
00928   GV->eraseFromParent();
00929 }
00930 
00931 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
00932   // Look for the global arrays.
00933   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
00934   if (!DstGV)
00935     return;
00936   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
00937   if (!SrcGV)
00938     return;
00939 
00940   // Check if the types already match.
00941   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00942   auto *SrcTy =
00943       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00944   if (DstTy == SrcTy)
00945     return;
00946 
00947   // Grab the element types.  We can only upgrade an array of a two-field
00948   // struct.  Only bother if the other one has three-fields.
00949   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
00950   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
00951   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
00952     upgradeGlobalArray(DstGV);
00953     return;
00954   }
00955   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
00956     upgradeGlobalArray(SrcGV);
00957 
00958   // We can't upgrade any other differences.
00959 }
00960 
00961 void ModuleLinker::upgradeMismatchedGlobals() {
00962   upgradeMismatchedGlobalArray("llvm.global_ctors");
00963   upgradeMismatchedGlobalArray("llvm.global_dtors");
00964 }
00965 
00966 /// If there were any appending global variables, link them together now.
00967 /// Return true on error.
00968 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
00969                                          const GlobalVariable *SrcGV) {
00970 
00971   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
00972     return emitError("Linking globals named '" + SrcGV->getName() +
00973            "': can only link appending global with another appending global!");
00974 
00975   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
00976   ArrayType *SrcTy =
00977     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
00978   Type *EltTy = DstTy->getElementType();
00979 
00980   // Check to see that they two arrays agree on type.
00981   if (EltTy != SrcTy->getElementType())
00982     return emitError("Appending variables with different element types!");
00983   if (DstGV->isConstant() != SrcGV->isConstant())
00984     return emitError("Appending variables linked with different const'ness!");
00985 
00986   if (DstGV->getAlignment() != SrcGV->getAlignment())
00987     return emitError(
00988              "Appending variables with different alignment need to be linked!");
00989 
00990   if (DstGV->getVisibility() != SrcGV->getVisibility())
00991     return emitError(
00992             "Appending variables with different visibility need to be linked!");
00993 
00994   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
00995     return emitError(
00996         "Appending variables with different unnamed_addr need to be linked!");
00997 
00998   if (StringRef(DstGV->getSection()) != SrcGV->getSection())
00999     return emitError(
01000           "Appending variables with different section name need to be linked!");
01001 
01002   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
01003   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
01004 
01005   // Create the new global variable.
01006   GlobalVariable *NG =
01007     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
01008                        DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
01009                        DstGV->getThreadLocalMode(),
01010                        DstGV->getType()->getAddressSpace());
01011 
01012   // Propagate alignment, visibility and section info.
01013   copyGVAttributes(NG, DstGV);
01014 
01015   AppendingVarInfo AVI;
01016   AVI.NewGV = NG;
01017   AVI.DstInit = DstGV->getInitializer();
01018   AVI.SrcInit = SrcGV->getInitializer();
01019   AppendingVars.push_back(AVI);
01020 
01021   // Replace any uses of the two global variables with uses of the new
01022   // global.
01023   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
01024 
01025   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
01026   DstGV->eraseFromParent();
01027 
01028   // Track the source variable so we don't try to link it.
01029   DoNotLinkFromSource.insert(SrcGV);
01030 
01031   return false;
01032 }
01033 
01034 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
01035   GlobalValue *DGV = getLinkedToGlobal(SGV);
01036 
01037   // Handle the ultra special appending linkage case first.
01038   if (DGV && DGV->hasAppendingLinkage())
01039     return linkAppendingVarProto(cast<GlobalVariable>(DGV),
01040                                  cast<GlobalVariable>(SGV));
01041 
01042   bool LinkFromSrc = true;
01043   Comdat *C = nullptr;
01044   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
01045   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
01046 
01047   if (const Comdat *SC = SGV->getComdat()) {
01048     Comdat::SelectionKind SK;
01049     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
01050     C = DstM->getOrInsertComdat(SC->getName());
01051     C->setSelectionKind(SK);
01052   } else if (DGV) {
01053     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
01054       return true;
01055   }
01056 
01057   if (!LinkFromSrc) {
01058     // Track the source global so that we don't attempt to copy it over when
01059     // processing global initializers.
01060     DoNotLinkFromSource.insert(SGV);
01061 
01062     if (DGV)
01063       // Make sure to remember this mapping.
01064       ValueMap[SGV] =
01065           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
01066   }
01067 
01068   if (DGV) {
01069     Visibility = isLessConstraining(Visibility, DGV->getVisibility())
01070                      ? DGV->getVisibility()
01071                      : Visibility;
01072     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
01073   }
01074 
01075   if (!LinkFromSrc && !DGV)
01076     return false;
01077 
01078   GlobalValue *NewGV;
01079   if (!LinkFromSrc) {
01080     NewGV = DGV;
01081   } else {
01082     // If the GV is to be lazily linked, don't create it just yet.
01083     // The ValueMaterializerTy will deal with creating it if it's used.
01084     if (!DGV && !OverrideFromSrc &&
01085         (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
01086          SGV->hasAvailableExternallyLinkage())) {
01087       DoNotLinkFromSource.insert(SGV);
01088       return false;
01089     }
01090 
01091     NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV);
01092 
01093     if (DGV && isa<Function>(DGV))
01094       if (auto *NewF = dyn_cast<Function>(NewGV))
01095         OverridingFunctions.insert(NewF);
01096   }
01097 
01098   NewGV->setUnnamedAddr(HasUnnamedAddr);
01099   NewGV->setVisibility(Visibility);
01100 
01101   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
01102     if (C)
01103       NewGO->setComdat(C);
01104 
01105     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
01106       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
01107   }
01108 
01109   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
01110     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
01111     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
01112     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
01113         (!DGVar->isConstant() || !SGVar->isConstant()))
01114       NewGVar->setConstant(false);
01115   }
01116 
01117   // Make sure to remember this mapping.
01118   if (NewGV != DGV) {
01119     if (DGV) {
01120       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
01121       DGV->eraseFromParent();
01122     }
01123     ValueMap[SGV] = NewGV;
01124   }
01125 
01126   return false;
01127 }
01128 
01129 static void getArrayElements(const Constant *C,
01130                              SmallVectorImpl<Constant *> &Dest) {
01131   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
01132 
01133   for (unsigned i = 0; i != NumElements; ++i)
01134     Dest.push_back(C->getAggregateElement(i));
01135 }
01136 
01137 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
01138   // Merge the initializer.
01139   SmallVector<Constant *, 16> DstElements;
01140   getArrayElements(AVI.DstInit, DstElements);
01141 
01142   SmallVector<Constant *, 16> SrcElements;
01143   getArrayElements(AVI.SrcInit, SrcElements);
01144 
01145   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
01146 
01147   StringRef Name = AVI.NewGV->getName();
01148   bool IsNewStructor =
01149       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
01150       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
01151 
01152   for (auto *V : SrcElements) {
01153     if (IsNewStructor) {
01154       Constant *Key = V->getAggregateElement(2);
01155       if (DoNotLinkFromSource.count(Key))
01156         continue;
01157     }
01158     DstElements.push_back(
01159         MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
01160   }
01161   if (IsNewStructor) {
01162     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
01163     AVI.NewGV->mutateType(PointerType::get(NewType, 0));
01164   }
01165 
01166   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
01167 }
01168 
01169 /// Update the initializers in the Dest module now that all globals that may be
01170 /// referenced are in Dest.
01171 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
01172   // Figure out what the initializer looks like in the dest module.
01173   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap,
01174                               &ValMaterializer));
01175 }
01176 
01177 /// Copy the source function over into the dest function and fix up references
01178 /// to values. At this point we know that Dest is an external function, and
01179 /// that Src is not.
01180 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
01181   assert(Dst.isDeclaration() && !Src.isDeclaration());
01182 
01183   // Materialize if needed.
01184   if (std::error_code EC = Src.materialize())
01185     return emitError(EC.message());
01186 
01187   // Link in the prefix data.
01188   if (Src.hasPrefixData())
01189     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap,
01190                                &ValMaterializer));
01191 
01192   // Link in the prologue data.
01193   if (Src.hasPrologueData())
01194     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None,
01195                                  &TypeMap, &ValMaterializer));
01196 
01197   // Link in the personality function.
01198   if (Src.hasPersonalityFn())
01199     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap, RF_None,
01200                                   &TypeMap, &ValMaterializer));
01201 
01202   // Go through and convert function arguments over, remembering the mapping.
01203   Function::arg_iterator DI = Dst.arg_begin();
01204   for (Argument &Arg : Src.args()) {
01205     DI->setName(Arg.getName());  // Copy the name over.
01206 
01207     // Add a mapping to our mapping.
01208     ValueMap[&Arg] = DI;
01209     ++DI;
01210   }
01211 
01212   // Copy over the metadata attachments.
01213   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
01214   Src.getAllMetadata(MDs);
01215   for (const auto &I : MDs)
01216     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_None, &TypeMap,
01217                                          &ValMaterializer));
01218 
01219   // Splice the body of the source function into the dest function.
01220   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
01221 
01222   // At this point, all of the instructions and values of the function are now
01223   // copied over.  The only problem is that they are still referencing values in
01224   // the Source function as operands.  Loop through all of the operands of the
01225   // functions and patch them up to point to the local versions.
01226   for (BasicBlock &BB : Dst)
01227     for (Instruction &I : BB)
01228       RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
01229                        &ValMaterializer);
01230 
01231   // There is no need to map the arguments anymore.
01232   for (Argument &Arg : Src.args())
01233     ValueMap.erase(&Arg);
01234 
01235   Src.dematerialize();
01236   return false;
01237 }
01238 
01239 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
01240   Constant *Aliasee = Src.getAliasee();
01241   Constant *Val =
01242       MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01243   Dst.setAliasee(Val);
01244 }
01245 
01246 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
01247   Value *Dst = ValueMap[&Src];
01248   assert(Dst);
01249   if (auto *F = dyn_cast<Function>(&Src))
01250     return linkFunctionBody(cast<Function>(*Dst), *F);
01251   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
01252     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
01253     return false;
01254   }
01255   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
01256   return false;
01257 }
01258 
01259 /// Insert all of the named MDNodes in Src into the Dest module.
01260 void ModuleLinker::linkNamedMDNodes() {
01261   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01262   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
01263     // Don't link module flags here. Do them separately.
01264     if (&NMD == SrcModFlags)
01265       continue;
01266     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
01267     // Add Src elements into Dest node.
01268     for (const MDNode *op : NMD.operands())
01269       DestNMD->addOperand(
01270           MapMetadata(op, ValueMap, RF_None, &TypeMap, &ValMaterializer));
01271   }
01272 }
01273 
01274 /// Drop DISubprograms that have been superseded.
01275 ///
01276 /// FIXME: this creates an asymmetric result: we strip functions from losing
01277 /// subprograms in DstM, but leave losing subprograms in SrcM.
01278 /// TODO: Remove this logic once the backend can correctly determine canonical
01279 /// subprograms.
01280 void ModuleLinker::stripReplacedSubprograms() {
01281   // Avoid quadratic runtime by returning early when there's nothing to do.
01282   if (OverridingFunctions.empty())
01283     return;
01284 
01285   // Move the functions now, so the set gets cleared even on early returns.
01286   auto Functions = std::move(OverridingFunctions);
01287   OverridingFunctions.clear();
01288 
01289   // Drop functions from subprograms if they've been overridden by the new
01290   // compile unit.
01291   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
01292   if (!CompileUnits)
01293     return;
01294   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
01295     auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
01296     assert(CU && "Expected valid compile unit");
01297 
01298     for (DISubprogram *SP : CU->getSubprograms()) {
01299       if (!SP || !SP->getFunction() || !Functions.count(SP->getFunction()))
01300         continue;
01301 
01302       // Prevent DebugInfoFinder from tagging this as the canonical subprogram,
01303       // since the canonical one is in the incoming module.
01304       SP->replaceFunction(nullptr);
01305     }
01306   }
01307 }
01308 
01309 /// Merge the linker flags in Src into the Dest module.
01310 bool ModuleLinker::linkModuleFlagsMetadata() {
01311   // If the source module has no module flags, we are done.
01312   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01313   if (!SrcModFlags) return false;
01314 
01315   // If the destination module doesn't have module flags yet, then just copy
01316   // over the source module's flags.
01317   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
01318   if (DstModFlags->getNumOperands() == 0) {
01319     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
01320       DstModFlags->addOperand(SrcModFlags->getOperand(I));
01321 
01322     return false;
01323   }
01324 
01325   // First build a map of the existing module flags and requirements.
01326   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
01327   SmallSetVector<MDNode*, 16> Requirements;
01328   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
01329     MDNode *Op = DstModFlags->getOperand(I);
01330     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
01331     MDString *ID = cast<MDString>(Op->getOperand(1));
01332 
01333     if (Behavior->getZExtValue() == Module::Require) {
01334       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
01335     } else {
01336       Flags[ID] = std::make_pair(Op, I);
01337     }
01338   }
01339 
01340   // Merge in the flags from the source module, and also collect its set of
01341   // requirements.
01342   bool HasErr = false;
01343   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
01344     MDNode *SrcOp = SrcModFlags->getOperand(I);
01345     ConstantInt *SrcBehavior =
01346         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
01347     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
01348     MDNode *DstOp;
01349     unsigned DstIndex;
01350     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
01351     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
01352 
01353     // If this is a requirement, add it and continue.
01354     if (SrcBehaviorValue == Module::Require) {
01355       // If the destination module does not already have this requirement, add
01356       // it.
01357       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
01358         DstModFlags->addOperand(SrcOp);
01359       }
01360       continue;
01361     }
01362 
01363     // If there is no existing flag with this ID, just add it.
01364     if (!DstOp) {
01365       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
01366       DstModFlags->addOperand(SrcOp);
01367       continue;
01368     }
01369 
01370     // Otherwise, perform a merge.
01371     ConstantInt *DstBehavior =
01372         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
01373     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
01374 
01375     // If either flag has override behavior, handle it first.
01376     if (DstBehaviorValue == Module::Override) {
01377       // Diagnose inconsistent flags which both have override behavior.
01378       if (SrcBehaviorValue == Module::Override &&
01379           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01380         HasErr |= emitError("linking module flags '" + ID->getString() +
01381                             "': IDs have conflicting override values");
01382       }
01383       continue;
01384     } else if (SrcBehaviorValue == Module::Override) {
01385       // Update the destination flag to that of the source.
01386       DstModFlags->setOperand(DstIndex, SrcOp);
01387       Flags[ID].first = SrcOp;
01388       continue;
01389     }
01390 
01391     // Diagnose inconsistent merge behavior types.
01392     if (SrcBehaviorValue != DstBehaviorValue) {
01393       HasErr |= emitError("linking module flags '" + ID->getString() +
01394                           "': IDs have conflicting behaviors");
01395       continue;
01396     }
01397 
01398     auto replaceDstValue = [&](MDNode *New) {
01399       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
01400       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
01401       DstModFlags->setOperand(DstIndex, Flag);
01402       Flags[ID].first = Flag;
01403     };
01404 
01405     // Perform the merge for standard behavior types.
01406     switch (SrcBehaviorValue) {
01407     case Module::Require:
01408     case Module::Override: llvm_unreachable("not possible");
01409     case Module::Error: {
01410       // Emit an error if the values differ.
01411       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01412         HasErr |= emitError("linking module flags '" + ID->getString() +
01413                             "': IDs have conflicting values");
01414       }
01415       continue;
01416     }
01417     case Module::Warning: {
01418       // Emit a warning if the values differ.
01419       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01420         emitWarning("linking module flags '" + ID->getString() +
01421                     "': IDs have conflicting values");
01422       }
01423       continue;
01424     }
01425     case Module::Append: {
01426       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01427       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01428       SmallVector<Metadata *, 8> MDs;
01429       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
01430       MDs.append(DstValue->op_begin(), DstValue->op_end());
01431       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
01432 
01433       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
01434       break;
01435     }
01436     case Module::AppendUnique: {
01437       SmallSetVector<Metadata *, 16> Elts;
01438       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01439       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01440       Elts.insert(DstValue->op_begin(), DstValue->op_end());
01441       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
01442 
01443       replaceDstValue(MDNode::get(DstM->getContext(),
01444                                   makeArrayRef(Elts.begin(), Elts.end())));
01445       break;
01446     }
01447     }
01448   }
01449 
01450   // Check all of the requirements.
01451   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
01452     MDNode *Requirement = Requirements[I];
01453     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
01454     Metadata *ReqValue = Requirement->getOperand(1);
01455 
01456     MDNode *Op = Flags[Flag].first;
01457     if (!Op || Op->getOperand(2) != ReqValue) {
01458       HasErr |= emitError("linking module flags '" + Flag->getString() +
01459                           "': does not have the required value");
01460       continue;
01461     }
01462   }
01463 
01464   return HasErr;
01465 }
01466 
01467 // This function returns true if the triples match.
01468 static bool triplesMatch(const Triple &T0, const Triple &T1) {
01469   // If vendor is apple, ignore the version number.
01470   if (T0.getVendor() == Triple::Apple)
01471     return T0.getArch() == T1.getArch() &&
01472            T0.getSubArch() == T1.getSubArch() &&
01473            T0.getVendor() == T1.getVendor() &&
01474            T0.getOS() == T1.getOS();
01475 
01476   return T0 == T1;
01477 }
01478 
01479 // This function returns the merged triple.
01480 static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
01481   // If vendor is apple, pick the triple with the larger version number.
01482   if (SrcTriple.getVendor() == Triple::Apple)
01483     if (DstTriple.isOSVersionLT(SrcTriple))
01484       return SrcTriple.str();
01485 
01486   return DstTriple.str();
01487 }
01488 
01489 bool ModuleLinker::run() {
01490   assert(DstM && "Null destination module");
01491   assert(SrcM && "Null source module");
01492 
01493   // Inherit the target data from the source module if the destination module
01494   // doesn't have one already.
01495   if (DstM->getDataLayout().isDefault())
01496     DstM->setDataLayout(SrcM->getDataLayout());
01497 
01498   if (SrcM->getDataLayout() != DstM->getDataLayout()) {
01499     emitWarning("Linking two modules of different data layouts: '" +
01500                 SrcM->getModuleIdentifier() + "' is '" +
01501                 SrcM->getDataLayoutStr() + "' whereas '" +
01502                 DstM->getModuleIdentifier() + "' is '" +
01503                 DstM->getDataLayoutStr() + "'\n");
01504   }
01505 
01506   // Copy the target triple from the source to dest if the dest's is empty.
01507   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
01508     DstM->setTargetTriple(SrcM->getTargetTriple());
01509 
01510   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
01511 
01512   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
01513     emitWarning("Linking two modules of different target triples: " +
01514                 SrcM->getModuleIdentifier() + "' is '" +
01515                 SrcM->getTargetTriple() + "' whereas '" +
01516                 DstM->getModuleIdentifier() + "' is '" +
01517                 DstM->getTargetTriple() + "'\n");
01518 
01519   DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
01520 
01521   // Append the module inline asm string.
01522   if (!SrcM->getModuleInlineAsm().empty()) {
01523     if (DstM->getModuleInlineAsm().empty())
01524       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
01525     else
01526       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
01527                                SrcM->getModuleInlineAsm());
01528   }
01529 
01530   // Loop over all of the linked values to compute type mappings.
01531   computeTypeMapping();
01532 
01533   ComdatsChosen.clear();
01534   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
01535     const Comdat &C = SMEC.getValue();
01536     if (ComdatsChosen.count(&C))
01537       continue;
01538     Comdat::SelectionKind SK;
01539     bool LinkFromSrc;
01540     if (getComdatResult(&C, SK, LinkFromSrc))
01541       return true;
01542     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
01543   }
01544 
01545   // Upgrade mismatched global arrays.
01546   upgradeMismatchedGlobals();
01547 
01548   // Insert all of the globals in src into the DstM module... without linking
01549   // initializers (which could refer to functions not yet mapped over).
01550   for (GlobalVariable &GV : SrcM->globals())
01551     if (linkGlobalValueProto(&GV))
01552       return true;
01553 
01554   // Link the functions together between the two modules, without doing function
01555   // bodies... this just adds external function prototypes to the DstM
01556   // function...  We do this so that when we begin processing function bodies,
01557   // all of the global values that may be referenced are available in our
01558   // ValueMap.
01559   for (Function &F :*SrcM)
01560     if (linkGlobalValueProto(&F))
01561       return true;
01562 
01563   // If there were any aliases, link them now.
01564   for (GlobalAlias &GA : SrcM->aliases())
01565     if (linkGlobalValueProto(&GA))
01566       return true;
01567 
01568   for (const AppendingVarInfo &AppendingVar : AppendingVars)
01569     linkAppendingVarInit(AppendingVar);
01570 
01571   for (const auto &Entry : DstM->getComdatSymbolTable()) {
01572     const Comdat &C = Entry.getValue();
01573     if (C.getSelectionKind() == Comdat::Any)
01574       continue;
01575     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
01576     if (GV)
01577       MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01578   }
01579 
01580   // Strip replaced subprograms before mapping any metadata -- so that we're
01581   // not changing metadata from the source module (note that
01582   // linkGlobalValueBody() eventually calls RemapInstruction() and therefore
01583   // MapMetadata()) -- but after linking global value protocols -- so that
01584   // OverridingFunctions has been built.
01585   stripReplacedSubprograms();
01586 
01587   // Link in the function bodies that are defined in the source module into
01588   // DstM.
01589   for (Function &SF : *SrcM) {
01590     // Skip if no body (function is external).
01591     if (SF.isDeclaration())
01592       continue;
01593 
01594     // Skip if not linking from source.
01595     if (DoNotLinkFromSource.count(&SF))
01596       continue;
01597 
01598     if (linkGlobalValueBody(SF))
01599       return true;
01600   }
01601 
01602   // Resolve all uses of aliases with aliasees.
01603   for (GlobalAlias &Src : SrcM->aliases()) {
01604     if (DoNotLinkFromSource.count(&Src))
01605       continue;
01606     linkGlobalValueBody(Src);
01607   }
01608 
01609   // Remap all of the named MDNodes in Src into the DstM module. We do this
01610   // after linking GlobalValues so that MDNodes that reference GlobalValues
01611   // are properly remapped.
01612   linkNamedMDNodes();
01613 
01614   // Merge the module flags into the DstM module.
01615   if (linkModuleFlagsMetadata())
01616     return true;
01617 
01618   // Update the initializers in the DstM module now that all globals that may
01619   // be referenced are in DstM.
01620   for (GlobalVariable &Src : SrcM->globals()) {
01621     // Only process initialized GV's or ones not already in dest.
01622     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
01623       continue;
01624     linkGlobalValueBody(Src);
01625   }
01626 
01627   // Process vector of lazily linked in functions.
01628   while (!LazilyLinkGlobalValues.empty()) {
01629     GlobalValue *SGV = LazilyLinkGlobalValues.back();
01630     LazilyLinkGlobalValues.pop_back();
01631 
01632     assert(!SGV->isDeclaration() && "users should not pass down decls");
01633     if (linkGlobalValueBody(*SGV))
01634       return true;
01635   }
01636 
01637   return false;
01638 }
01639 
01640 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
01641     : ETypes(E), IsPacked(P) {}
01642 
01643 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
01644     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
01645 
01646 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
01647   if (IsPacked != That.IsPacked)
01648     return false;
01649   if (ETypes != That.ETypes)
01650     return false;
01651   return true;
01652 }
01653 
01654 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
01655   return !this->operator==(That);
01656 }
01657 
01658 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
01659   return DenseMapInfo<StructType *>::getEmptyKey();
01660 }
01661 
01662 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
01663   return DenseMapInfo<StructType *>::getTombstoneKey();
01664 }
01665 
01666 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
01667   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
01668                       Key.IsPacked);
01669 }
01670 
01671 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
01672   return getHashValue(KeyTy(ST));
01673 }
01674 
01675 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
01676                                         const StructType *RHS) {
01677   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
01678     return false;
01679   return LHS == KeyTy(RHS);
01680 }
01681 
01682 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
01683                                         const StructType *RHS) {
01684   if (RHS == getEmptyKey())
01685     return LHS == getEmptyKey();
01686 
01687   if (RHS == getTombstoneKey())
01688     return LHS == getTombstoneKey();
01689 
01690   return KeyTy(LHS) == KeyTy(RHS);
01691 }
01692 
01693 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
01694   assert(!Ty->isOpaque());
01695   NonOpaqueStructTypes.insert(Ty);
01696 }
01697 
01698 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
01699   assert(!Ty->isOpaque());
01700   NonOpaqueStructTypes.insert(Ty);
01701   bool Removed = OpaqueStructTypes.erase(Ty);
01702   (void)Removed;
01703   assert(Removed);
01704 }
01705 
01706 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
01707   assert(Ty->isOpaque());
01708   OpaqueStructTypes.insert(Ty);
01709 }
01710 
01711 StructType *
01712 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
01713                                                bool IsPacked) {
01714   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
01715   auto I = NonOpaqueStructTypes.find_as(Key);
01716   if (I == NonOpaqueStructTypes.end())
01717     return nullptr;
01718   return *I;
01719 }
01720 
01721 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
01722   if (Ty->isOpaque())
01723     return OpaqueStructTypes.count(Ty);
01724   auto I = NonOpaqueStructTypes.find(Ty);
01725   if (I == NonOpaqueStructTypes.end())
01726     return false;
01727   return *I == Ty;
01728 }
01729 
01730 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01731   this->Composite = M;
01732   this->DiagnosticHandler = DiagnosticHandler;
01733 
01734   TypeFinder StructTypes;
01735   StructTypes.run(*M, true);
01736   for (StructType *Ty : StructTypes) {
01737     if (Ty->isOpaque())
01738       IdentifiedStructTypes.addOpaque(Ty);
01739     else
01740       IdentifiedStructTypes.addNonOpaque(Ty);
01741   }
01742 }
01743 
01744 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01745   init(M, DiagnosticHandler);
01746 }
01747 
01748 Linker::Linker(Module *M) {
01749   init(M, [this](const DiagnosticInfo &DI) {
01750     Composite->getContext().diagnose(DI);
01751   });
01752 }
01753 
01754 Linker::~Linker() {
01755 }
01756 
01757 void Linker::deleteModule() {
01758   delete Composite;
01759   Composite = nullptr;
01760 }
01761 
01762 bool Linker::linkInModule(Module *Src, bool OverrideSymbols) {
01763   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
01764                          DiagnosticHandler, OverrideSymbols);
01765   bool RetCode = TheLinker.run();
01766   Composite->dropTriviallyDeadConstantArrays();
01767   return RetCode;
01768 }
01769 
01770 void Linker::setModule(Module *Dst) {
01771   init(Dst, DiagnosticHandler);
01772 }
01773 
01774 //===----------------------------------------------------------------------===//
01775 // LinkModules entrypoint.
01776 //===----------------------------------------------------------------------===//
01777 
01778 /// This function links two modules together, with the resulting Dest module
01779 /// modified to be the composite of the two input modules. If an error occurs,
01780 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
01781 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
01782 /// relied on to be consistent.
01783 bool Linker::LinkModules(Module *Dest, Module *Src,
01784                          DiagnosticHandlerFunction DiagnosticHandler) {
01785   Linker L(Dest, DiagnosticHandler);
01786   return L.linkInModule(Src);
01787 }
01788 
01789 bool Linker::LinkModules(Module *Dest, Module *Src) {
01790   Linker L(Dest);
01791   return L.linkInModule(Src);
01792 }
01793 
01794 //===----------------------------------------------------------------------===//
01795 // C API.
01796 //===----------------------------------------------------------------------===//
01797 
01798 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
01799                          LLVMLinkerMode Unused, char **OutMessages) {
01800   Module *D = unwrap(Dest);
01801   std::string Message;
01802   raw_string_ostream Stream(Message);
01803   DiagnosticPrinterRawOStream DP(Stream);
01804 
01805   LLVMBool Result = Linker::LinkModules(
01806       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
01807 
01808   if (OutMessages && Result) {
01809     Stream.flush();
01810     *OutMessages = strdup(Message.c_str());
01811   }
01812   return Result;
01813 }