1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 // Specifically, this:
13 // * Merges global variables between the two modules
14 // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15 // * Merges functions between two modules
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Assembly/Writer.h"
28 // Error - Simple wrapper function to conditionally assign to E and return true.
29 // This just makes error return conditions a little bit simpler...
31 static inline bool Error(std::string *E, const std::string &Message) {
37 // Function: ResolveTypes()
40 // Attempt to link the two specified types together.
43 // DestTy - The type to which we wish to resolve.
44 // SrcTy - The original type which we want to resolve.
45 // Name - The name of the type.
48 // DestST - The symbol table in which the new type should be placed.
51 // true - There is an error and the types cannot yet be linked.
54 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
55 SymbolTable *DestST, const std::string &Name) {
56 if (DestTy == SrcTy) return false; // If already equal, noop
58 // Does the type already exist in the module?
59 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
60 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
61 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
63 return true; // Cannot link types... neither is opaque and not-equal
65 } else { // Type not in dest module. Add it now.
66 if (DestTy) // Type _is_ in module, just opaque...
67 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
68 ->refineAbstractTypeTo(SrcTy);
69 else if (!Name.empty())
70 DestST->insert(Name, const_cast<Type*>(SrcTy));
75 static const FunctionType *getFT(const PATypeHolder &TH) {
76 return cast<FunctionType>(TH.get());
78 static const StructType *getST(const PATypeHolder &TH) {
79 return cast<StructType>(TH.get());
82 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
83 // recurses down into derived types, merging the used types if the parent types
86 static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
87 const PATypeHolder &SrcTy,
88 SymbolTable *DestST, const std::string &Name,
89 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
90 const Type *SrcTyT = SrcTy.get();
91 const Type *DestTyT = DestTy.get();
92 if (DestTyT == SrcTyT) return false; // If already equal, noop
94 // If we found our opaque type, resolve it now!
95 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
96 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
98 // Two types cannot be resolved together if they are of different primitive
99 // type. For example, we cannot resolve an int to a float.
100 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
102 // Otherwise, resolve the used type used by this derived type...
103 switch (DestTyT->getPrimitiveID()) {
104 case Type::FunctionTyID: {
105 if (cast<FunctionType>(DestTyT)->isVarArg() !=
106 cast<FunctionType>(SrcTyT)->isVarArg() ||
107 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
108 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
110 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
111 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
112 getFT(SrcTy)->getContainedType(i), DestST, "",
117 case Type::StructTyID: {
118 if (getST(DestTy)->getNumContainedTypes() !=
119 getST(SrcTy)->getNumContainedTypes()) return 1;
120 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
121 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
122 getST(SrcTy)->getContainedType(i), DestST, "",
127 case Type::ArrayTyID: {
128 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
129 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
130 if (DAT->getNumElements() != SAT->getNumElements()) return true;
131 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
132 DestST, "", Pointers);
134 case Type::PointerTyID: {
135 // If this is a pointer type, check to see if we have already seen it. If
136 // so, we are in a recursive branch. Cut off the search now. We cannot use
137 // an associative container for this search, because the type pointers (keys
138 // in the container) change whenever types get resolved...
140 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
141 if (Pointers[i].first == DestTy)
142 return Pointers[i].second != SrcTy;
144 // Otherwise, add the current pointers to the vector to stop recursion on
146 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
148 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
149 cast<PointerType>(SrcTy.get())->getElementType(),
150 DestST, "", Pointers);
154 default: assert(0 && "Unexpected type!"); return true;
158 static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
159 const PATypeHolder &SrcTy,
160 SymbolTable *DestST, const std::string &Name){
161 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
162 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
166 // LinkTypes - Go through the symbol table of the Src module and see if any
167 // types are named in the src module that are not named in the Dst module.
168 // Make sure there are no type name conflicts.
170 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
171 SymbolTable *DestST = &Dest->getSymbolTable();
172 const SymbolTable *SrcST = &Src->getSymbolTable();
174 // Look for a type plane for Type's...
175 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
176 if (PI == SrcST->end()) return false; // No named types, do nothing.
178 // Some types cannot be resolved immediately because they depend on other
179 // types being resolved to each other first. This contains a list of types we
180 // are waiting to recheck.
181 std::vector<std::string> DelayedTypesToResolve;
183 const SymbolTable::VarMap &VM = PI->second;
184 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
186 const std::string &Name = I->first;
187 Type *RHS = cast<Type>(I->second);
189 // Check to see if this type name is already in the dest module...
190 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
192 if (ResolveTypes(Entry, RHS, DestST, Name)) {
193 // They look different, save the types 'till later to resolve.
194 DelayedTypesToResolve.push_back(Name);
198 // Iteratively resolve types while we can...
199 while (!DelayedTypesToResolve.empty()) {
200 // Loop over all of the types, attempting to resolve them if possible...
201 unsigned OldSize = DelayedTypesToResolve.size();
203 // Try direct resolution by name...
204 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
205 const std::string &Name = DelayedTypesToResolve[i];
206 Type *T1 = cast<Type>(VM.find(Name)->second);
207 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
208 if (!ResolveTypes(T2, T1, DestST, Name)) {
209 // We are making progress!
210 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
215 // Did we not eliminate any types?
216 if (DelayedTypesToResolve.size() == OldSize) {
217 // Attempt to resolve subelements of types. This allows us to merge these
218 // two types: { int* } and { opaque* }
219 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
220 const std::string &Name = DelayedTypesToResolve[i];
221 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
222 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
224 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
225 // We are making progress!
226 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
228 // Go back to the main loop, perhaps we can resolve directly by name
234 // If we STILL cannot resolve the types, then there is something wrong.
235 // Report the warning and delete one of the names.
236 if (DelayedTypesToResolve.size() == OldSize) {
237 const std::string &Name = DelayedTypesToResolve.back();
239 const Type *T1 = cast<Type>(VM.find(Name)->second);
240 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
241 std::cerr << "WARNING: Type conflict between types named '" << Name
243 WriteTypeSymbolic(std::cerr, T1, Src);
244 std::cerr << "'.\n Dest='";
245 WriteTypeSymbolic(std::cerr, T2, Dest);
248 // Remove the symbol name from the destination.
249 DelayedTypesToResolve.pop_back();
258 static void PrintMap(const std::map<const Value*, Value*> &M) {
259 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
261 std::cerr << " Fr: " << (void*)I->first << " ";
263 std::cerr << " To: " << (void*)I->second << " ";
270 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
271 // module to another. This is somewhat sophisticated in that it can
272 // automatically handle constant references correctly as well...
274 static Value *RemapOperand(const Value *In,
275 std::map<const Value*, Value*> &LocalMap,
276 std::map<const Value*, Value*> *GlobalMap) {
277 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
278 if (I != LocalMap.end()) return I->second;
281 I = GlobalMap->find(In);
282 if (I != GlobalMap->end()) return I->second;
285 // Check to see if it's a constant that we are interesting in transforming...
286 if (const Constant *CPV = dyn_cast<Constant>(In)) {
287 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
288 return const_cast<Constant*>(CPV); // Simple constants stay identical...
290 Constant *Result = 0;
292 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
293 const std::vector<Use> &Ops = CPA->getValues();
294 std::vector<Constant*> Operands(Ops.size());
295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
297 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
298 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
299 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
300 const std::vector<Use> &Ops = CPS->getValues();
301 std::vector<Constant*> Operands(Ops.size());
302 for (unsigned i = 0; i < Ops.size(); ++i)
304 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
305 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
306 } else if (isa<ConstantPointerNull>(CPV)) {
307 Result = const_cast<Constant*>(CPV);
308 } else if (const ConstantPointerRef *CPR =
309 dyn_cast<ConstantPointerRef>(CPV)) {
310 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
311 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
312 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
313 if (CE->getOpcode() == Instruction::GetElementPtr) {
314 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
315 std::vector<Constant*> Indices;
316 Indices.reserve(CE->getNumOperands()-1);
317 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
318 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
319 LocalMap, GlobalMap)));
321 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
322 } else if (CE->getNumOperands() == 1) {
324 assert(CE->getOpcode() == Instruction::Cast);
325 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
326 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
327 } else if (CE->getNumOperands() == 2) {
328 // Binary operator...
329 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
330 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
332 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
335 assert(0 && "Unknown constant expr type!");
339 assert(0 && "Unknown type of derived type constant value!");
342 // Cache the mapping in our local map structure...
344 GlobalMap->insert(std::make_pair(In, Result));
346 LocalMap.insert(std::make_pair(In, Result));
350 std::cerr << "XXX LocalMap: \n";
354 std::cerr << "XXX GlobalMap: \n";
355 PrintMap(*GlobalMap);
358 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
359 assert(0 && "Couldn't remap value!");
363 /// FindGlobalNamed - Look in the specified symbol table for a global with the
364 /// specified name and type. If an exactly matching global does not exist, see
365 /// if there is a global which is "type compatible" with the specified
366 /// name/type. This allows us to resolve things like '%x = global int*' with
367 /// '%x = global opaque*'.
369 static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
371 // See if an exact match exists in the symbol table...
372 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
374 // It doesn't exist exactly, scan through all of the type planes in the symbol
375 // table, checking each of them for a type-compatible version.
377 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
378 if (I->first != Type::TypeTy) {
379 SymbolTable::VarMap &VM = I->second;
381 // Does this type plane contain an entry with the specified name?
382 SymbolTable::type_iterator TI = VM.find(Name);
383 if (TI != VM.end()) {
385 // Ensure that this type if placed correctly into the symbol table.
387 assert(TI->second->getType() == I->first && "Type conflict!");
390 // Save a reference to the new type. Resolving the type can modify the
391 // symbol table, invalidating the TI variable.
393 Value *ValPtr = TI->second;
396 // Determine whether we can fold the two types together, resolving them.
397 // If so, we can use this value.
399 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
400 return cast<GlobalValue>(ValPtr);
403 return 0; // Otherwise, nothing could be found.
407 // LinkGlobals - Loop through the global variables in the src module and merge
408 // them into the dest module.
410 static bool LinkGlobals(Module *Dest, const Module *Src,
411 std::map<const Value*, Value*> &ValueMap,
412 std::multimap<std::string, GlobalVariable *> &AppendingVars,
414 // We will need a module level symbol table if the src module has a module
415 // level symbol table...
416 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
418 // Loop over all of the globals in the src module, mapping them over as we go
420 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
421 const GlobalVariable *SGV = I;
422 GlobalVariable *DGV = 0;
423 if (SGV->hasName()) {
424 // A same named thing is a global variable, because the only two things
425 // that may be in a module level symbol table are Global Vars and
426 // Functions, and they both have distinct, nonoverlapping, possible types.
428 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
429 SGV->getType(), ST));
432 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
433 "Global must either be external or have an initializer!");
435 bool SGExtern = SGV->isExternal();
436 bool DGExtern = DGV ? DGV->isExternal() : false;
438 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
439 // No linking to be performed, simply create an identical version of the
440 // symbol over in the dest module... the initializer will be filled in
441 // later by LinkGlobalInits...
443 GlobalVariable *NewDGV =
444 new GlobalVariable(SGV->getType()->getElementType(),
445 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
446 SGV->getName(), Dest);
448 // If the LLVM runtime renamed the global, but it is an externally visible
449 // symbol, DGV must be an existing global with internal linkage. Rename
451 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
452 assert(DGV && DGV->getName() == SGV->getName() &&
453 DGV->hasInternalLinkage());
455 NewDGV->setName(SGV->getName()); // Force the name back
456 DGV->setName(SGV->getName()); // This will cause a renaming
457 assert(NewDGV->getName() == SGV->getName() &&
458 DGV->getName() != SGV->getName());
461 // Make sure to remember this mapping...
462 ValueMap.insert(std::make_pair(SGV, NewDGV));
463 if (SGV->hasAppendingLinkage())
464 // Keep track that this is an appending variable...
465 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
467 } else if (SGV->isExternal()) {
468 // If SGV is external or if both SGV & DGV are external.. Just link the
469 // external globals, we aren't adding anything.
470 ValueMap.insert(std::make_pair(SGV, DGV));
472 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
473 ValueMap.insert(std::make_pair(SGV, DGV));
474 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
475 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
476 // At this point we know that DGV has LinkOnce, Appending, Weak, or
477 // External linkage. If DGV is Appending, this is an error.
478 if (DGV->hasAppendingLinkage())
479 return Error(Err, "Linking globals named '" + SGV->getName() +
480 " ' with 'weak' and 'appending' linkage is not allowed!");
482 if (SGV->isConstant() != DGV->isConstant())
483 return Error(Err, "Global Variable Collision on '" +
484 SGV->getType()->getDescription() + " %" + SGV->getName() +
485 "' - Global variables differ in const'ness");
487 // Otherwise, just perform the link.
488 ValueMap.insert(std::make_pair(SGV, DGV));
490 // Linkonce+Weak = Weak
491 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
492 DGV->setLinkage(SGV->getLinkage());
494 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
495 // At this point we know that SGV has LinkOnce, Appending, or External
496 // linkage. If SGV is Appending, this is an error.
497 if (SGV->hasAppendingLinkage())
498 return Error(Err, "Linking globals named '" + SGV->getName() +
499 " ' with 'weak' and 'appending' linkage is not allowed!");
501 if (SGV->isConstant() != DGV->isConstant())
502 return Error(Err, "Global Variable Collision on '" +
503 SGV->getType()->getDescription() + " %" + SGV->getName() +
504 "' - Global variables differ in const'ness");
506 if (!SGV->hasLinkOnceLinkage())
507 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
508 ValueMap.insert(std::make_pair(SGV, DGV));
510 } else if (SGV->getLinkage() != DGV->getLinkage()) {
511 return Error(Err, "Global variables named '" + SGV->getName() +
512 "' have different linkage specifiers!");
513 } else if (SGV->hasExternalLinkage()) {
514 // Allow linking two exactly identical external global variables...
515 if (SGV->isConstant() != DGV->isConstant())
516 return Error(Err, "Global Variable Collision on '" +
517 SGV->getType()->getDescription() + " %" + SGV->getName() +
518 "' - Global variables differ in const'ness");
520 if (SGV->getInitializer() != DGV->getInitializer())
521 return Error(Err, "Global Variable Collision on '" +
522 SGV->getType()->getDescription() + " %" + SGV->getName() +
523 "' - External linkage globals have different initializers");
525 ValueMap.insert(std::make_pair(SGV, DGV));
526 } else if (SGV->hasAppendingLinkage()) {
527 // No linking is performed yet. Just insert a new copy of the global, and
528 // keep track of the fact that it is an appending variable in the
529 // AppendingVars map. The name is cleared out so that no linkage is
531 GlobalVariable *NewDGV =
532 new GlobalVariable(SGV->getType()->getElementType(),
533 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
536 // Make sure to remember this mapping...
537 ValueMap.insert(std::make_pair(SGV, NewDGV));
539 // Keep track that this is an appending variable...
540 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
542 assert(0 && "Unknown linkage!");
549 // LinkGlobalInits - Update the initializers in the Dest module now that all
550 // globals that may be referenced are in Dest.
552 static bool LinkGlobalInits(Module *Dest, const Module *Src,
553 std::map<const Value*, Value*> &ValueMap,
556 // Loop over all of the globals in the src module, mapping them over as we go
558 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
559 const GlobalVariable *SGV = I;
561 if (SGV->hasInitializer()) { // Only process initialized GV's
562 // Figure out what the initializer looks like in the dest module...
564 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
566 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
567 if (DGV->hasInitializer()) {
568 assert(SGV->getLinkage() == DGV->getLinkage());
569 if (SGV->hasExternalLinkage()) {
570 if (DGV->getInitializer() != SInit)
571 return Error(Err, "Global Variable Collision on '" +
572 SGV->getType()->getDescription() +"':%"+SGV->getName()+
573 " - Global variables have different initializers");
574 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
575 // Nothing is required, mapped values will take the new global
577 } else if (DGV->hasAppendingLinkage()) {
578 assert(0 && "Appending linkage unimplemented!");
580 assert(0 && "Unknown linkage!");
583 // Copy the initializer over now...
584 DGV->setInitializer(SInit);
591 // LinkFunctionProtos - Link the functions together between the two modules,
592 // without doing function bodies... this just adds external function prototypes
593 // to the Dest function...
595 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
596 std::map<const Value*, Value*> &ValueMap,
598 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
600 // Loop over all of the functions in the src module, mapping them over as we
603 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
604 const Function *SF = I; // SrcFunction
607 // The same named thing is a Function, because the only two things
608 // that may be in a module level symbol table are Global Vars and
609 // Functions, and they both have distinct, nonoverlapping, possible types.
611 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
614 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
615 // Function does not already exist, simply insert an function signature
616 // identical to SF into the dest module...
617 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
618 SF->getName(), Dest);
620 // If the LLVM runtime renamed the function, but it is an externally
621 // visible symbol, DF must be an existing function with internal linkage.
623 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
624 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
626 NewDF->setName(SF->getName()); // Force the name back
627 DF->setName(SF->getName()); // This will cause a renaming
628 assert(NewDF->getName() == SF->getName() &&
629 DF->getName() != SF->getName());
632 // ... and remember this mapping...
633 ValueMap.insert(std::make_pair(SF, NewDF));
634 } else if (SF->isExternal()) {
635 // If SF is external or if both SF & DF are external.. Just link the
636 // external functions, we aren't adding anything.
637 ValueMap.insert(std::make_pair(SF, DF));
638 } else if (DF->isExternal()) { // If DF is external but SF is not...
639 // Link the external functions, update linkage qualifiers
640 ValueMap.insert(std::make_pair(SF, DF));
641 DF->setLinkage(SF->getLinkage());
643 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
644 // At this point we know that DF has LinkOnce, Weak, or External linkage.
645 ValueMap.insert(std::make_pair(SF, DF));
647 // Linkonce+Weak = Weak
648 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
649 DF->setLinkage(SF->getLinkage());
651 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
652 // At this point we know that SF has LinkOnce or External linkage.
653 ValueMap.insert(std::make_pair(SF, DF));
654 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
655 DF->setLinkage(SF->getLinkage());
657 } else if (SF->getLinkage() != DF->getLinkage()) {
658 return Error(Err, "Functions named '" + SF->getName() +
659 "' have different linkage specifiers!");
660 } else if (SF->hasExternalLinkage()) {
661 // The function is defined in both modules!!
662 return Error(Err, "Function '" +
663 SF->getFunctionType()->getDescription() + "':\"" +
664 SF->getName() + "\" - Function is already defined!");
666 assert(0 && "Unknown linkage configuration found!");
672 // LinkFunctionBody - Copy the source function over into the dest function and
673 // fix up references to values. At this point we know that Dest is an external
674 // function, and that Src is not.
676 static bool LinkFunctionBody(Function *Dest, const Function *Src,
677 std::map<const Value*, Value*> &GlobalMap,
679 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
680 std::map<const Value*, Value*> LocalMap; // Map for function local values
682 // Go through and convert function arguments over...
683 Function::aiterator DI = Dest->abegin();
684 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
686 DI->setName(I->getName()); // Copy the name information over...
688 // Add a mapping to our local map
689 LocalMap.insert(std::make_pair(I, DI));
692 // Loop over all of the basic blocks, copying the instructions over...
694 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
695 // Create new basic block and add to mapping and the Dest function...
696 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
697 LocalMap.insert(std::make_pair(I, DBB));
699 // Loop over all of the instructions in the src basic block, copying them
700 // over. Note that this is broken in a strict sense because the cloned
701 // instructions will still be referencing values in the Src module, not
702 // the remapped values. In our case, however, we will not get caught and
703 // so we can delay patching the values up until later...
705 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
707 Instruction *DI = II->clone();
708 DI->setName(II->getName());
709 DBB->getInstList().push_back(DI);
710 LocalMap.insert(std::make_pair(II, DI));
714 // At this point, all of the instructions and values of the function are now
715 // copied over. The only problem is that they are still referencing values in
716 // the Source function as operands. Loop through all of the operands of the
717 // functions and patch them up to point to the local versions...
719 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
720 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
721 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
723 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
729 // LinkFunctionBodies - Link in the function bodies that are defined in the
730 // source module into the DestModule. This consists basically of copying the
731 // function over and fixing up references to values.
733 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
734 std::map<const Value*, Value*> &ValueMap,
737 // Loop over all of the functions in the src module, mapping them over as we
740 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
741 if (!SF->isExternal()) { // No body if function is external
742 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
744 // DF not external SF external?
745 if (DF->isExternal()) {
746 // Only provide the function body if there isn't one already.
747 if (LinkFunctionBody(DF, SF, ValueMap, Err))
755 // LinkAppendingVars - If there were any appending global variables, link them
756 // together now. Return true on error.
758 static bool LinkAppendingVars(Module *M,
759 std::multimap<std::string, GlobalVariable *> &AppendingVars,
760 std::string *ErrorMsg) {
761 if (AppendingVars.empty()) return false; // Nothing to do.
763 // Loop over the multimap of appending vars, processing any variables with the
764 // same name, forming a new appending global variable with both of the
765 // initializers merged together, then rewrite references to the old variables
768 std::vector<Constant*> Inits;
769 while (AppendingVars.size() > 1) {
770 // Get the first two elements in the map...
771 std::multimap<std::string,
772 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
774 // If the first two elements are for different names, there is no pair...
775 // Otherwise there is a pair, so link them together...
776 if (First->first == Second->first) {
777 GlobalVariable *G1 = First->second, *G2 = Second->second;
778 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
779 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
781 // Check to see that they two arrays agree on type...
782 if (T1->getElementType() != T2->getElementType())
783 return Error(ErrorMsg,
784 "Appending variables with different element types need to be linked!");
785 if (G1->isConstant() != G2->isConstant())
786 return Error(ErrorMsg,
787 "Appending variables linked with different const'ness!");
789 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
790 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
792 // Create the new global variable...
794 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
795 /*init*/0, First->first, M);
797 // Merge the initializer...
798 Inits.reserve(NewSize);
799 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
800 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
801 Inits.push_back(cast<Constant>(I->getValues()[i]));
802 I = cast<ConstantArray>(G2->getInitializer());
803 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
804 Inits.push_back(cast<Constant>(I->getValues()[i]));
805 NG->setInitializer(ConstantArray::get(NewType, Inits));
808 // Replace any uses of the two global variables with uses of the new
811 // FIXME: This should rewrite simple/straight-forward uses such as
812 // getelementptr instructions to not use the Cast!
813 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
814 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
815 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
817 // Remove the two globals from the module now...
818 M->getGlobalList().erase(G1);
819 M->getGlobalList().erase(G2);
821 // Put the new global into the AppendingVars map so that we can handle
822 // linking of more than two vars...
825 AppendingVars.erase(First);
832 // LinkModules - This function links two modules together, with the resulting
833 // left module modified to be the composite of the two input modules. If an
834 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
835 // the problem. Upon failure, the Dest module could be in a modified state, and
836 // shouldn't be relied on to be consistent.
838 bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
839 if (Dest->getEndianness() == Module::AnyEndianness)
840 Dest->setEndianness(Src->getEndianness());
841 if (Dest->getPointerSize() == Module::AnyPointerSize)
842 Dest->setPointerSize(Src->getPointerSize());
844 if (Src->getEndianness() != Module::AnyEndianness &&
845 Dest->getEndianness() != Src->getEndianness())
846 std::cerr << "WARNING: Linking two modules of different endianness!\n";
847 if (Src->getPointerSize() != Module::AnyPointerSize &&
848 Dest->getPointerSize() != Src->getPointerSize())
849 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
851 // LinkTypes - Go through the symbol table of the Src module and see if any
852 // types are named in the src module that are not named in the Dst module.
853 // Make sure there are no type name conflicts.
855 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
857 // ValueMap - Mapping of values from what they used to be in Src, to what they
860 std::map<const Value*, Value*> ValueMap;
862 // AppendingVars - Keep track of global variables in the destination module
863 // with appending linkage. After the module is linked together, they are
864 // appended and the module is rewritten.
866 std::multimap<std::string, GlobalVariable *> AppendingVars;
868 // Add all of the appending globals already in the Dest module to
870 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
871 if (I->hasAppendingLinkage())
872 AppendingVars.insert(std::make_pair(I->getName(), I));
874 // Insert all of the globals in src into the Dest module... without linking
875 // initializers (which could refer to functions not yet mapped over).
877 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
879 // Link the functions together between the two modules, without doing function
880 // bodies... this just adds external function prototypes to the Dest
881 // function... We do this so that when we begin processing function bodies,
882 // all of the global values that may be referenced are available in our
885 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
887 // Update the initializers in the Dest module now that all globals that may
888 // be referenced are in Dest.
890 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
892 // Link in the function bodies that are defined in the source module into the
893 // DestModule. This consists basically of copying the function over and
894 // fixing up references to values.
896 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
898 // If there were any appending global variables, link them together now.
900 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;