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 // Specifically, this:
00013 //  * Merges global variables between the two modules
00014 //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
00015 //  * Merges functions between two modules
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Linker.h"
00020 #include "llvm/Constants.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/LLVMContext.h"
00023 #include "llvm/Module.h"
00024 #include "llvm/TypeSymbolTable.h"
00025 #include "llvm/ValueSymbolTable.h"
00026 #include "llvm/Instructions.h"
00027 #include "llvm/Assembly/Writer.h"
00028 #include "llvm/Support/Streams.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/System/Path.h"
00031 #include "llvm/ADT/DenseMap.h"
00032 #include <sstream>
00033 using namespace llvm;
00034 
00035 // Error - Simple wrapper function to conditionally assign to E and return true.
00036 // This just makes error return conditions a little bit simpler...
00037 static inline bool Error(std::string *E, const Twine &Message) {
00038   if (E) *E = Message.str();
00039   return true;
00040 }
00041 
00042 // Function: ResolveTypes()
00043 //
00044 // Description:
00045 //  Attempt to link the two specified types together.
00046 //
00047 // Inputs:
00048 //  DestTy - The type to which we wish to resolve.
00049 //  SrcTy  - The original type which we want to resolve.
00050 //
00051 // Outputs:
00052 //  DestST - The symbol table in which the new type should be placed.
00053 //
00054 // Return value:
00055 //  true  - There is an error and the types cannot yet be linked.
00056 //  false - No errors.
00057 //
00058 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
00059   if (DestTy == SrcTy) return false;       // If already equal, noop
00060   assert(DestTy && SrcTy && "Can't handle null types");
00061 
00062   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
00063     // Type _is_ in module, just opaque...
00064     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
00065   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
00066     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
00067   } else {
00068     return true;  // Cannot link types... not-equal and neither is opaque.
00069   }
00070   return false;
00071 }
00072 
00073 /// LinkerTypeMap - This implements a map of types that is stable
00074 /// even if types are resolved/refined to other types.  This is not a general
00075 /// purpose map, it is specific to the linker's use.
00076 namespace {
00077 class LinkerTypeMap : public AbstractTypeUser {
00078   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
00079   TheMapTy TheMap;
00080 
00081   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
00082   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
00083 public:
00084   LinkerTypeMap() {}
00085   ~LinkerTypeMap() {
00086     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
00087          E = TheMap.end(); I != E; ++I)
00088       I->first->removeAbstractTypeUser(this);
00089   }
00090 
00091   /// lookup - Return the value for the specified type or null if it doesn't
00092   /// exist.
00093   const Type *lookup(const Type *Ty) const {
00094     TheMapTy::const_iterator I = TheMap.find(Ty);
00095     if (I != TheMap.end()) return I->second;
00096     return 0;
00097   }
00098 
00099   /// erase - Remove the specified type, returning true if it was in the set.
00100   bool erase(const Type *Ty) {
00101     if (!TheMap.erase(Ty))
00102       return false;
00103     if (Ty->isAbstract())
00104       Ty->removeAbstractTypeUser(this);
00105     return true;
00106   }
00107 
00108   /// insert - This returns true if the pointer was new to the set, false if it
00109   /// was already in the set.
00110   bool insert(const Type *Src, const Type *Dst) {
00111     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
00112       return false;  // Already in map.
00113     if (Src->isAbstract())
00114       Src->addAbstractTypeUser(this);
00115     return true;
00116   }
00117 
00118 protected:
00119   /// refineAbstractType - The callback method invoked when an abstract type is
00120   /// resolved to another type.  An object must override this method to update
00121   /// its internal state to reference NewType instead of OldType.
00122   ///
00123   virtual void refineAbstractType(const DerivedType *OldTy,
00124                                   const Type *NewTy) {
00125     TheMapTy::iterator I = TheMap.find(OldTy);
00126     const Type *DstTy = I->second;
00127 
00128     TheMap.erase(I);
00129     if (OldTy->isAbstract())
00130       OldTy->removeAbstractTypeUser(this);
00131 
00132     // Don't reinsert into the map if the key is concrete now.
00133     if (NewTy->isAbstract())
00134       insert(NewTy, DstTy);
00135   }
00136 
00137   /// The other case which AbstractTypeUsers must be aware of is when a type
00138   /// makes the transition from being abstract (where it has clients on it's
00139   /// AbstractTypeUsers list) to concrete (where it does not).  This method
00140   /// notifies ATU's when this occurs for a type.
00141   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
00142     TheMap.erase(AbsTy);
00143     AbsTy->removeAbstractTypeUser(this);
00144   }
00145 
00146   // for debugging...
00147   virtual void dump() const {
00148     cerr << "AbstractTypeSet!\n";
00149   }
00150 };
00151 }
00152 
00153 
00154 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
00155 // recurses down into derived types, merging the used types if the parent types
00156 // are compatible.
00157 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
00158                                    LinkerTypeMap &Pointers) {
00159   if (DstTy == SrcTy) return false;       // If already equal, noop
00160 
00161   // If we found our opaque type, resolve it now!
00162   if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
00163     return ResolveTypes(DstTy, SrcTy);
00164 
00165   // Two types cannot be resolved together if they are of different primitive
00166   // type.  For example, we cannot resolve an int to a float.
00167   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
00168 
00169   // If neither type is abstract, then they really are just different types.
00170   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
00171     return true;
00172 
00173   // Otherwise, resolve the used type used by this derived type...
00174   switch (DstTy->getTypeID()) {
00175   default:
00176     return true;
00177   case Type::FunctionTyID: {
00178     const FunctionType *DstFT = cast<FunctionType>(DstTy);
00179     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
00180     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
00181         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
00182       return true;
00183 
00184     // Use TypeHolder's so recursive resolution won't break us.
00185     PATypeHolder ST(SrcFT), DT(DstFT);
00186     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
00187       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
00188       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
00189         return true;
00190     }
00191     return false;
00192   }
00193   case Type::StructTyID: {
00194     const StructType *DstST = cast<StructType>(DstTy);
00195     const StructType *SrcST = cast<StructType>(SrcTy);
00196     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
00197       return true;
00198 
00199     PATypeHolder ST(SrcST), DT(DstST);
00200     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
00201       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
00202       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
00203         return true;
00204     }
00205     return false;
00206   }
00207   case Type::ArrayTyID: {
00208     const ArrayType *DAT = cast<ArrayType>(DstTy);
00209     const ArrayType *SAT = cast<ArrayType>(SrcTy);
00210     if (DAT->getNumElements() != SAT->getNumElements()) return true;
00211     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
00212                                   Pointers);
00213   }
00214   case Type::VectorTyID: {
00215     const VectorType *DVT = cast<VectorType>(DstTy);
00216     const VectorType *SVT = cast<VectorType>(SrcTy);
00217     if (DVT->getNumElements() != SVT->getNumElements()) return true;
00218     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
00219                                   Pointers);
00220   }
00221   case Type::PointerTyID: {
00222     const PointerType *DstPT = cast<PointerType>(DstTy);
00223     const PointerType *SrcPT = cast<PointerType>(SrcTy);
00224 
00225     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
00226       return true;
00227 
00228     // If this is a pointer type, check to see if we have already seen it.  If
00229     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
00230     // an associative container for this search, because the type pointers (keys
00231     // in the container) change whenever types get resolved.
00232     if (SrcPT->isAbstract())
00233       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
00234         return ExistingDestTy != DstPT;
00235 
00236     if (DstPT->isAbstract())
00237       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
00238         return ExistingSrcTy != SrcPT;
00239     // Otherwise, add the current pointers to the vector to stop recursion on
00240     // this pair.
00241     if (DstPT->isAbstract())
00242       Pointers.insert(DstPT, SrcPT);
00243     if (SrcPT->isAbstract())
00244       Pointers.insert(SrcPT, DstPT);
00245 
00246     return RecursiveResolveTypesI(DstPT->getElementType(),
00247                                   SrcPT->getElementType(), Pointers);
00248   }
00249   }
00250 }
00251 
00252 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
00253   LinkerTypeMap PointerTypes;
00254   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
00255 }
00256 
00257 
00258 // LinkTypes - Go through the symbol table of the Src module and see if any
00259 // types are named in the src module that are not named in the Dst module.
00260 // Make sure there are no type name conflicts.
00261 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
00262         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
00263   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
00264 
00265   // Look for a type plane for Type's...
00266   TypeSymbolTable::const_iterator TI = SrcST->begin();
00267   TypeSymbolTable::const_iterator TE = SrcST->end();
00268   if (TI == TE) return false;  // No named types, do nothing.
00269 
00270   // Some types cannot be resolved immediately because they depend on other
00271   // types being resolved to each other first.  This contains a list of types we
00272   // are waiting to recheck.
00273   std::vector<std::string> DelayedTypesToResolve;
00274 
00275   for ( ; TI != TE; ++TI ) {
00276     const std::string &Name = TI->first;
00277     const Type *RHS = TI->second;
00278 
00279     // Check to see if this type name is already in the dest module.
00280     Type *Entry = DestST->lookup(Name);
00281 
00282     // If the name is just in the source module, bring it over to the dest.
00283     if (Entry == 0) {
00284       if (!Name.empty())
00285         DestST->insert(Name, const_cast<Type*>(RHS));
00286     } else if (ResolveTypes(Entry, RHS)) {
00287       // They look different, save the types 'till later to resolve.
00288       DelayedTypesToResolve.push_back(Name);
00289     }
00290   }
00291 
00292   // Iteratively resolve types while we can...
00293   while (!DelayedTypesToResolve.empty()) {
00294     // Loop over all of the types, attempting to resolve them if possible...
00295     unsigned OldSize = DelayedTypesToResolve.size();
00296 
00297     // Try direct resolution by name...
00298     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
00299       const std::string &Name = DelayedTypesToResolve[i];
00300       Type *T1 = SrcST->lookup(Name);
00301       Type *T2 = DestST->lookup(Name);
00302       if (!ResolveTypes(T2, T1)) {
00303         // We are making progress!
00304         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
00305         --i;
00306       }
00307     }
00308 
00309     // Did we not eliminate any types?
00310     if (DelayedTypesToResolve.size() == OldSize) {
00311       // Attempt to resolve subelements of types.  This allows us to merge these
00312       // two types: { int* } and { opaque* }
00313       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
00314         const std::string &Name = DelayedTypesToResolve[i];
00315         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
00316           // We are making progress!
00317           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
00318 
00319           // Go back to the main loop, perhaps we can resolve directly by name
00320           // now...
00321           break;
00322         }
00323       }
00324 
00325       // If we STILL cannot resolve the types, then there is something wrong.
00326       if (DelayedTypesToResolve.size() == OldSize) {
00327         // Remove the symbol name from the destination.
00328         DelayedTypesToResolve.pop_back();
00329       }
00330     }
00331   }
00332 
00333 
00334   return false;
00335 }
00336 
00337 #ifndef NDEBUG
00338 static void PrintMap(const std::map<const Value*, Value*> &M) {
00339   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
00340        I != E; ++I) {
00341     cerr << " Fr: " << (void*)I->first << " ";
00342     I->first->dump();
00343     cerr << " To: " << (void*)I->second << " ";
00344     I->second->dump();
00345     cerr << "\n";
00346   }
00347 }
00348 #endif
00349 
00350 
00351 // RemapOperand - Use ValueMap to convert constants from one module to another.
00352 static Value *RemapOperand(const Value *In,
00353                            std::map<const Value*, Value*> &ValueMap,
00354                            LLVMContext &Context) {
00355   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
00356   if (I != ValueMap.end())
00357     return I->second;
00358 
00359   // Check to see if it's a constant that we are interested in transforming.
00360   Value *Result = 0;
00361   if (const Constant *CPV = dyn_cast<Constant>(In)) {
00362     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
00363         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
00364       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
00365 
00366     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
00367       std::vector<Constant*> Operands(CPA->getNumOperands());
00368       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
00369         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap, 
00370                                                  Context));
00371       Result =
00372           ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
00373     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
00374       std::vector<Constant*> Operands(CPS->getNumOperands());
00375       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
00376         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
00377                                                  Context));
00378       Result =
00379          ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
00380     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
00381       Result = const_cast<Constant*>(CPV);
00382     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
00383       std::vector<Constant*> Operands(CP->getNumOperands());
00384       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
00385         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
00386                                      Context));
00387       Result = ConstantVector::get(Operands);
00388     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
00389       std::vector<Constant*> Ops;
00390       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
00391         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
00392                                      Context)));
00393       Result = CE->getWithOperands(Ops);
00394     } else {
00395       assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
00396       llvm_unreachable("Unknown type of derived type constant value!");
00397     }
00398   } else if (const MDNode *N = dyn_cast<MDNode>(In)) {
00399     std::vector<Value*> Elems;
00400     for (unsigned i = 0, e = N->getNumElements(); i !=e; ++i)
00401       Elems.push_back(RemapOperand(N->getElement(i), ValueMap, Context));
00402     if (!Elems.empty())
00403       Result = MDNode::get(Context, &Elems[0], Elems.size());
00404   } else if (const MDString *MDS = dyn_cast<MDString>(In)) {
00405     Result = MDString::get(Context, MDS->getString());
00406   } else if (isa<InlineAsm>(In)) {
00407     Result = const_cast<Value*>(In);
00408   }
00409 
00410   // Cache the mapping in our local map structure
00411   if (Result) {
00412     ValueMap[In] = Result;
00413     return Result;
00414   }
00415 
00416 #ifndef NDEBUG
00417   cerr << "LinkModules ValueMap: \n";
00418   PrintMap(ValueMap);
00419 
00420   cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
00421   llvm_unreachable("Couldn't remap value!");
00422 #endif
00423   return 0;
00424 }
00425 
00426 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
00427 /// in the symbol table.  This is good for all clients except for us.  Go
00428 /// through the trouble to force this back.
00429 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
00430   assert(GV->getName() != Name && "Can't force rename to self");
00431   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
00432 
00433   // If there is a conflict, rename the conflict.
00434   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
00435     assert(ConflictGV->hasLocalLinkage() &&
00436            "Not conflicting with a static global, should link instead!");
00437     GV->takeName(ConflictGV);
00438     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
00439     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
00440   } else {
00441     GV->setName(Name);              // Force the name back
00442   }
00443 }
00444 
00445 /// CopyGVAttributes - copy additional attributes (those not needed to construct
00446 /// a GlobalValue) from the SrcGV to the DestGV.
00447 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
00448   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
00449   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
00450   DestGV->copyAttributesFrom(SrcGV);
00451   DestGV->setAlignment(Alignment);
00452 }
00453 
00454 /// GetLinkageResult - This analyzes the two global values and determines what
00455 /// the result will look like in the destination module.  In particular, it
00456 /// computes the resultant linkage type, computes whether the global in the
00457 /// source should be copied over to the destination (replacing the existing
00458 /// one), and computes whether this linkage is an error or not. It also performs
00459 /// visibility checks: we cannot link together two symbols with different
00460 /// visibilities.
00461 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
00462                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
00463                              std::string *Err) {
00464   assert((!Dest || !Src->hasLocalLinkage()) &&
00465          "If Src has internal linkage, Dest shouldn't be set!");
00466   if (!Dest) {
00467     // Linking something to nothing.
00468     LinkFromSrc = true;
00469     LT = Src->getLinkage();
00470   } else if (Src->isDeclaration()) {
00471     // If Src is external or if both Src & Dest are external..  Just link the
00472     // external globals, we aren't adding anything.
00473     if (Src->hasDLLImportLinkage()) {
00474       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
00475       if (Dest->isDeclaration()) {
00476         LinkFromSrc = true;
00477         LT = Src->getLinkage();
00478       }
00479     } else if (Dest->hasExternalWeakLinkage()) {
00480       // If the Dest is weak, use the source linkage.
00481       LinkFromSrc = true;
00482       LT = Src->getLinkage();
00483     } else {
00484       LinkFromSrc = false;
00485       LT = Dest->getLinkage();
00486     }
00487   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
00488     // If Dest is external but Src is not:
00489     LinkFromSrc = true;
00490     LT = Src->getLinkage();
00491   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
00492     if (Src->getLinkage() != Dest->getLinkage())
00493       return Error(Err, "Linking globals named '" + Src->getName() +
00494             "': can only link appending global with another appending global!");
00495     LinkFromSrc = true; // Special cased.
00496     LT = Src->getLinkage();
00497   } else if (Src->isWeakForLinker()) {
00498     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
00499     // or DLL* linkage.
00500     if (Dest->hasExternalWeakLinkage() ||
00501         Dest->hasAvailableExternallyLinkage() ||
00502         (Dest->hasLinkOnceLinkage() &&
00503          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
00504       LinkFromSrc = true;
00505       LT = Src->getLinkage();
00506     } else {
00507       LinkFromSrc = false;
00508       LT = Dest->getLinkage();
00509     }
00510   } else if (Dest->isWeakForLinker()) {
00511     // At this point we know that Src has External* or DLL* linkage.
00512     if (Src->hasExternalWeakLinkage()) {
00513       LinkFromSrc = false;
00514       LT = Dest->getLinkage();
00515     } else {
00516       LinkFromSrc = true;
00517       LT = GlobalValue::ExternalLinkage;
00518     }
00519   } else {
00520     assert((Dest->hasExternalLinkage() ||
00521             Dest->hasDLLImportLinkage() ||
00522             Dest->hasDLLExportLinkage() ||
00523             Dest->hasExternalWeakLinkage()) &&
00524            (Src->hasExternalLinkage() ||
00525             Src->hasDLLImportLinkage() ||
00526             Src->hasDLLExportLinkage() ||
00527             Src->hasExternalWeakLinkage()) &&
00528            "Unexpected linkage type!");
00529     return Error(Err, "Linking globals named '" + Src->getName() +
00530                  "': symbol multiply defined!");
00531   }
00532 
00533   // Check visibility
00534   if (Dest && Src->getVisibility() != Dest->getVisibility())
00535     if (!Src->isDeclaration() && !Dest->isDeclaration())
00536       return Error(Err, "Linking globals named '" + Src->getName() +
00537                    "': symbols have different visibilities!");
00538   return false;
00539 }
00540 
00541 // Insert all of the named mdnoes in Src into the Dest module.
00542 static void LinkNamedMDNodes(Module *Dest, Module *Src) {
00543   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
00544          E = Src->named_metadata_end(); I != E; ++I) {
00545     const NamedMDNode *SrcNMD = I;
00546     NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
00547     if (!DestNMD)
00548       NamedMDNode::Create(SrcNMD, Dest);
00549     else {
00550       // Add Src elements into Dest node.
00551       for (unsigned i = 0, e = SrcNMD->getNumElements(); i != e; ++i) 
00552         DestNMD->addElement(SrcNMD->getElement(i));
00553     }
00554   }
00555 }
00556 
00557 // LinkGlobals - Loop through the global variables in the src module and merge
00558 // them into the dest module.
00559 static bool LinkGlobals(Module *Dest, const Module *Src,
00560                         std::map<const Value*, Value*> &ValueMap,
00561                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
00562                         std::string *Err) {
00563   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
00564 
00565   // Loop over all of the globals in the src module, mapping them over as we go
00566   for (Module::const_global_iterator I = Src->global_begin(),
00567        E = Src->global_end(); I != E; ++I) {
00568     const GlobalVariable *SGV = I;
00569     GlobalValue *DGV = 0;
00570 
00571     // Check to see if may have to link the global with the global, alias or
00572     // function.
00573     if (SGV->hasName() && !SGV->hasLocalLinkage())
00574       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
00575 
00576     // If we found a global with the same name in the dest module, but it has
00577     // internal linkage, we are really not doing any linkage here.
00578     if (DGV && DGV->hasLocalLinkage())
00579       DGV = 0;
00580 
00581     // If types don't agree due to opaque types, try to resolve them.
00582     if (DGV && DGV->getType() != SGV->getType())
00583       RecursiveResolveTypes(SGV->getType(), DGV->getType());
00584 
00585     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
00586             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
00587            "Global must either be external or have an initializer!");
00588 
00589     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
00590     bool LinkFromSrc = false;
00591     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
00592       return true;
00593 
00594     if (DGV == 0) {
00595       // No linking to be performed, simply create an identical version of the
00596       // symbol over in the dest module... the initializer will be filled in
00597       // later by LinkGlobalInits.
00598       GlobalVariable *NewDGV =
00599         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
00600                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
00601                            SGV->getName(), 0, false,
00602                            SGV->getType()->getAddressSpace());
00603       // Propagate alignment, visibility and section info.
00604       CopyGVAttributes(NewDGV, SGV);
00605 
00606       // If the LLVM runtime renamed the global, but it is an externally visible
00607       // symbol, DGV must be an existing global with internal linkage.  Rename
00608       // it.
00609       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
00610         ForceRenaming(NewDGV, SGV->getName());
00611 
00612       // Make sure to remember this mapping.
00613       ValueMap[SGV] = NewDGV;
00614 
00615       // Keep track that this is an appending variable.
00616       if (SGV->hasAppendingLinkage())
00617         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
00618       continue;
00619     }
00620 
00621     // If the visibilities of the symbols disagree and the destination is a
00622     // prototype, take the visibility of its input.
00623     if (DGV->isDeclaration())
00624       DGV->setVisibility(SGV->getVisibility());
00625 
00626     if (DGV->hasAppendingLinkage()) {
00627       // No linking is performed yet.  Just insert a new copy of the global, and
00628       // keep track of the fact that it is an appending variable in the
00629       // AppendingVars map.  The name is cleared out so that no linkage is
00630       // performed.
00631       GlobalVariable *NewDGV =
00632         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
00633                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
00634                            "", 0, false,
00635                            SGV->getType()->getAddressSpace());
00636 
00637       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
00638       NewDGV->setAlignment(DGV->getAlignment());
00639       // Propagate alignment, section and visibility info.
00640       CopyGVAttributes(NewDGV, SGV);
00641 
00642       // Make sure to remember this mapping...
00643       ValueMap[SGV] = NewDGV;
00644 
00645       // Keep track that this is an appending variable...
00646       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
00647       continue;
00648     }
00649 
00650     if (LinkFromSrc) {
00651       if (isa<GlobalAlias>(DGV))
00652         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
00653                      "': symbol multiple defined");
00654 
00655       // If the types don't match, and if we are to link from the source, nuke
00656       // DGV and create a new one of the appropriate type.  Note that the thing
00657       // we are replacing may be a function (if a prototype, weak, etc) or a
00658       // global variable.
00659       GlobalVariable *NewDGV =
00660         new GlobalVariable(*Dest, SGV->getType()->getElementType(), 
00661                            SGV->isConstant(), NewLinkage, /*init*/0, 
00662                            DGV->getName(), 0, false,
00663                            SGV->getType()->getAddressSpace());
00664 
00665       // Propagate alignment, section, and visibility info.
00666       CopyGVAttributes(NewDGV, SGV);
00667       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, 
00668                                                               DGV->getType()));
00669 
00670       // DGV will conflict with NewDGV because they both had the same
00671       // name. We must erase this now so ForceRenaming doesn't assert
00672       // because DGV might not have internal linkage.
00673       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
00674         Var->eraseFromParent();
00675       else
00676         cast<Function>(DGV)->eraseFromParent();
00677       DGV = NewDGV;
00678 
00679       // If the symbol table renamed the global, but it is an externally visible
00680       // symbol, DGV must be an existing global with internal linkage.  Rename.
00681       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
00682         ForceRenaming(NewDGV, SGV->getName());
00683 
00684       // Inherit const as appropriate.
00685       NewDGV->setConstant(SGV->isConstant());
00686 
00687       // Make sure to remember this mapping.
00688       ValueMap[SGV] = NewDGV;
00689       continue;
00690     }
00691 
00692     // Not "link from source", keep the one in the DestModule and remap the
00693     // input onto it.
00694 
00695     // Special case for const propagation.
00696     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
00697       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
00698         DGVar->setConstant(true);
00699 
00700     // SGV is global, but DGV is alias.
00701     if (isa<GlobalAlias>(DGV)) {
00702       // The only valid mappings are:
00703       // - SGV is external declaration, which is effectively a no-op.
00704       // - SGV is weak, when we just need to throw SGV out.
00705       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
00706         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
00707                      "': symbol multiple defined");
00708     }
00709 
00710     // Set calculated linkage
00711     DGV->setLinkage(NewLinkage);
00712 
00713     // Make sure to remember this mapping...
00714     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
00715   }
00716   return false;
00717 }
00718 
00719 static GlobalValue::LinkageTypes
00720 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
00721   GlobalValue::LinkageTypes SL = SGV->getLinkage();
00722   GlobalValue::LinkageTypes DL = DGV->getLinkage();
00723   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
00724     return GlobalValue::ExternalLinkage;
00725   else if (SL == GlobalValue::WeakAnyLinkage ||
00726            DL == GlobalValue::WeakAnyLinkage)
00727     return GlobalValue::WeakAnyLinkage;
00728   else if (SL == GlobalValue::WeakODRLinkage ||
00729            DL == GlobalValue::WeakODRLinkage)
00730     return GlobalValue::WeakODRLinkage;
00731   else if (SL == GlobalValue::InternalLinkage &&
00732            DL == GlobalValue::InternalLinkage)
00733     return GlobalValue::InternalLinkage;
00734   else if (SL == GlobalValue::LinkerPrivateLinkage &&
00735            DL == GlobalValue::LinkerPrivateLinkage)
00736     return GlobalValue::LinkerPrivateLinkage;
00737   else {
00738     assert (SL == GlobalValue::PrivateLinkage &&
00739             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
00740     return GlobalValue::PrivateLinkage;
00741   }
00742 }
00743 
00744 // LinkAlias - Loop through the alias in the src module and link them into the
00745 // dest module. We're assuming, that all functions/global variables were already
00746 // linked in.
00747 static bool LinkAlias(Module *Dest, const Module *Src,
00748                       std::map<const Value*, Value*> &ValueMap,
00749                       std::string *Err) {
00750   // Loop over all alias in the src module
00751   for (Module::const_alias_iterator I = Src->alias_begin(),
00752          E = Src->alias_end(); I != E; ++I) {
00753     const GlobalAlias *SGA = I;
00754     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
00755     GlobalAlias *NewGA = NULL;
00756 
00757     // Globals were already linked, thus we can just query ValueMap for variant
00758     // of SAliasee in Dest.
00759     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
00760     assert(VMI != ValueMap.end() && "Aliasee not linked");
00761     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
00762     GlobalValue* DGV = NULL;
00763 
00764     // Try to find something 'similar' to SGA in destination module.
00765     if (!DGV && !SGA->hasLocalLinkage()) {
00766       DGV = Dest->getNamedAlias(SGA->getName());
00767 
00768       // If types don't agree due to opaque types, try to resolve them.
00769       if (DGV && DGV->getType() != SGA->getType())
00770         RecursiveResolveTypes(SGA->getType(), DGV->getType());
00771     }
00772 
00773     if (!DGV && !SGA->hasLocalLinkage()) {
00774       DGV = Dest->getGlobalVariable(SGA->getName());
00775 
00776       // If types don't agree due to opaque types, try to resolve them.
00777       if (DGV && DGV->getType() != SGA->getType())
00778         RecursiveResolveTypes(SGA->getType(), DGV->getType());
00779     }
00780 
00781     if (!DGV && !SGA->hasLocalLinkage()) {
00782       DGV = Dest->getFunction(SGA->getName());
00783 
00784       // If types don't agree due to opaque types, try to resolve them.
00785       if (DGV && DGV->getType() != SGA->getType())
00786         RecursiveResolveTypes(SGA->getType(), DGV->getType());
00787     }
00788 
00789     // No linking to be performed on internal stuff.
00790     if (DGV && DGV->hasLocalLinkage())
00791       DGV = NULL;
00792 
00793     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
00794       // Types are known to be the same, check whether aliasees equal. As
00795       // globals are already linked we just need query ValueMap to find the
00796       // mapping.
00797       if (DAliasee == DGA->getAliasedGlobal()) {
00798         // This is just two copies of the same alias. Propagate linkage, if
00799         // necessary.
00800         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
00801 
00802         NewGA = DGA;
00803         // Proceed to 'common' steps
00804       } else
00805         return Error(Err, "Alias Collision on '"  + SGA->getName()+
00806                      "': aliases have different aliasees");
00807     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
00808       // The only allowed way is to link alias with external declaration or weak
00809       // symbol..
00810       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
00811         // But only if aliasee is global too...
00812         if (!isa<GlobalVariable>(DAliasee))
00813           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
00814                        "': aliasee is not global variable");
00815 
00816         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
00817                                 SGA->getName(), DAliasee, Dest);
00818         CopyGVAttributes(NewGA, SGA);
00819 
00820         // Any uses of DGV need to change to NewGA, with cast, if needed.
00821         if (SGA->getType() != DGVar->getType())
00822           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
00823                                                              DGVar->getType()));
00824         else
00825           DGVar->replaceAllUsesWith(NewGA);
00826 
00827         // DGVar will conflict with NewGA because they both had the same
00828         // name. We must erase this now so ForceRenaming doesn't assert
00829         // because DGV might not have internal linkage.
00830         DGVar->eraseFromParent();
00831 
00832         // Proceed to 'common' steps
00833       } else
00834         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
00835                      "': symbol multiple defined");
00836     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
00837       // The only allowed way is to link alias with external declaration or weak
00838       // symbol...
00839       if (DF->isDeclaration() || DF->isWeakForLinker()) {
00840         // But only if aliasee is function too...
00841         if (!isa<Function>(DAliasee))
00842           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
00843                        "': aliasee is not function");
00844 
00845         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
00846                                 SGA->getName(), DAliasee, Dest);
00847         CopyGVAttributes(NewGA, SGA);
00848 
00849         // Any uses of DF need to change to NewGA, with cast, if needed.
00850         if (SGA->getType() != DF->getType())
00851           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
00852                                                           DF->getType()));
00853         else
00854           DF->replaceAllUsesWith(NewGA);
00855 
00856         // DF will conflict with NewGA because they both had the same
00857         // name. We must erase this now so ForceRenaming doesn't assert
00858         // because DF might not have internal linkage.
00859         DF->eraseFromParent();
00860 
00861         // Proceed to 'common' steps
00862       } else
00863         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
00864                      "': symbol multiple defined");
00865     } else {
00866       // No linking to be performed, simply create an identical version of the
00867       // alias over in the dest module...
00868 
00869       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
00870                               SGA->getName(), DAliasee, Dest);
00871       CopyGVAttributes(NewGA, SGA);
00872 
00873       // Proceed to 'common' steps
00874     }
00875 
00876     assert(NewGA && "No alias was created in destination module!");
00877 
00878     // If the symbol table renamed the alias, but it is an externally visible
00879     // symbol, DGA must be an global value with internal linkage. Rename it.
00880     if (NewGA->getName() != SGA->getName() &&
00881         !NewGA->hasLocalLinkage())
00882       ForceRenaming(NewGA, SGA->getName());
00883 
00884     // Remember this mapping so uses in the source module get remapped
00885     // later by RemapOperand.
00886     ValueMap[SGA] = NewGA;
00887   }
00888 
00889   return false;
00890 }
00891 
00892 
00893 // LinkGlobalInits - Update the initializers in the Dest module now that all
00894 // globals that may be referenced are in Dest.
00895 static bool LinkGlobalInits(Module *Dest, const Module *Src,
00896                             std::map<const Value*, Value*> &ValueMap,
00897                             std::string *Err) {
00898   // Loop over all of the globals in the src module, mapping them over as we go
00899   for (Module::const_global_iterator I = Src->global_begin(),
00900        E = Src->global_end(); I != E; ++I) {
00901     const GlobalVariable *SGV = I;
00902 
00903     if (SGV->hasInitializer()) {      // Only process initialized GV's
00904       // Figure out what the initializer looks like in the dest module...
00905       Constant *SInit =
00906         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
00907                        Dest->getContext()));
00908       // Grab destination global variable or alias.
00909       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
00910 
00911       // If dest if global variable, check that initializers match.
00912       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
00913         if (DGVar->hasInitializer()) {
00914           if (SGV->hasExternalLinkage()) {
00915             if (DGVar->getInitializer() != SInit)
00916               return Error(Err, "Global Variable Collision on '" +
00917                            SGV->getName() +
00918                            "': global variables have different initializers");
00919           } else if (DGVar->isWeakForLinker()) {
00920             // Nothing is required, mapped values will take the new global
00921             // automatically.
00922           } else if (SGV->isWeakForLinker()) {
00923             // Nothing is required, mapped values will take the new global
00924             // automatically.
00925           } else if (DGVar->hasAppendingLinkage()) {
00926             llvm_unreachable("Appending linkage unimplemented!");
00927           } else {
00928             llvm_unreachable("Unknown linkage!");
00929           }
00930         } else {
00931           // Copy the initializer over now...
00932           DGVar->setInitializer(SInit);
00933         }
00934       } else {
00935         // Destination is alias, the only valid situation is when source is
00936         // weak. Also, note, that we already checked linkage in LinkGlobals(),
00937         // thus we assert here.
00938         // FIXME: Should we weaken this assumption, 'dereference' alias and
00939         // check for initializer of aliasee?
00940         assert(SGV->isWeakForLinker());
00941       }
00942     }
00943   }
00944   return false;
00945 }
00946 
00947 // LinkFunctionProtos - Link the functions together between the two modules,
00948 // without doing function bodies... this just adds external function prototypes
00949 // to the Dest function...
00950 //
00951 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
00952                                std::map<const Value*, Value*> &ValueMap,
00953                                std::string *Err) {
00954   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
00955 
00956   // Loop over all of the functions in the src module, mapping them over
00957   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
00958     const Function *SF = I;   // SrcFunction
00959     GlobalValue *DGV = 0;
00960 
00961     // Check to see if may have to link the function with the global, alias or
00962     // function.
00963     if (SF->hasName() && !SF->hasLocalLinkage())
00964       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
00965 
00966     // If we found a global with the same name in the dest module, but it has
00967     // internal linkage, we are really not doing any linkage here.
00968     if (DGV && DGV->hasLocalLinkage())
00969       DGV = 0;
00970 
00971     // If types don't agree due to opaque types, try to resolve them.
00972     if (DGV && DGV->getType() != SF->getType())
00973       RecursiveResolveTypes(SF->getType(), DGV->getType());
00974 
00975     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
00976     bool LinkFromSrc = false;
00977     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
00978       return true;
00979 
00980     // If there is no linkage to be performed, just bring over SF without
00981     // modifying it.
00982     if (DGV == 0) {
00983       // Function does not already exist, simply insert an function signature
00984       // identical to SF into the dest module.
00985       Function *NewDF = Function::Create(SF->getFunctionType(),
00986                                          SF->getLinkage(),
00987                                          SF->getName(), Dest);
00988       CopyGVAttributes(NewDF, SF);
00989 
00990       // If the LLVM runtime renamed the function, but it is an externally
00991       // visible symbol, DF must be an existing function with internal linkage.
00992       // Rename it.
00993       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
00994         ForceRenaming(NewDF, SF->getName());
00995 
00996       // ... and remember this mapping...
00997       ValueMap[SF] = NewDF;
00998       continue;
00999     }
01000 
01001     // If the visibilities of the symbols disagree and the destination is a
01002     // prototype, take the visibility of its input.
01003     if (DGV->isDeclaration())
01004       DGV->setVisibility(SF->getVisibility());
01005 
01006     if (LinkFromSrc) {
01007       if (isa<GlobalAlias>(DGV))
01008         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
01009                      "': symbol multiple defined");
01010 
01011       // We have a definition of the same name but different type in the
01012       // source module. Copy the prototype to the destination and replace
01013       // uses of the destination's prototype with the new prototype.
01014       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
01015                                          SF->getName(), Dest);
01016       CopyGVAttributes(NewDF, SF);
01017 
01018       // Any uses of DF need to change to NewDF, with cast
01019       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, 
01020                                                               DGV->getType()));
01021 
01022       // DF will conflict with NewDF because they both had the same. We must
01023       // erase this now so ForceRenaming doesn't assert because DF might
01024       // not have internal linkage.
01025       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
01026         Var->eraseFromParent();
01027       else
01028         cast<Function>(DGV)->eraseFromParent();
01029 
01030       // If the symbol table renamed the function, but it is an externally
01031       // visible symbol, DF must be an existing function with internal
01032       // linkage.  Rename it.
01033       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
01034         ForceRenaming(NewDF, SF->getName());
01035 
01036       // Remember this mapping so uses in the source module get remapped
01037       // later by RemapOperand.
01038       ValueMap[SF] = NewDF;
01039       continue;
01040     }
01041 
01042     // Not "link from source", keep the one in the DestModule and remap the
01043     // input onto it.
01044 
01045     if (isa<GlobalAlias>(DGV)) {
01046       // The only valid mappings are:
01047       // - SF is external declaration, which is effectively a no-op.
01048       // - SF is weak, when we just need to throw SF out.
01049       if (!SF->isDeclaration() && !SF->isWeakForLinker())
01050         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
01051                      "': symbol multiple defined");
01052     }
01053 
01054     // Set calculated linkage
01055     DGV->setLinkage(NewLinkage);
01056 
01057     // Make sure to remember this mapping.
01058     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
01059   }
01060   return false;
01061 }
01062 
01063 // LinkFunctionBody - Copy the source function over into the dest function and
01064 // fix up references to values.  At this point we know that Dest is an external
01065 // function, and that Src is not.
01066 static bool LinkFunctionBody(Function *Dest, Function *Src,
01067                              std::map<const Value*, Value*> &ValueMap,
01068                              std::string *Err) {
01069   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
01070 
01071   // Go through and convert function arguments over, remembering the mapping.
01072   Function::arg_iterator DI = Dest->arg_begin();
01073   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
01074        I != E; ++I, ++DI) {
01075     DI->setName(I->getName());  // Copy the name information over...
01076 
01077     // Add a mapping to our local map
01078     ValueMap[I] = DI;
01079   }
01080 
01081   // Splice the body of the source function into the dest function.
01082   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
01083 
01084   // At this point, all of the instructions and values of the function are now
01085   // copied over.  The only problem is that they are still referencing values in
01086   // the Source function as operands.  Loop through all of the operands of the
01087   // functions and patch them up to point to the local versions...
01088   //
01089   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
01090     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
01091       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
01092            OI != OE; ++OI)
01093         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
01094           *OI = RemapOperand(*OI, ValueMap, Dest->getContext());
01095 
01096   // There is no need to map the arguments anymore.
01097   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
01098        I != E; ++I)
01099     ValueMap.erase(I);
01100 
01101   return false;
01102 }
01103 
01104 
01105 // LinkFunctionBodies - Link in the function bodies that are defined in the
01106 // source module into the DestModule.  This consists basically of copying the
01107 // function over and fixing up references to values.
01108 static bool LinkFunctionBodies(Module *Dest, Module *Src,
01109                                std::map<const Value*, Value*> &ValueMap,
01110                                std::string *Err) {
01111 
01112   // Loop over all of the functions in the src module, mapping them over as we
01113   // go
01114   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
01115     if (!SF->isDeclaration()) {               // No body if function is external
01116       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
01117 
01118       // DF not external SF external?
01119       if (DF && DF->isDeclaration())
01120         // Only provide the function body if there isn't one already.
01121         if (LinkFunctionBody(DF, SF, ValueMap, Err))
01122           return true;
01123     }
01124   }
01125   return false;
01126 }
01127 
01128 // LinkAppendingVars - If there were any appending global variables, link them
01129 // together now.  Return true on error.
01130 static bool LinkAppendingVars(Module *M,
01131                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
01132                               std::string *ErrorMsg) {
01133   if (AppendingVars.empty()) return false; // Nothing to do.
01134 
01135   // Loop over the multimap of appending vars, processing any variables with the
01136   // same name, forming a new appending global variable with both of the
01137   // initializers merged together, then rewrite references to the old variables
01138   // and delete them.
01139   std::vector<Constant*> Inits;
01140   while (AppendingVars.size() > 1) {
01141     // Get the first two elements in the map...
01142     std::multimap<std::string,
01143       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
01144 
01145     // If the first two elements are for different names, there is no pair...
01146     // Otherwise there is a pair, so link them together...
01147     if (First->first == Second->first) {
01148       GlobalVariable *G1 = First->second, *G2 = Second->second;
01149       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
01150       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
01151 
01152       // Check to see that they two arrays agree on type...
01153       if (T1->getElementType() != T2->getElementType())
01154         return Error(ErrorMsg,
01155          "Appending variables with different element types need to be linked!");
01156       if (G1->isConstant() != G2->isConstant())
01157         return Error(ErrorMsg,
01158                      "Appending variables linked with different const'ness!");
01159 
01160       if (G1->getAlignment() != G2->getAlignment())
01161         return Error(ErrorMsg,
01162          "Appending variables with different alignment need to be linked!");
01163 
01164       if (G1->getVisibility() != G2->getVisibility())
01165         return Error(ErrorMsg,
01166          "Appending variables with different visibility need to be linked!");
01167 
01168       if (G1->getSection() != G2->getSection())
01169         return Error(ErrorMsg,
01170          "Appending variables with different section name need to be linked!");
01171 
01172       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
01173       ArrayType *NewType = ArrayType::get(T1->getElementType(), 
01174                                                          NewSize);
01175 
01176       G1->setName("");   // Clear G1's name in case of a conflict!
01177 
01178       // Create the new global variable...
01179       GlobalVariable *NG =
01180         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
01181                            /*init*/0, First->first, 0, G1->isThreadLocal(),
01182                            G1->getType()->getAddressSpace());
01183 
01184       // Propagate alignment, visibility and section info.
01185       CopyGVAttributes(NG, G1);
01186 
01187       // Merge the initializer...
01188       Inits.reserve(NewSize);
01189       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
01190         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
01191           Inits.push_back(I->getOperand(i));
01192       } else {
01193         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
01194         Constant *CV = Constant::getNullValue(T1->getElementType());
01195         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
01196           Inits.push_back(CV);
01197       }
01198       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
01199         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
01200           Inits.push_back(I->getOperand(i));
01201       } else {
01202         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
01203         Constant *CV = Constant::getNullValue(T2->getElementType());
01204         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
01205           Inits.push_back(CV);
01206       }
01207       NG->setInitializer(ConstantArray::get(NewType, Inits));
01208       Inits.clear();
01209 
01210       // Replace any uses of the two global variables with uses of the new
01211       // global...
01212 
01213       // FIXME: This should rewrite simple/straight-forward uses such as
01214       // getelementptr instructions to not use the Cast!
01215       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
01216                              G1->getType()));
01217       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, 
01218                              G2->getType()));
01219 
01220       // Remove the two globals from the module now...
01221       M->getGlobalList().erase(G1);
01222       M->getGlobalList().erase(G2);
01223 
01224       // Put the new global into the AppendingVars map so that we can handle
01225       // linking of more than two vars...
01226       Second->second = NG;
01227     }
01228     AppendingVars.erase(First);
01229   }
01230 
01231   return false;
01232 }
01233 
01234 static bool ResolveAliases(Module *Dest) {
01235   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
01236        I != E; ++I)
01237     if (const GlobalValue *GV = I->resolveAliasedGlobal())
01238       if (GV != I && !GV->isDeclaration())
01239         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
01240 
01241   return false;
01242 }
01243 
01244 // LinkModules - This function links two modules together, with the resulting
01245 // left module modified to be the composite of the two input modules.  If an
01246 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
01247 // the problem.  Upon failure, the Dest module could be in a modified state, and
01248 // shouldn't be relied on to be consistent.
01249 bool
01250 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
01251   assert(Dest != 0 && "Invalid Destination module");
01252   assert(Src  != 0 && "Invalid Source Module");
01253 
01254   if (Dest->getDataLayout().empty()) {
01255     if (!Src->getDataLayout().empty()) {
01256       Dest->setDataLayout(Src->getDataLayout());
01257     } else {
01258       std::string DataLayout;
01259 
01260       if (Dest->getEndianness() == Module::AnyEndianness) {
01261         if (Src->getEndianness() == Module::BigEndian)
01262           DataLayout.append("E");
01263         else if (Src->getEndianness() == Module::LittleEndian)
01264           DataLayout.append("e");
01265       }
01266 
01267       if (Dest->getPointerSize() == Module::AnyPointerSize) {
01268         if (Src->getPointerSize() == Module::Pointer64)
01269           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
01270         else if (Src->getPointerSize() == Module::Pointer32)
01271           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
01272       }
01273       Dest->setDataLayout(DataLayout);
01274     }
01275   }
01276 
01277   // Copy the target triple from the source to dest if the dest's is empty.
01278   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
01279     Dest->setTargetTriple(Src->getTargetTriple());
01280 
01281   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
01282       Src->getDataLayout() != Dest->getDataLayout())
01283     cerr << "WARNING: Linking two modules of different data layouts!\n";
01284   if (!Src->getTargetTriple().empty() &&
01285       Dest->getTargetTriple() != Src->getTargetTriple())
01286     cerr << "WARNING: Linking two modules of different target triples!\n";
01287 
01288   // Append the module inline asm string.
01289   if (!Src->getModuleInlineAsm().empty()) {
01290     if (Dest->getModuleInlineAsm().empty())
01291       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
01292     else
01293       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
01294                                Src->getModuleInlineAsm());
01295   }
01296 
01297   // Update the destination module's dependent libraries list with the libraries
01298   // from the source module. There's no opportunity for duplicates here as the
01299   // Module ensures that duplicate insertions are discarded.
01300   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
01301        SI != SE; ++SI)
01302     Dest->addLibrary(*SI);
01303 
01304   // LinkTypes - Go through the symbol table of the Src module and see if any
01305   // types are named in the src module that are not named in the Dst module.
01306   // Make sure there are no type name conflicts.
01307   if (LinkTypes(Dest, Src, ErrorMsg))
01308     return true;
01309 
01310   // ValueMap - Mapping of values from what they used to be in Src, to what they
01311   // are now in Dest.
01312   std::map<const Value*, Value*> ValueMap;
01313 
01314   // AppendingVars - Keep track of global variables in the destination module
01315   // with appending linkage.  After the module is linked together, they are
01316   // appended and the module is rewritten.
01317   std::multimap<std::string, GlobalVariable *> AppendingVars;
01318   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
01319        I != E; ++I) {
01320     // Add all of the appending globals already in the Dest module to
01321     // AppendingVars.
01322     if (I->hasAppendingLinkage())
01323       AppendingVars.insert(std::make_pair(I->getName(), I));
01324   }
01325 
01326   // Insert all of the named mdnoes in Src into the Dest module.
01327   LinkNamedMDNodes(Dest, Src);
01328 
01329   // Insert all of the globals in src into the Dest module... without linking
01330   // initializers (which could refer to functions not yet mapped over).
01331   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
01332     return true;
01333 
01334   // Link the functions together between the two modules, without doing function
01335   // bodies... this just adds external function prototypes to the Dest
01336   // function...  We do this so that when we begin processing function bodies,
01337   // all of the global values that may be referenced are available in our
01338   // ValueMap.
01339   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
01340     return true;
01341 
01342   // If there were any alias, link them now. We really need to do this now,
01343   // because all of the aliases that may be referenced need to be available in
01344   // ValueMap
01345   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
01346 
01347   // Update the initializers in the Dest module now that all globals that may
01348   // be referenced are in Dest.
01349   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
01350 
01351   // Link in the function bodies that are defined in the source module into the
01352   // DestModule.  This consists basically of copying the function over and
01353   // fixing up references to values.
01354   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
01355 
01356   // If there were any appending global variables, link them together now.
01357   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
01358 
01359   // Resolve all uses of aliases with aliasees
01360   if (ResolveAliases(Dest)) return true;
01361 
01362   // If the source library's module id is in the dependent library list of the
01363   // destination library, remove it since that module is now linked in.
01364   sys::Path modId;
01365   modId.set(Src->getModuleIdentifier());
01366   if (!modId.isEmpty())
01367     Dest->removeLibrary(modId.getBasename());
01368 
01369   return false;
01370 }
01371 
01372 // vim: sw=2