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