LLVM API Documentation

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