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