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"
20 // Error - Simple wrapper function to conditionally assign to E and return true.
21 // This just makes error return conditions a little bit simpler...
23 static inline bool Error(string *E, string Message) {
28 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
30 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
31 // module to another. This is somewhat sophisticated in that it can
32 // automatically handle constant references correctly as well...
34 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
35 const map<const Value*, Value*> *GlobalMap = 0) {
36 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
37 if (I != LocalMap.end()) return I->second;
40 I = GlobalMap->find(In);
41 if (I != GlobalMap->end()) return I->second;
44 // Check to see if it's a constant that we are interesting in transforming...
45 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
46 if (!isa<DerivedType>(CPV->getType()))
47 return CPV; // Simple constants stay identical...
49 ConstPoolVal *Result = 0;
51 if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
52 const vector<Use> &Ops = CPA->getValues();
53 vector<ConstPoolVal*> Operands(Ops.size());
54 for (unsigned i = 0; i < Ops.size(); ++i)
56 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
57 Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
58 } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
59 const vector<Use> &Ops = CPS->getValues();
60 vector<ConstPoolVal*> Operands(Ops.size());
61 for (unsigned i = 0; i < Ops.size(); ++i)
63 cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
64 Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
65 } else if (isa<ConstPoolPointerNull>(CPV)) {
67 } else if (ConstPoolPointerReference *CPR =
68 dyn_cast<ConstPoolPointerReference>(CPV)) {
69 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
70 Result = ConstPoolPointerReference::get(cast<GlobalValue>(V));
72 assert(0 && "Unknown type of derived type constant value!");
75 // Cache the mapping in our local map structure...
76 LocalMap.insert(make_pair(In, CPV));
80 cerr << "Couldn't remap value: " << In << endl;
81 assert(0 && "Couldn't remap value!");
86 // LinkGlobals - Loop through the global variables in the src module and merge
87 // them into the dest module...
89 static bool LinkGlobals(Module *Dest, const Module *Src,
90 map<const Value*, Value*> &ValueMap, string *Err = 0) {
91 // We will need a module level symbol table if the src module has a module
92 // level symbol table...
93 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
95 // Loop over all of the globals in the src module, mapping them over as we go
97 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
98 const GlobalVariable *SGV = *I;
101 // If the global variable has a name, and that name is already in use in the
102 // Dest module, make sure that the name is a compatible global variable...
104 if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
105 // The same named thing is a global variable, because the only two things
106 // that may be in a module level symbol table are Global Vars and Methods,
107 // and they both have distinct, nonoverlapping, possible types.
109 GlobalVariable *DGV = cast<GlobalVariable>(V);
111 // Check to see if the two GV's have the same Const'ness...
112 if (SGV->isConstant() != DGV->isConstant())
113 return Error(Err, "Global Variable Collision on '" +
114 SGV->getType()->getDescription() + "':%" + SGV->getName() +
115 " - Global variables differ in const'ness");
117 // Okay, everything is cool, remember the mapping...
118 ValueMap.insert(make_pair(SGV, DGV));
120 // No linking to be performed, simply create an identical version of the
121 // symbol over in the dest module... the initializer will be filled in
122 // later by LinkGlobalInits...
124 GlobalVariable *DGV =
125 new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
128 // Add the new global to the dest module
129 Dest->getGlobalList().push_back(DGV);
131 // Make sure to remember this mapping...
132 ValueMap.insert(make_pair(SGV, DGV));
139 // LinkGlobalInits - Update the initializers in the Dest module now that all
140 // globals that may be referenced are in Dest.
142 static bool LinkGlobalInits(Module *Dest, const Module *Src,
143 map<const Value*, Value*> &ValueMap,
146 // Loop over all of the globals in the src module, mapping them over as we go
148 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
149 const GlobalVariable *SGV = *I;
151 if (SGV->hasInitializer()) { // Only process initialized GV's
152 // Figure out what the initializer looks like in the dest module...
153 ConstPoolVal *DInit =
154 cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
156 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
157 if (DGV->hasInitializer()) {
158 if (DGV->getInitializer() != DInit)
159 return Error(Err, "Global Variable Collision on '" +
160 SGV->getType()->getDescription() + "':%" +SGV->getName()+
161 " - Global variables have different initializers");
163 // Copy the initializer over now...
164 DGV->setInitializer(DInit);
171 // LinkMethodProtos - Link the methods together between the two modules, without
172 // doing method bodies... this just adds external method prototypes to the Dest
175 static bool LinkMethodProtos(Module *Dest, const Module *Src,
176 map<const Value*, Value*> &ValueMap,
178 // We will need a module level symbol table if the src module has a module
179 // level symbol table...
180 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
182 // Loop over all of the methods in the src module, mapping them over as we go
184 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
185 const Method *SM = *I; // SrcMethod
188 // If the method has a name, and that name is already in use in the
189 // Dest module, make sure that the name is a compatible method...
191 if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
192 // The same named thing is a Method, because the only two things
193 // that may be in a module level symbol table are Global Vars and Methods,
194 // and they both have distinct, nonoverlapping, possible types.
196 Method *DM = cast<Method>(V); // DestMethod
198 // Check to make sure the method is not defined in both modules...
199 if (!SM->isExternal() && !DM->isExternal())
200 return Error(Err, "Method '" +
201 SM->getMethodType()->getDescription() + "':\"" +
202 SM->getName() + "\" - Method is already defined!");
204 // Otherwise, just remember this mapping...
205 ValueMap.insert(make_pair(SM, DM));
207 // Method does not already exist, simply insert an external method
208 // signature identical to SM into the dest module...
209 Method *DM = new Method(SM->getMethodType(), SM->getName());
211 // Add the method signature to the dest module...
212 Dest->getMethodList().push_back(DM);
214 // ... and remember this mapping...
215 ValueMap.insert(make_pair(SM, DM));
221 // LinkMethodBody - Copy the source method over into the dest method and fix up
222 // references to values. At this point we know that Dest is an external method,
223 // and that Src is not.
225 static bool LinkMethodBody(Method *Dest, const Method *Src,
226 const map<const Value*, Value*> &GlobalMap,
228 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
229 map<const Value*, Value*> LocalMap; // Map for method local values
231 // Go through and convert method arguments over...
232 for (Method::ArgumentListType::const_iterator
233 I = Src->getArgumentList().begin(),
234 E = Src->getArgumentList().end(); I != E; ++I) {
235 const MethodArgument *SMA = *I;
237 // Create the new method argument and add to the dest method...
238 MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
239 Dest->getArgumentList().push_back(DMA);
241 // Add a mapping to our local map
242 LocalMap.insert(make_pair(SMA, DMA));
245 // Loop over all of the basic blocks, copying the instructions over...
247 for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
248 const BasicBlock *SBB = *I;
250 // Create new basic block and add to mapping and the Dest method...
251 BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
252 LocalMap.insert(make_pair(SBB, DBB));
254 // Loop over all of the instructions in the src basic block, copying them
255 // over. Note that this is broken in a strict sense because the cloned
256 // instructions will still be referencing values in the Src module, not
257 // the remapped values. In our case, however, we will not get caught and
258 // so we can delay patching the values up until later...
260 for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end();
262 const Instruction *SI = *II;
263 Instruction *DI = SI->clone();
264 DBB->getInstList().push_back(DI);
265 LocalMap.insert(make_pair(SI, DI));
269 // At this point, all of the instructions and values of the method are now
270 // copied over. The only problem is that they are still referencing values
271 // in the Source method as operands. Loop through all of the operands of the
272 // methods and patch them up to point to the local versions...
274 for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
276 Instruction *Inst = *I;
278 for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
280 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
287 // LinkMethodBodies - Link in the method bodies that are defined in the source
288 // module into the DestModule. This consists basically of copying the method
289 // over and fixing up references to values.
291 static bool LinkMethodBodies(Module *Dest, const Module *Src,
292 map<const Value*, Value*> &ValueMap,
295 // Loop over all of the methods in the src module, mapping them over as we go
297 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
298 const Method *SM = *I; // Source Method
299 Method *DM = cast<Method>(ValueMap[SM]); // Destination method
301 assert(DM && DM->isExternal() && "LinkMethodProtos failed!");
302 if (!SM->isExternal()) // External methods are already done
303 if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
310 // LinkModules - This function links two modules together, with the resulting
311 // left module modified to be the composite of the two input modules. If an
312 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
313 // the problem. Upon failure, the Dest module could be in a modified state, and
314 // shouldn't be relied on to be consistent.
316 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
317 // ValueMap - Mapping of values from what they used to be in Src, to what they
320 map<const Value*, Value*> ValueMap;
322 // Insert all of the globals in src into the Dest module... without
324 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
326 // Update the initializers in the Dest module now that all globals that may
327 // be referenced are in Dest.
329 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
331 // Link the methods together between the two modules, without doing method
332 // bodies... this just adds external method prototypes to the Dest method...
333 // We do this so that when we begin processing method bodies, all of the
334 // global values that may be referenced are available in our ValueMap.
336 if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
338 // Link in the method bodies that are defined in the source module into the
339 // DestModule. This consists basically of copying the method over and fixing
340 // up references to values.
342 if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;