1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
3 // This file implements the LLVM module linker.
6 // * Merges global variables between the two modules
7 // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
8 // * Merges methods between two modules
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/Linker.h"
13 #include "llvm/Module.h"
14 #include "llvm/Method.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/iOther.h"
22 // Error - Simple wrapper function to conditionally assign to E and return true.
23 // This just makes error return conditions a little bit simpler...
25 static inline bool Error(string *E, string Message) {
30 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
32 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
33 // module to another. This is somewhat sophisticated in that it can
34 // automatically handle constant references correctly as well...
36 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
37 const map<const Value*, Value*> *GlobalMap = 0) {
38 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
39 if (I != LocalMap.end()) return I->second;
42 I = GlobalMap->find(In);
43 if (I != GlobalMap->end()) return I->second;
46 // Check to see if it's a constant that we are interesting in transforming...
47 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
48 if (!isa<DerivedType>(CPV->getType()))
49 return CPV; // Simple constants stay identical...
51 ConstPoolVal *Result = 0;
53 if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
54 const vector<Use> &Ops = CPA->getValues();
55 vector<ConstPoolVal*> Operands(Ops.size());
56 for (unsigned i = 0; i < Ops.size(); ++i)
58 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
59 Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
60 } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
61 const vector<Use> &Ops = CPS->getValues();
62 vector<ConstPoolVal*> Operands(Ops.size());
63 for (unsigned i = 0; i < Ops.size(); ++i)
65 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
66 Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
67 } else if (isa<ConstPoolPointerNull>(CPV)) {
69 } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
70 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
71 Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
73 assert(0 && "Unknown type of derived type constant value!");
76 // Cache the mapping in our local map structure...
77 LocalMap.insert(make_pair(In, CPV));
81 cerr << "Couldn't remap value: " << In << endl;
82 assert(0 && "Couldn't remap value!");
87 // LinkGlobals - Loop through the global variables in the src module and merge
88 // them into the dest module...
90 static bool LinkGlobals(Module *Dest, const Module *Src,
91 map<const Value*, Value*> &ValueMap, string *Err = 0) {
92 // We will need a module level symbol table if the src module has a module
93 // level symbol table...
94 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
96 // Loop over all of the globals in the src module, mapping them over as we go
98 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
99 const GlobalVariable *SGV = *I;
102 // If the global variable has a name, and that name is already in use in the
103 // Dest module, make sure that the name is a compatible global variable...
105 if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
106 // The same named thing is a global variable, because the only two things
107 // that may be in a module level symbol table are Global Vars and Methods,
108 // and they both have distinct, nonoverlapping, possible types.
110 GlobalVariable *DGV = cast<GlobalVariable>(V);
112 // Check to see if the two GV's have the same Const'ness...
113 if (SGV->isConstant() != DGV->isConstant())
114 return Error(Err, "Global Variable Collision on '" +
115 SGV->getType()->getDescription() + "':%" + SGV->getName() +
116 " - Global variables differ in const'ness");
118 // Okay, everything is cool, remember the mapping...
119 ValueMap.insert(make_pair(SGV, DGV));
121 // No linking to be performed, simply create an identical version of the
122 // symbol over in the dest module... the initializer will be filled in
123 // later by LinkGlobalInits...
125 GlobalVariable *DGV =
126 new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
129 // Add the new global to the dest module
130 Dest->getGlobalList().push_back(DGV);
132 // Make sure to remember this mapping...
133 ValueMap.insert(make_pair(SGV, DGV));
140 // LinkGlobalInits - Update the initializers in the Dest module now that all
141 // globals that may be referenced are in Dest.
143 static bool LinkGlobalInits(Module *Dest, const Module *Src,
144 map<const Value*, Value*> &ValueMap,
147 // Loop over all of the globals in the src module, mapping them over as we go
149 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
150 const GlobalVariable *SGV = *I;
152 if (SGV->hasInitializer()) { // Only process initialized GV's
153 // Figure out what the initializer looks like in the dest module...
154 ConstPoolVal *DInit =
155 cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
157 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
158 if (DGV->hasInitializer()) {
159 if (DGV->getInitializer() != DInit)
160 return Error(Err, "Global Variable Collision on '" +
161 SGV->getType()->getDescription() + "':%" +SGV->getName()+
162 " - Global variables have different initializers");
164 // Copy the initializer over now...
165 DGV->setInitializer(DInit);
172 // LinkMethodProtos - Link the methods together between the two modules, without
173 // doing method bodies... this just adds external method prototypes to the Dest
176 static bool LinkMethodProtos(Module *Dest, const Module *Src,
177 map<const Value*, Value*> &ValueMap,
179 // We will need a module level symbol table if the src module has a module
180 // level symbol table...
181 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
183 // Loop over all of the methods in the src module, mapping them over as we go
185 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
186 const Method *SM = *I; // SrcMethod
189 // If the method has a name, and that name is already in use in the
190 // Dest module, make sure that the name is a compatible method...
192 if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
193 // The same named thing is a Method, because the only two things
194 // that may be in a module level symbol table are Global Vars and Methods,
195 // and they both have distinct, nonoverlapping, possible types.
197 Method *DM = cast<Method>(V); // DestMethod
199 // Check to make sure the method is not defined in both modules...
200 if (!SM->isExternal() && !DM->isExternal())
201 return Error(Err, "Method '" +
202 SM->getMethodType()->getDescription() + "':\"" +
203 SM->getName() + "\" - Method is already defined!");
205 // Otherwise, just remember this mapping...
206 ValueMap.insert(make_pair(SM, DM));
208 // Method does not already exist, simply insert an external method
209 // signature identical to SM into the dest module...
210 Method *DM = new Method(SM->getMethodType(), SM->getName());
212 // Add the method signature to the dest module...
213 Dest->getMethodList().push_back(DM);
215 // ... and remember this mapping...
216 ValueMap.insert(make_pair(SM, DM));
222 // LinkMethodBody - Copy the source method over into the dest method and fix up
223 // references to values. At this point we know that Dest is an external method,
224 // and that Src is not.
226 static bool LinkMethodBody(Method *Dest, const Method *Src,
227 const map<const Value*, Value*> &GlobalMap,
229 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
230 map<const Value*, Value*> LocalMap; // Map for method local values
232 // Go through and convert method arguments over...
233 for (Method::ArgumentListType::const_iterator
234 I = Src->getArgumentList().begin(),
235 E = Src->getArgumentList().end(); I != E; ++I) {
236 const MethodArgument *SMA = *I;
238 // Create the new method argument and add to the dest method...
239 MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
240 Dest->getArgumentList().push_back(DMA);
242 // Add a mapping to our local map
243 LocalMap.insert(make_pair(SMA, DMA));
246 // Loop over all of the basic blocks, copying the instructions over...
248 for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
249 const BasicBlock *SBB = *I;
251 // Create new basic block and add to mapping and the Dest method...
252 BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
253 LocalMap.insert(make_pair(SBB, DBB));
255 // Loop over all of the instructions in the src basic block, copying them
256 // over. Note that this is broken in a strict sense because the cloned
257 // instructions will still be referencing values in the Src module, not
258 // the remapped values. In our case, however, we will not get caught and
259 // so we can delay patching the values up until later...
261 for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end();
263 const Instruction *SI = *II;
264 Instruction *DI = SI->clone();
265 DBB->getInstList().push_back(DI);
266 LocalMap.insert(make_pair(SI, DI));
270 // At this point, all of the instructions and values of the method are now
271 // copied over. The only problem is that they are still referencing values
272 // in the Source method as operands. Loop through all of the operands of the
273 // methods and patch them up to point to the local versions...
275 for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
277 Instruction *Inst = *I;
279 for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
281 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
288 // LinkMethodBodies - Link in the method bodies that are defined in the source
289 // module into the DestModule. This consists basically of copying the method
290 // over and fixing up references to values.
292 static bool LinkMethodBodies(Module *Dest, const Module *Src,
293 map<const Value*, Value*> &ValueMap,
296 // Loop over all of the methods in the src module, mapping them over as we go
298 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
299 const Method *SM = *I; // Source Method
300 if (!SM->isExternal()) { // No body if method is external
301 Method *DM = cast<Method>(ValueMap[SM]); // Destination method
303 // DM not external SM external?
304 if (!DM->isExternal()) {
306 *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
307 "' body multiply defined!";
311 if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
319 // LinkModules - This function links two modules together, with the resulting
320 // left module modified to be the composite of the two input modules. If an
321 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
322 // the problem. Upon failure, the Dest module could be in a modified state, and
323 // shouldn't be relied on to be consistent.
325 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
326 // ValueMap - Mapping of values from what they used to be in Src, to what they
329 map<const Value*, Value*> ValueMap;
331 // Insert all of the globals in src into the Dest module... without
333 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
335 // Update the initializers in the Dest module now that all globals that may
336 // be referenced are in Dest.
338 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
340 // Link the methods together between the two modules, without doing method
341 // bodies... this just adds external method prototypes to the Dest method...
342 // We do this so that when we begin processing method bodies, all of the
343 // global values that may be referenced are available in our ValueMap.
345 if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
347 // Link in the method bodies that are defined in the source module into the
348 // DestModule. This consists basically of copying the method over and fixing
349 // up references to values.
351 if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
357 // MangleTypeName - Implement a consistent name-mangling scheme for
361 MangleTypeName(const Type* type)
365 if (type->isPrimitiveType())
367 const string& longName = type->getDescription();
368 mangledName = string(longName.c_str(), (longName.length() < 2)? 1 : 2);
370 else if (type->getPrimitiveID() == Type::PointerTyID)
372 PointerType* ptype = (PointerType*) type;
373 mangledName = string("P_" + MangleTypeName(ptype->getValueType()));
375 else if (type->getPrimitiveID() == Type::StructTyID)
377 StructType* stype = (StructType*) type;
378 mangledName = string("S_");
379 for (unsigned i=0; i < stype->getNumContainedTypes(); ++i)
380 mangledName += string(MangleTypeName(stype->getContainedType(i)));
382 else if (type->getPrimitiveID() == Type::ArrayTyID)
384 ArrayType* atype = (ArrayType*) type;
385 mangledName = string("A_" +MangleTypeName(atype->getElementType()));
387 else if (type->getPrimitiveID() == Type::MethodTyID)
389 MethodType* mtype = (MethodType*) type;
390 mangledName = string("M_") + MangleTypeName(mtype->getReturnType());
391 for (unsigned i=1; i < mtype->getNumContainedTypes(); ++i)
392 mangledName += string(MangleTypeName(mtype->getContainedType(i)));
399 // mangleName - implement a consistent name-mangling scheme for all
400 // externally visible (i.e., global) objects.
401 // privateName should be unique within the module.
404 MangleName(const string& privateName, const Value* V)
406 // Lets drop the P_ before every global name since all globals are ptrs
407 return privateName + "_" +
408 MangleTypeName((isa<GlobalValue>(V)
409 ? cast<GlobalValue>(V)->getType()->getValueType()