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   // Go through and convert function arguments over, remembering the mapping.
01198   Function::arg_iterator DI = Dst.arg_begin();
01199   for (Argument &Arg : Src.args()) {
01200     DI->setName(Arg.getName());  // Copy the name over.
01201 
01202     // Add a mapping to our mapping.
01203     ValueMap[&Arg] = DI;
01204     ++DI;
01205   }
01206 
01207   // Copy over the metadata attachments.
01208   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
01209   Src.getAllMetadata(MDs);
01210   for (const auto &I : MDs)
01211     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_None, &TypeMap,
01212                                          &ValMaterializer));
01213 
01214   // Splice the body of the source function into the dest function.
01215   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
01216 
01217   // At this point, all of the instructions and values of the function are now
01218   // copied over.  The only problem is that they are still referencing values in
01219   // the Source function as operands.  Loop through all of the operands of the
01220   // functions and patch them up to point to the local versions.
01221   for (BasicBlock &BB : Dst)
01222     for (Instruction &I : BB)
01223       RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
01224                        &ValMaterializer);
01225 
01226   // There is no need to map the arguments anymore.
01227   for (Argument &Arg : Src.args())
01228     ValueMap.erase(&Arg);
01229 
01230   Src.Dematerialize();
01231   return false;
01232 }
01233 
01234 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
01235   Constant *Aliasee = Src.getAliasee();
01236   Constant *Val =
01237       MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01238   Dst.setAliasee(Val);
01239 }
01240 
01241 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
01242   Value *Dst = ValueMap[&Src];
01243   assert(Dst);
01244   if (auto *F = dyn_cast<Function>(&Src))
01245     return linkFunctionBody(cast<Function>(*Dst), *F);
01246   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
01247     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
01248     return false;
01249   }
01250   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
01251   return false;
01252 }
01253 
01254 /// Insert all of the named MDNodes in Src into the Dest module.
01255 void ModuleLinker::linkNamedMDNodes() {
01256   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01257   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
01258        E = SrcM->named_metadata_end(); I != E; ++I) {
01259     // Don't link module flags here. Do them separately.
01260     if (&*I == SrcModFlags) continue;
01261     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
01262     // Add Src elements into Dest node.
01263     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01264       DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None,
01265                                       &TypeMap, &ValMaterializer));
01266   }
01267 }
01268 
01269 /// Drop DISubprograms that have been superseded.
01270 ///
01271 /// FIXME: this creates an asymmetric result: we strip functions from losing
01272 /// subprograms in DstM, but leave losing subprograms in SrcM.
01273 /// TODO: Remove this logic once the backend can correctly determine canonical
01274 /// subprograms.
01275 void ModuleLinker::stripReplacedSubprograms() {
01276   // Avoid quadratic runtime by returning early when there's nothing to do.
01277   if (OverridingFunctions.empty())
01278     return;
01279 
01280   // Move the functions now, so the set gets cleared even on early returns.
01281   auto Functions = std::move(OverridingFunctions);
01282   OverridingFunctions.clear();
01283 
01284   // Drop functions from subprograms if they've been overridden by the new
01285   // compile unit.
01286   NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu");
01287   if (!CompileUnits)
01288     return;
01289   for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
01290     auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
01291     assert(CU && "Expected valid compile unit");
01292 
01293     for (DISubprogram *SP : CU->getSubprograms()) {
01294       if (!SP || !SP->getFunction() || !Functions.count(SP->getFunction()))
01295         continue;
01296 
01297       // Prevent DebugInfoFinder from tagging this as the canonical subprogram,
01298       // since the canonical one is in the incoming module.
01299       SP->replaceFunction(nullptr);
01300     }
01301   }
01302 }
01303 
01304 /// Merge the linker flags in Src into the Dest module.
01305 bool ModuleLinker::linkModuleFlagsMetadata() {
01306   // If the source module has no module flags, we are done.
01307   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
01308   if (!SrcModFlags) return false;
01309 
01310   // If the destination module doesn't have module flags yet, then just copy
01311   // over the source module's flags.
01312   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
01313   if (DstModFlags->getNumOperands() == 0) {
01314     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
01315       DstModFlags->addOperand(SrcModFlags->getOperand(I));
01316 
01317     return false;
01318   }
01319 
01320   // First build a map of the existing module flags and requirements.
01321   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
01322   SmallSetVector<MDNode*, 16> Requirements;
01323   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
01324     MDNode *Op = DstModFlags->getOperand(I);
01325     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
01326     MDString *ID = cast<MDString>(Op->getOperand(1));
01327 
01328     if (Behavior->getZExtValue() == Module::Require) {
01329       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
01330     } else {
01331       Flags[ID] = std::make_pair(Op, I);
01332     }
01333   }
01334 
01335   // Merge in the flags from the source module, and also collect its set of
01336   // requirements.
01337   bool HasErr = false;
01338   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
01339     MDNode *SrcOp = SrcModFlags->getOperand(I);
01340     ConstantInt *SrcBehavior =
01341         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
01342     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
01343     MDNode *DstOp;
01344     unsigned DstIndex;
01345     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
01346     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
01347 
01348     // If this is a requirement, add it and continue.
01349     if (SrcBehaviorValue == Module::Require) {
01350       // If the destination module does not already have this requirement, add
01351       // it.
01352       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
01353         DstModFlags->addOperand(SrcOp);
01354       }
01355       continue;
01356     }
01357 
01358     // If there is no existing flag with this ID, just add it.
01359     if (!DstOp) {
01360       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
01361       DstModFlags->addOperand(SrcOp);
01362       continue;
01363     }
01364 
01365     // Otherwise, perform a merge.
01366     ConstantInt *DstBehavior =
01367         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
01368     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
01369 
01370     // If either flag has override behavior, handle it first.
01371     if (DstBehaviorValue == Module::Override) {
01372       // Diagnose inconsistent flags which both have override behavior.
01373       if (SrcBehaviorValue == Module::Override &&
01374           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01375         HasErr |= emitError("linking module flags '" + ID->getString() +
01376                             "': IDs have conflicting override values");
01377       }
01378       continue;
01379     } else if (SrcBehaviorValue == Module::Override) {
01380       // Update the destination flag to that of the source.
01381       DstModFlags->setOperand(DstIndex, SrcOp);
01382       Flags[ID].first = SrcOp;
01383       continue;
01384     }
01385 
01386     // Diagnose inconsistent merge behavior types.
01387     if (SrcBehaviorValue != DstBehaviorValue) {
01388       HasErr |= emitError("linking module flags '" + ID->getString() +
01389                           "': IDs have conflicting behaviors");
01390       continue;
01391     }
01392 
01393     auto replaceDstValue = [&](MDNode *New) {
01394       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
01395       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
01396       DstModFlags->setOperand(DstIndex, Flag);
01397       Flags[ID].first = Flag;
01398     };
01399 
01400     // Perform the merge for standard behavior types.
01401     switch (SrcBehaviorValue) {
01402     case Module::Require:
01403     case Module::Override: llvm_unreachable("not possible");
01404     case Module::Error: {
01405       // Emit an error if the values differ.
01406       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01407         HasErr |= emitError("linking module flags '" + ID->getString() +
01408                             "': IDs have conflicting values");
01409       }
01410       continue;
01411     }
01412     case Module::Warning: {
01413       // Emit a warning if the values differ.
01414       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
01415         emitWarning("linking module flags '" + ID->getString() +
01416                     "': IDs have conflicting values");
01417       }
01418       continue;
01419     }
01420     case Module::Append: {
01421       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01422       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01423       SmallVector<Metadata *, 8> MDs;
01424       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
01425       MDs.append(DstValue->op_begin(), DstValue->op_end());
01426       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
01427 
01428       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
01429       break;
01430     }
01431     case Module::AppendUnique: {
01432       SmallSetVector<Metadata *, 16> Elts;
01433       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
01434       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
01435       Elts.insert(DstValue->op_begin(), DstValue->op_end());
01436       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
01437 
01438       replaceDstValue(MDNode::get(DstM->getContext(),
01439                                   makeArrayRef(Elts.begin(), Elts.end())));
01440       break;
01441     }
01442     }
01443   }
01444 
01445   // Check all of the requirements.
01446   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
01447     MDNode *Requirement = Requirements[I];
01448     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
01449     Metadata *ReqValue = Requirement->getOperand(1);
01450 
01451     MDNode *Op = Flags[Flag].first;
01452     if (!Op || Op->getOperand(2) != ReqValue) {
01453       HasErr |= emitError("linking module flags '" + Flag->getString() +
01454                           "': does not have the required value");
01455       continue;
01456     }
01457   }
01458 
01459   return HasErr;
01460 }
01461 
01462 // This function returns true if the triples match.
01463 static bool triplesMatch(const Triple &T0, const Triple &T1) {
01464   // If vendor is apple, ignore the version number.
01465   if (T0.getVendor() == Triple::Apple)
01466     return T0.getArch() == T1.getArch() &&
01467            T0.getSubArch() == T1.getSubArch() &&
01468            T0.getVendor() == T1.getVendor() &&
01469            T0.getOS() == T1.getOS();
01470 
01471   return T0 == T1;
01472 }
01473 
01474 // This function returns the merged triple.
01475 static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
01476   // If vendor is apple, pick the triple with the larger version number.
01477   if (SrcTriple.getVendor() == Triple::Apple)
01478     if (DstTriple.isOSVersionLT(SrcTriple))
01479       return SrcTriple.str();
01480 
01481   return DstTriple.str();
01482 }
01483 
01484 bool ModuleLinker::run() {
01485   assert(DstM && "Null destination module");
01486   assert(SrcM && "Null source module");
01487 
01488   // Inherit the target data from the source module if the destination module
01489   // doesn't have one already.
01490   if (DstM->getDataLayout().isDefault())
01491     DstM->setDataLayout(SrcM->getDataLayout());
01492 
01493   if (SrcM->getDataLayout() != DstM->getDataLayout()) {
01494     emitWarning("Linking two modules of different data layouts: '" +
01495                 SrcM->getModuleIdentifier() + "' is '" +
01496                 SrcM->getDataLayoutStr() + "' whereas '" +
01497                 DstM->getModuleIdentifier() + "' is '" +
01498                 DstM->getDataLayoutStr() + "'\n");
01499   }
01500 
01501   // Copy the target triple from the source to dest if the dest's is empty.
01502   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
01503     DstM->setTargetTriple(SrcM->getTargetTriple());
01504 
01505   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
01506 
01507   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
01508     emitWarning("Linking two modules of different target triples: " +
01509                 SrcM->getModuleIdentifier() + "' is '" +
01510                 SrcM->getTargetTriple() + "' whereas '" +
01511                 DstM->getModuleIdentifier() + "' is '" +
01512                 DstM->getTargetTriple() + "'\n");
01513 
01514   DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
01515 
01516   // Append the module inline asm string.
01517   if (!SrcM->getModuleInlineAsm().empty()) {
01518     if (DstM->getModuleInlineAsm().empty())
01519       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
01520     else
01521       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
01522                                SrcM->getModuleInlineAsm());
01523   }
01524 
01525   // Loop over all of the linked values to compute type mappings.
01526   computeTypeMapping();
01527 
01528   ComdatsChosen.clear();
01529   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
01530     const Comdat &C = SMEC.getValue();
01531     if (ComdatsChosen.count(&C))
01532       continue;
01533     Comdat::SelectionKind SK;
01534     bool LinkFromSrc;
01535     if (getComdatResult(&C, SK, LinkFromSrc))
01536       return true;
01537     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
01538   }
01539 
01540   // Upgrade mismatched global arrays.
01541   upgradeMismatchedGlobals();
01542 
01543   // Insert all of the globals in src into the DstM module... without linking
01544   // initializers (which could refer to functions not yet mapped over).
01545   for (Module::global_iterator I = SrcM->global_begin(),
01546        E = SrcM->global_end(); I != E; ++I)
01547     if (linkGlobalValueProto(I))
01548       return true;
01549 
01550   // Link the functions together between the two modules, without doing function
01551   // bodies... this just adds external function prototypes to the DstM
01552   // function...  We do this so that when we begin processing function bodies,
01553   // all of the global values that may be referenced are available in our
01554   // ValueMap.
01555   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
01556     if (linkGlobalValueProto(I))
01557       return true;
01558 
01559   // If there were any aliases, link them now.
01560   for (Module::alias_iterator I = SrcM->alias_begin(),
01561        E = SrcM->alias_end(); I != E; ++I)
01562     if (linkGlobalValueProto(I))
01563       return true;
01564 
01565   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
01566     linkAppendingVarInit(AppendingVars[i]);
01567 
01568   for (const auto &Entry : DstM->getComdatSymbolTable()) {
01569     const Comdat &C = Entry.getValue();
01570     if (C.getSelectionKind() == Comdat::Any)
01571       continue;
01572     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
01573     assert(GV);
01574     MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer);
01575   }
01576 
01577   // Strip replaced subprograms before mapping any metadata -- so that we're
01578   // not changing metadata from the source module (note that
01579   // linkGlobalValueBody() eventually calls RemapInstruction() and therefore
01580   // MapMetadata()) -- but after linking global value protocols -- so that
01581   // OverridingFunctions has been built.
01582   stripReplacedSubprograms();
01583 
01584   // Link in the function bodies that are defined in the source module into
01585   // DstM.
01586   for (Function &SF : *SrcM) {
01587     // Skip if no body (function is external).
01588     if (SF.isDeclaration())
01589       continue;
01590 
01591     // Skip if not linking from source.
01592     if (DoNotLinkFromSource.count(&SF))
01593       continue;
01594 
01595     if (linkGlobalValueBody(SF))
01596       return true;
01597   }
01598 
01599   // Resolve all uses of aliases with aliasees.
01600   for (GlobalAlias &Src : SrcM->aliases()) {
01601     if (DoNotLinkFromSource.count(&Src))
01602       continue;
01603     linkGlobalValueBody(Src);
01604   }
01605 
01606   // Remap all of the named MDNodes in Src into the DstM module. We do this
01607   // after linking GlobalValues so that MDNodes that reference GlobalValues
01608   // are properly remapped.
01609   linkNamedMDNodes();
01610 
01611   // Merge the module flags into the DstM module.
01612   if (linkModuleFlagsMetadata())
01613     return true;
01614 
01615   // Update the initializers in the DstM module now that all globals that may
01616   // be referenced are in DstM.
01617   for (GlobalVariable &Src : SrcM->globals()) {
01618     // Only process initialized GV's or ones not already in dest.
01619     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
01620       continue;
01621     linkGlobalValueBody(Src);
01622   }
01623 
01624   // Process vector of lazily linked in functions.
01625   while (!LazilyLinkGlobalValues.empty()) {
01626     GlobalValue *SGV = LazilyLinkGlobalValues.back();
01627     LazilyLinkGlobalValues.pop_back();
01628 
01629     assert(!SGV->isDeclaration() && "users should not pass down decls");
01630     if (linkGlobalValueBody(*SGV))
01631       return true;
01632   }
01633 
01634   return false;
01635 }
01636 
01637 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
01638     : ETypes(E), IsPacked(P) {}
01639 
01640 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
01641     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
01642 
01643 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
01644   if (IsPacked != That.IsPacked)
01645     return false;
01646   if (ETypes != That.ETypes)
01647     return false;
01648   return true;
01649 }
01650 
01651 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
01652   return !this->operator==(That);
01653 }
01654 
01655 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
01656   return DenseMapInfo<StructType *>::getEmptyKey();
01657 }
01658 
01659 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
01660   return DenseMapInfo<StructType *>::getTombstoneKey();
01661 }
01662 
01663 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
01664   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
01665                       Key.IsPacked);
01666 }
01667 
01668 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
01669   return getHashValue(KeyTy(ST));
01670 }
01671 
01672 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
01673                                         const StructType *RHS) {
01674   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
01675     return false;
01676   return LHS == KeyTy(RHS);
01677 }
01678 
01679 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
01680                                         const StructType *RHS) {
01681   if (RHS == getEmptyKey())
01682     return LHS == getEmptyKey();
01683 
01684   if (RHS == getTombstoneKey())
01685     return LHS == getTombstoneKey();
01686 
01687   return KeyTy(LHS) == KeyTy(RHS);
01688 }
01689 
01690 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
01691   assert(!Ty->isOpaque());
01692   NonOpaqueStructTypes.insert(Ty);
01693 }
01694 
01695 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
01696   assert(!Ty->isOpaque());
01697   NonOpaqueStructTypes.insert(Ty);
01698   bool Removed = OpaqueStructTypes.erase(Ty);
01699   (void)Removed;
01700   assert(Removed);
01701 }
01702 
01703 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
01704   assert(Ty->isOpaque());
01705   OpaqueStructTypes.insert(Ty);
01706 }
01707 
01708 StructType *
01709 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
01710                                                bool IsPacked) {
01711   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
01712   auto I = NonOpaqueStructTypes.find_as(Key);
01713   if (I == NonOpaqueStructTypes.end())
01714     return nullptr;
01715   return *I;
01716 }
01717 
01718 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
01719   if (Ty->isOpaque())
01720     return OpaqueStructTypes.count(Ty);
01721   auto I = NonOpaqueStructTypes.find(Ty);
01722   if (I == NonOpaqueStructTypes.end())
01723     return false;
01724   return *I == Ty;
01725 }
01726 
01727 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01728   this->Composite = M;
01729   this->DiagnosticHandler = DiagnosticHandler;
01730 
01731   TypeFinder StructTypes;
01732   StructTypes.run(*M, true);
01733   for (StructType *Ty : StructTypes) {
01734     if (Ty->isOpaque())
01735       IdentifiedStructTypes.addOpaque(Ty);
01736     else
01737       IdentifiedStructTypes.addNonOpaque(Ty);
01738   }
01739 }
01740 
01741 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
01742   init(M, DiagnosticHandler);
01743 }
01744 
01745 Linker::Linker(Module *M) {
01746   init(M, [this](const DiagnosticInfo &DI) {
01747     Composite->getContext().diagnose(DI);
01748   });
01749 }
01750 
01751 Linker::~Linker() {
01752 }
01753 
01754 void Linker::deleteModule() {
01755   delete Composite;
01756   Composite = nullptr;
01757 }
01758 
01759 bool Linker::linkInModule(Module *Src, bool OverrideSymbols) {
01760   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
01761                          DiagnosticHandler, OverrideSymbols);
01762   bool RetCode = TheLinker.run();
01763   Composite->dropTriviallyDeadConstantArrays();
01764   return RetCode;
01765 }
01766 
01767 void Linker::setModule(Module *Dst) {
01768   init(Dst, DiagnosticHandler);
01769 }
01770 
01771 //===----------------------------------------------------------------------===//
01772 // LinkModules entrypoint.
01773 //===----------------------------------------------------------------------===//
01774 
01775 /// This function links two modules together, with the resulting Dest module
01776 /// modified to be the composite of the two input modules. If an error occurs,
01777 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
01778 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
01779 /// relied on to be consistent.
01780 bool Linker::LinkModules(Module *Dest, Module *Src,
01781                          DiagnosticHandlerFunction DiagnosticHandler) {
01782   Linker L(Dest, DiagnosticHandler);
01783   return L.linkInModule(Src);
01784 }
01785 
01786 bool Linker::LinkModules(Module *Dest, Module *Src) {
01787   Linker L(Dest);
01788   return L.linkInModule(Src);
01789 }
01790 
01791 //===----------------------------------------------------------------------===//
01792 // C API.
01793 //===----------------------------------------------------------------------===//
01794 
01795 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
01796                          LLVMLinkerMode Unused, char **OutMessages) {
01797   Module *D = unwrap(Dest);
01798   std::string Message;
01799   raw_string_ostream Stream(Message);
01800   DiagnosticPrinterRawOStream DP(Stream);
01801 
01802   LLVMBool Result = Linker::LinkModules(
01803       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
01804 
01805   if (OutMessages && Result)
01806     *OutMessages = strdup(Message.c_str());
01807   return Result;
01808 }