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::type_const_iterator TI = SrcST->type_begin();
176 SymbolTable::type_const_iterator TE = SrcST->type_end();
177 if (TI == TE) return false; // No named types, do nothing.
179 // Some types cannot be resolved immediately because they depend on other
180 // types being resolved to each other first. This contains a list of types we
181 // are waiting to recheck.
182 std::vector<std::string> DelayedTypesToResolve;
184 for ( ; TI != TE; ++TI ) {
185 const std::string &Name = TI->first;
186 Type *RHS = TI->second;
188 // Check to see if this type name is already in the dest module...
189 Type *Entry = DestST->lookupType(Name);
191 if (ResolveTypes(Entry, RHS, DestST, Name)) {
192 // They look different, save the types 'till later to resolve.
193 DelayedTypesToResolve.push_back(Name);
197 // Iteratively resolve types while we can...
198 while (!DelayedTypesToResolve.empty()) {
199 // Loop over all of the types, attempting to resolve them if possible...
200 unsigned OldSize = DelayedTypesToResolve.size();
202 // Try direct resolution by name...
203 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
204 const std::string &Name = DelayedTypesToResolve[i];
205 Type *T1 = SrcST->lookupType(Name);
206 Type *T2 = DestST->lookupType(Name);
207 if (!ResolveTypes(T2, T1, DestST, Name)) {
208 // We are making progress!
209 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
214 // Did we not eliminate any types?
215 if (DelayedTypesToResolve.size() == OldSize) {
216 // Attempt to resolve subelements of types. This allows us to merge these
217 // two types: { int* } and { opaque* }
218 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
219 const std::string &Name = DelayedTypesToResolve[i];
220 PATypeHolder T1(SrcST->lookupType(Name));
221 PATypeHolder T2(DestST->lookupType(Name));
223 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
224 // We are making progress!
225 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
227 // Go back to the main loop, perhaps we can resolve directly by name
233 // If we STILL cannot resolve the types, then there is something wrong.
234 // Report the warning and delete one of the names.
235 if (DelayedTypesToResolve.size() == OldSize) {
236 const std::string &Name = DelayedTypesToResolve.back();
238 const Type *T1 = SrcST->lookupType(Name);
239 const Type *T2 = DestST->lookupType(Name);
240 std::cerr << "WARNING: Type conflict between types named '" << Name
242 WriteTypeSymbolic(std::cerr, T1, Src);
243 std::cerr << "'.\n Dest='";
244 WriteTypeSymbolic(std::cerr, T2, Dest);
247 // Remove the symbol name from the destination.
248 DelayedTypesToResolve.pop_back();
257 static void PrintMap(const std::map<const Value*, Value*> &M) {
258 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
260 std::cerr << " Fr: " << (void*)I->first << " ";
262 std::cerr << " To: " << (void*)I->second << " ";
269 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
270 // module to another. This is somewhat sophisticated in that it can
271 // automatically handle constant references correctly as well...
273 static Value *RemapOperand(const Value *In,
274 std::map<const Value*, Value*> &LocalMap,
275 std::map<const Value*, Value*> *GlobalMap) {
276 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
277 if (I != LocalMap.end()) return I->second;
280 I = GlobalMap->find(In);
281 if (I != GlobalMap->end()) return I->second;
284 // Check to see if it's a constant that we are interesting in transforming...
285 if (const Constant *CPV = dyn_cast<Constant>(In)) {
286 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
287 isa<ConstantAggregateZero>(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() == 3) {
328 // Select instruction
329 assert(CE->getOpcode() == Instruction::Select);
330 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
331 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
332 Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
333 Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
335 } else if (CE->getNumOperands() == 2) {
336 // Binary operator...
337 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
338 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
340 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
343 assert(0 && "Unknown constant expr type!");
347 assert(0 && "Unknown type of derived type constant value!");
350 // Cache the mapping in our local map structure...
352 GlobalMap->insert(std::make_pair(In, Result));
354 LocalMap.insert(std::make_pair(In, Result));
358 std::cerr << "XXX LocalMap: \n";
362 std::cerr << "XXX GlobalMap: \n";
363 PrintMap(*GlobalMap);
366 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
367 assert(0 && "Couldn't remap value!");
371 /// FindGlobalNamed - Look in the specified symbol table for a global with the
372 /// specified name and type. If an exactly matching global does not exist, see
373 /// if there is a global which is "type compatible" with the specified
374 /// name/type. This allows us to resolve things like '%x = global int*' with
375 /// '%x = global opaque*'.
377 static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
379 // See if an exact match exists in the symbol table...
380 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
382 // It doesn't exist exactly, scan through all of the type planes in the symbol
383 // table, checking each of them for a type-compatible version.
385 for (SymbolTable::plane_iterator PI = ST->plane_begin(), PE = ST->plane_end();
387 SymbolTable::ValueMap &VM = PI->second;
389 // Does this type plane contain an entry with the specified name?
390 SymbolTable::value_iterator VI = VM.find(Name);
391 if (VI != VM.end()) {
393 // Ensure that this type if placed correctly into the symbol table.
395 assert(VI->second->getType() == PI->first && "Type conflict!");
398 // Save a reference to the new type. Resolving the type can modify the
399 // symbol table, invalidating the TI variable.
401 Value *ValPtr = VI->second;
404 // Determine whether we can fold the two types together, resolving them.
405 // If so, we can use this value.
407 if (!RecursiveResolveTypes(Ty, PI->first, ST, ""))
408 return cast<GlobalValue>(ValPtr);
411 return 0; // Otherwise, nothing could be found.
415 // LinkGlobals - Loop through the global variables in the src module and merge
416 // them into the dest module.
418 static bool LinkGlobals(Module *Dest, const Module *Src,
419 std::map<const Value*, Value*> &ValueMap,
420 std::multimap<std::string, GlobalVariable *> &AppendingVars,
422 // We will need a module level symbol table if the src module has a module
423 // level symbol table...
424 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
426 // Loop over all of the globals in the src module, mapping them over as we go
428 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
429 const GlobalVariable *SGV = I;
430 GlobalVariable *DGV = 0;
431 if (SGV->hasName()) {
432 // A same named thing is a global variable, because the only two things
433 // that may be in a module level symbol table are Global Vars and
434 // Functions, and they both have distinct, nonoverlapping, possible types.
436 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
437 SGV->getType(), ST));
440 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
441 "Global must either be external or have an initializer!");
443 bool SGExtern = SGV->isExternal();
444 bool DGExtern = DGV ? DGV->isExternal() : false;
446 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
447 // No linking to be performed, simply create an identical version of the
448 // symbol over in the dest module... the initializer will be filled in
449 // later by LinkGlobalInits...
451 GlobalVariable *NewDGV =
452 new GlobalVariable(SGV->getType()->getElementType(),
453 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
454 SGV->getName(), Dest);
456 // If the LLVM runtime renamed the global, but it is an externally visible
457 // symbol, DGV must be an existing global with internal linkage. Rename
459 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
460 assert(DGV && DGV->getName() == SGV->getName() &&
461 DGV->hasInternalLinkage());
463 NewDGV->setName(SGV->getName()); // Force the name back
464 DGV->setName(SGV->getName()); // This will cause a renaming
465 assert(NewDGV->getName() == SGV->getName() &&
466 DGV->getName() != SGV->getName());
469 // Make sure to remember this mapping...
470 ValueMap.insert(std::make_pair(SGV, NewDGV));
471 if (SGV->hasAppendingLinkage())
472 // Keep track that this is an appending variable...
473 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
475 } else if (SGV->isExternal()) {
476 // If SGV is external or if both SGV & DGV are external.. Just link the
477 // external globals, we aren't adding anything.
478 ValueMap.insert(std::make_pair(SGV, DGV));
480 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
481 ValueMap.insert(std::make_pair(SGV, DGV));
482 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
483 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
484 // At this point we know that DGV has LinkOnce, Appending, Weak, or
485 // External linkage. If DGV is Appending, this is an error.
486 if (DGV->hasAppendingLinkage())
487 return Error(Err, "Linking globals named '" + SGV->getName() +
488 " ' with 'weak' and 'appending' linkage is not allowed!");
490 if (SGV->isConstant() != DGV->isConstant())
491 return Error(Err, "Global Variable Collision on '" +
492 SGV->getType()->getDescription() + " %" + SGV->getName() +
493 "' - Global variables differ in const'ness");
495 // Otherwise, just perform the link.
496 ValueMap.insert(std::make_pair(SGV, DGV));
498 // Linkonce+Weak = Weak
499 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
500 DGV->setLinkage(SGV->getLinkage());
502 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
503 // At this point we know that SGV has LinkOnce, Appending, or External
504 // linkage. If SGV is Appending, this is an error.
505 if (SGV->hasAppendingLinkage())
506 return Error(Err, "Linking globals named '" + SGV->getName() +
507 " ' with 'weak' and 'appending' linkage is not allowed!");
509 if (SGV->isConstant() != DGV->isConstant())
510 return Error(Err, "Global Variable Collision on '" +
511 SGV->getType()->getDescription() + " %" + SGV->getName() +
512 "' - Global variables differ in const'ness");
514 if (!SGV->hasLinkOnceLinkage())
515 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
516 ValueMap.insert(std::make_pair(SGV, DGV));
518 } else if (SGV->getLinkage() != DGV->getLinkage()) {
519 return Error(Err, "Global variables named '" + SGV->getName() +
520 "' have different linkage specifiers!");
521 } else if (SGV->hasExternalLinkage()) {
522 // Allow linking two exactly identical external global variables...
523 if (SGV->isConstant() != DGV->isConstant())
524 return Error(Err, "Global Variable Collision on '" +
525 SGV->getType()->getDescription() + " %" + SGV->getName() +
526 "' - Global variables differ in const'ness");
528 if (SGV->getInitializer() != DGV->getInitializer())
529 return Error(Err, "Global Variable Collision on '" +
530 SGV->getType()->getDescription() + " %" + SGV->getName() +
531 "' - External linkage globals have different initializers");
533 ValueMap.insert(std::make_pair(SGV, DGV));
534 } else if (SGV->hasAppendingLinkage()) {
535 // No linking is performed yet. Just insert a new copy of the global, and
536 // keep track of the fact that it is an appending variable in the
537 // AppendingVars map. The name is cleared out so that no linkage is
539 GlobalVariable *NewDGV =
540 new GlobalVariable(SGV->getType()->getElementType(),
541 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
544 // Make sure to remember this mapping...
545 ValueMap.insert(std::make_pair(SGV, NewDGV));
547 // Keep track that this is an appending variable...
548 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
550 assert(0 && "Unknown linkage!");
557 // LinkGlobalInits - Update the initializers in the Dest module now that all
558 // globals that may be referenced are in Dest.
560 static bool LinkGlobalInits(Module *Dest, const Module *Src,
561 std::map<const Value*, Value*> &ValueMap,
564 // Loop over all of the globals in the src module, mapping them over as we go
566 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
567 const GlobalVariable *SGV = I;
569 if (SGV->hasInitializer()) { // Only process initialized GV's
570 // Figure out what the initializer looks like in the dest module...
572 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
574 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
575 if (DGV->hasInitializer()) {
576 if (SGV->hasExternalLinkage()) {
577 if (DGV->getInitializer() != SInit)
578 return Error(Err, "Global Variable Collision on '" +
579 SGV->getType()->getDescription() +"':%"+SGV->getName()+
580 " - Global variables have different initializers");
581 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
582 // Nothing is required, mapped values will take the new global
584 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
585 // Nothing is required, mapped values will take the new global
587 } else if (DGV->hasAppendingLinkage()) {
588 assert(0 && "Appending linkage unimplemented!");
590 assert(0 && "Unknown linkage!");
593 // Copy the initializer over now...
594 DGV->setInitializer(SInit);
601 // LinkFunctionProtos - Link the functions together between the two modules,
602 // without doing function bodies... this just adds external function prototypes
603 // to the Dest function...
605 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
606 std::map<const Value*, Value*> &ValueMap,
608 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
610 // Loop over all of the functions in the src module, mapping them over as we
613 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
614 const Function *SF = I; // SrcFunction
617 // The same named thing is a Function, because the only two things
618 // that may be in a module level symbol table are Global Vars and
619 // Functions, and they both have distinct, nonoverlapping, possible types.
621 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
624 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
625 // Function does not already exist, simply insert an function signature
626 // identical to SF into the dest module...
627 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
628 SF->getName(), Dest);
630 // If the LLVM runtime renamed the function, but it is an externally
631 // visible symbol, DF must be an existing function with internal linkage.
633 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
634 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
636 NewDF->setName(SF->getName()); // Force the name back
637 DF->setName(SF->getName()); // This will cause a renaming
638 assert(NewDF->getName() == SF->getName() &&
639 DF->getName() != SF->getName());
642 // ... and remember this mapping...
643 ValueMap.insert(std::make_pair(SF, NewDF));
644 } else if (SF->isExternal()) {
645 // If SF is external or if both SF & DF are external.. Just link the
646 // external functions, we aren't adding anything.
647 ValueMap.insert(std::make_pair(SF, DF));
648 } else if (DF->isExternal()) { // If DF is external but SF is not...
649 // Link the external functions, update linkage qualifiers
650 ValueMap.insert(std::make_pair(SF, DF));
651 DF->setLinkage(SF->getLinkage());
653 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
654 // At this point we know that DF has LinkOnce, Weak, or External linkage.
655 ValueMap.insert(std::make_pair(SF, DF));
657 // Linkonce+Weak = Weak
658 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
659 DF->setLinkage(SF->getLinkage());
661 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
662 // At this point we know that SF has LinkOnce or External linkage.
663 ValueMap.insert(std::make_pair(SF, DF));
664 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
665 DF->setLinkage(SF->getLinkage());
667 } else if (SF->getLinkage() != DF->getLinkage()) {
668 return Error(Err, "Functions named '" + SF->getName() +
669 "' have different linkage specifiers!");
670 } else if (SF->hasExternalLinkage()) {
671 // The function is defined in both modules!!
672 return Error(Err, "Function '" +
673 SF->getFunctionType()->getDescription() + "':\"" +
674 SF->getName() + "\" - Function is already defined!");
676 assert(0 && "Unknown linkage configuration found!");
682 // LinkFunctionBody - Copy the source function over into the dest function and
683 // fix up references to values. At this point we know that Dest is an external
684 // function, and that Src is not.
686 static bool LinkFunctionBody(Function *Dest, const Function *Src,
687 std::map<const Value*, Value*> &GlobalMap,
689 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
690 std::map<const Value*, Value*> LocalMap; // Map for function local values
692 // Go through and convert function arguments over...
693 Function::aiterator DI = Dest->abegin();
694 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
696 DI->setName(I->getName()); // Copy the name information over...
698 // Add a mapping to our local map
699 LocalMap.insert(std::make_pair(I, DI));
702 // Loop over all of the basic blocks, copying the instructions over...
704 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
705 // Create new basic block and add to mapping and the Dest function...
706 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
707 LocalMap.insert(std::make_pair(I, DBB));
709 // Loop over all of the instructions in the src basic block, copying them
710 // over. Note that this is broken in a strict sense because the cloned
711 // instructions will still be referencing values in the Src module, not
712 // the remapped values. In our case, however, we will not get caught and
713 // so we can delay patching the values up until later...
715 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
717 Instruction *DI = II->clone();
718 DI->setName(II->getName());
719 DBB->getInstList().push_back(DI);
720 LocalMap.insert(std::make_pair(II, DI));
724 // At this point, all of the instructions and values of the function are now
725 // copied over. The only problem is that they are still referencing values in
726 // the Source function as operands. Loop through all of the operands of the
727 // functions and patch them up to point to the local versions...
729 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
730 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
731 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
733 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
739 // LinkFunctionBodies - Link in the function bodies that are defined in the
740 // source module into the DestModule. This consists basically of copying the
741 // function over and fixing up references to values.
743 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
744 std::map<const Value*, Value*> &ValueMap,
747 // Loop over all of the functions in the src module, mapping them over as we
750 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
751 if (!SF->isExternal()) { // No body if function is external
752 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
754 // DF not external SF external?
755 if (DF->isExternal()) {
756 // Only provide the function body if there isn't one already.
757 if (LinkFunctionBody(DF, SF, ValueMap, Err))
765 // LinkAppendingVars - If there were any appending global variables, link them
766 // together now. Return true on error.
768 static bool LinkAppendingVars(Module *M,
769 std::multimap<std::string, GlobalVariable *> &AppendingVars,
770 std::string *ErrorMsg) {
771 if (AppendingVars.empty()) return false; // Nothing to do.
773 // Loop over the multimap of appending vars, processing any variables with the
774 // same name, forming a new appending global variable with both of the
775 // initializers merged together, then rewrite references to the old variables
778 std::vector<Constant*> Inits;
779 while (AppendingVars.size() > 1) {
780 // Get the first two elements in the map...
781 std::multimap<std::string,
782 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
784 // If the first two elements are for different names, there is no pair...
785 // Otherwise there is a pair, so link them together...
786 if (First->first == Second->first) {
787 GlobalVariable *G1 = First->second, *G2 = Second->second;
788 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
789 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
791 // Check to see that they two arrays agree on type...
792 if (T1->getElementType() != T2->getElementType())
793 return Error(ErrorMsg,
794 "Appending variables with different element types need to be linked!");
795 if (G1->isConstant() != G2->isConstant())
796 return Error(ErrorMsg,
797 "Appending variables linked with different const'ness!");
799 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
800 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
802 // Create the new global variable...
804 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
805 /*init*/0, First->first, M);
807 // Merge the initializer...
808 Inits.reserve(NewSize);
809 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
810 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
811 Inits.push_back(cast<Constant>(I->getValues()[i]));
813 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
814 Constant *CV = Constant::getNullValue(T1->getElementType());
815 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
818 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
819 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
820 Inits.push_back(cast<Constant>(I->getValues()[i]));
822 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
823 Constant *CV = Constant::getNullValue(T2->getElementType());
824 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
827 NG->setInitializer(ConstantArray::get(NewType, Inits));
830 // Replace any uses of the two global variables with uses of the new
833 // FIXME: This should rewrite simple/straight-forward uses such as
834 // getelementptr instructions to not use the Cast!
835 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
836 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
837 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
839 // Remove the two globals from the module now...
840 M->getGlobalList().erase(G1);
841 M->getGlobalList().erase(G2);
843 // Put the new global into the AppendingVars map so that we can handle
844 // linking of more than two vars...
847 AppendingVars.erase(First);
854 // LinkModules - This function links two modules together, with the resulting
855 // left module modified to be the composite of the two input modules. If an
856 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
857 // the problem. Upon failure, the Dest module could be in a modified state, and
858 // shouldn't be relied on to be consistent.
860 bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
861 if (Dest->getEndianness() == Module::AnyEndianness)
862 Dest->setEndianness(Src->getEndianness());
863 if (Dest->getPointerSize() == Module::AnyPointerSize)
864 Dest->setPointerSize(Src->getPointerSize());
866 if (Src->getEndianness() != Module::AnyEndianness &&
867 Dest->getEndianness() != Src->getEndianness())
868 std::cerr << "WARNING: Linking two modules of different endianness!\n";
869 if (Src->getPointerSize() != Module::AnyPointerSize &&
870 Dest->getPointerSize() != Src->getPointerSize())
871 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
873 // LinkTypes - Go through the symbol table of the Src module and see if any
874 // types are named in the src module that are not named in the Dst module.
875 // Make sure there are no type name conflicts.
877 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
879 // ValueMap - Mapping of values from what they used to be in Src, to what they
882 std::map<const Value*, Value*> ValueMap;
884 // AppendingVars - Keep track of global variables in the destination module
885 // with appending linkage. After the module is linked together, they are
886 // appended and the module is rewritten.
888 std::multimap<std::string, GlobalVariable *> AppendingVars;
890 // Add all of the appending globals already in the Dest module to
892 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
893 if (I->hasAppendingLinkage())
894 AppendingVars.insert(std::make_pair(I->getName(), I));
896 // Insert all of the globals in src into the Dest module... without linking
897 // initializers (which could refer to functions not yet mapped over).
899 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
901 // Link the functions together between the two modules, without doing function
902 // bodies... this just adds external function prototypes to the Dest
903 // function... We do this so that when we begin processing function bodies,
904 // all of the global values that may be referenced are available in our
907 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
909 // Update the initializers in the Dest module now that all globals that may
910 // be referenced are in Dest.
912 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
914 // Link in the function bodies that are defined in the source module into the
915 // DestModule. This consists basically of copying the function over and
916 // fixing up references to values.
918 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
920 // If there were any appending global variables, link them together now.
922 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;