Add extra code for debugging linker problems
[oota-llvm.git] / lib / Transforms / Utils / Linker.cpp
1 //===- Linker.cpp - Module Linker Implementation --------------------------===//
2 //
3 // This file implements the LLVM module linker.
4 //
5 // Specifically, this:
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
9 //
10 //===----------------------------------------------------------------------===//
11
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"
19
20 // Error - Simple wrapper function to conditionally assign to E and return true.
21 // This just makes error return conditions a little bit simpler...
22 //
23 static inline bool Error(string *E, string Message) {
24   if (E) *E = Message;
25   return true;
26 }
27
28 #include "llvm/Assembly/Writer.h" // TODO: REMOVE
29
30 static void PrintMap(const map<const Value*, Value*> &M) {
31   for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
32        I != E; ++I) {
33     cerr << " Fr: " << (void*)I->first << " " << I->first 
34          << " To: " << (void*)I->second << " " << I->second << endl;
35   }
36 }
37
38
39 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
40 // module to another.  This is somewhat sophisticated in that it can
41 // automatically handle constant references correctly as well...
42 //
43 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
44                            const map<const Value*, Value*> *GlobalMap = 0) {
45   map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
46   if (I != LocalMap.end()) return I->second;
47
48   if (GlobalMap) {
49     I = GlobalMap->find(In);
50     if (I != GlobalMap->end()) return I->second;
51   }
52
53   // Check to see if it's a constant that we are interesting in transforming...
54   if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(In)) {
55     if (!isa<DerivedType>(CPV->getType()))
56       return CPV;              // Simple constants stay identical...
57
58     ConstPoolVal *Result = 0;
59
60     if (ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CPV)) {
61       const vector<Use> &Ops = CPA->getValues();
62       vector<ConstPoolVal*> Operands(Ops.size());
63       for (unsigned i = 0; i < Ops.size(); ++i)
64         Operands[i] = 
65           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
66       Result = ConstPoolArray::get(cast<ArrayType>(CPA->getType()), Operands);
67     } else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CPV)) {
68       const vector<Use> &Ops = CPS->getValues();
69       vector<ConstPoolVal*> Operands(Ops.size());
70       for (unsigned i = 0; i < Ops.size(); ++i)
71         Operands[i] = 
72           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
73       Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
74     } else if (isa<ConstPoolPointerNull>(CPV)) {
75       Result = CPV;
76     } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(CPV)) {
77       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
78       Result = ConstPoolPointerRef::get(cast<GlobalValue>(V));
79     } else {
80       assert(0 && "Unknown type of derived type constant value!");
81     }
82
83     // Cache the mapping in our local map structure...
84     LocalMap.insert(make_pair(In, CPV));
85     return Result;
86   }
87
88   cerr << "XXX LocalMap: \n";
89   PrintMap(LocalMap);
90
91   if (GlobalMap) {
92     cerr << "XXX GlobalMap: \n";
93     PrintMap(*GlobalMap);
94   }
95
96   cerr << "Couldn't remap value: " << (void*)In << " " << In << endl;
97   assert(0 && "Couldn't remap value!");
98   return 0;
99 }
100
101
102 // LinkGlobals - Loop through the global variables in the src module and merge
103 // them into the dest module...
104 //
105 static bool LinkGlobals(Module *Dest, const Module *Src,
106                         map<const Value*, Value*> &ValueMap, string *Err = 0) {
107   // We will need a module level symbol table if the src module has a module
108   // level symbol table...
109   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
110   
111   // Loop over all of the globals in the src module, mapping them over as we go
112   //
113   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
114     const GlobalVariable *SGV = *I;
115     Value *V;
116
117     // If the global variable has a name, and that name is already in use in the
118     // Dest module, make sure that the name is a compatible global variable...
119     //
120     if (SGV->hasName() && (V = ST->lookup(SGV->getType(), SGV->getName()))) {
121       // The same named thing is a global variable, because the only two things
122       // that may be in a module level symbol table are Global Vars and Methods,
123       // and they both have distinct, nonoverlapping, possible types.
124       // 
125       GlobalVariable *DGV = cast<GlobalVariable>(V);
126
127       // Check to see if the two GV's have the same Const'ness...
128       if (SGV->isConstant() != DGV->isConstant())
129         return Error(Err, "Global Variable Collision on '" + 
130                      SGV->getType()->getDescription() + "':%" + SGV->getName() +
131                      " - Global variables differ in const'ness");
132
133       // Okay, everything is cool, remember the mapping...
134       ValueMap.insert(make_pair(SGV, DGV));
135     } else {
136       // No linking to be performed, simply create an identical version of the
137       // symbol over in the dest module... the initializer will be filled in
138       // later by LinkGlobalInits...
139       //
140       GlobalVariable *DGV = 
141         new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
142                            0, SGV->getName());
143
144       // Add the new global to the dest module
145       Dest->getGlobalList().push_back(DGV);
146
147       // Make sure to remember this mapping...
148       ValueMap.insert(make_pair(SGV, DGV));
149     }
150   }
151   return false;
152 }
153
154
155 // LinkGlobalInits - Update the initializers in the Dest module now that all
156 // globals that may be referenced are in Dest.
157 //
158 static bool LinkGlobalInits(Module *Dest, const Module *Src,
159                             map<const Value*, Value*> &ValueMap,
160                             string *Err = 0) {
161
162   // Loop over all of the globals in the src module, mapping them over as we go
163   //
164   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
165     const GlobalVariable *SGV = *I;
166
167     if (SGV->hasInitializer()) {      // Only process initialized GV's
168       // Figure out what the initializer looks like in the dest module...
169       ConstPoolVal *DInit =
170         cast<ConstPoolVal>(RemapOperand(SGV->getInitializer(), ValueMap));
171
172       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
173       if (DGV->hasInitializer()) {
174         if (DGV->getInitializer() != DInit)
175           return Error(Err, "Global Variable Collision on '" + 
176                        SGV->getType()->getDescription() + "':%" +SGV->getName()+
177                        " - Global variables have different initializers");
178       } else {
179         // Copy the initializer over now...
180         DGV->setInitializer(DInit);
181       }
182     }
183   }
184   return false;
185 }
186
187 // LinkMethodProtos - Link the methods together between the two modules, without
188 // doing method bodies... this just adds external method prototypes to the Dest
189 // method...
190 //
191 static bool LinkMethodProtos(Module *Dest, const Module *Src,
192                              map<const Value*, Value*> &ValueMap,
193                              string *Err = 0) {
194   // We will need a module level symbol table if the src module has a module
195   // level symbol table...
196   SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
197   
198   // Loop over all of the methods in the src module, mapping them over as we go
199   //
200   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
201     const Method *SM = *I;   // SrcMethod
202     Value *V;
203
204     // If the method has a name, and that name is already in use in the
205     // Dest module, make sure that the name is a compatible method...
206     //
207     if (SM->hasName() && (V = ST->lookup(SM->getType(), SM->getName()))) {
208       // The same named thing is a Method, because the only two things
209       // that may be in a module level symbol table are Global Vars and Methods,
210       // and they both have distinct, nonoverlapping, possible types.
211       // 
212       Method *DM = cast<Method>(V);   // DestMethod
213
214       // Check to make sure the method is not defined in both modules...
215       if (!SM->isExternal() && !DM->isExternal())
216         return Error(Err, "Method '" + 
217                      SM->getMethodType()->getDescription() + "':\"" + 
218                      SM->getName() + "\" - Method is already defined!");
219
220       // Otherwise, just remember this mapping...
221       ValueMap.insert(make_pair(SM, DM));
222     } else {
223       // Method does not already exist, simply insert an external method
224       // signature identical to SM into the dest module...
225       Method *DM = new Method(SM->getMethodType(), SM->getName());
226
227       // Add the method signature to the dest module...
228       Dest->getMethodList().push_back(DM);
229
230       // ... and remember this mapping...
231       ValueMap.insert(make_pair(SM, DM));
232     }
233   }
234   return false;
235 }
236
237 // LinkMethodBody - Copy the source method over into the dest method and fix up
238 // references to values.  At this point we know that Dest is an external method,
239 // and that Src is not.
240 //
241 static bool LinkMethodBody(Method *Dest, const Method *Src,
242                            const map<const Value*, Value*> &GlobalMap,
243                            string *Err = 0) {
244   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
245   map<const Value*, Value*> LocalMap;   // Map for method local values
246
247   // Go through and convert method arguments over...
248   for (Method::ArgumentListType::const_iterator 
249          I = Src->getArgumentList().begin(),
250          E = Src->getArgumentList().end(); I != E; ++I) {
251     const MethodArgument *SMA = *I;
252
253     // Create the new method argument and add to the dest method...
254     MethodArgument *DMA = new MethodArgument(SMA->getType(), SMA->getName());
255     Dest->getArgumentList().push_back(DMA);
256
257     // Add a mapping to our local map
258     LocalMap.insert(make_pair(SMA, DMA));
259   }
260
261   // Loop over all of the basic blocks, copying the instructions over...
262   //
263   for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
264     const BasicBlock *SBB = *I;
265
266     // Create new basic block and add to mapping and the Dest method...
267     BasicBlock *DBB = new BasicBlock(SBB->getName(), Dest);
268     LocalMap.insert(make_pair(SBB, DBB));
269
270     // Loop over all of the instructions in the src basic block, copying them
271     // over.  Note that this is broken in a strict sense because the cloned
272     // instructions will still be referencing values in the Src module, not
273     // the remapped values.  In our case, however, we will not get caught and 
274     // so we can delay patching the values up until later...
275     //
276     for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end(); 
277          II != IE; ++II) {
278       const Instruction *SI = *II;
279       Instruction *DI = SI->clone();
280       DI->setName(SI->getName());
281       DBB->getInstList().push_back(DI);
282       LocalMap.insert(make_pair(SI, DI));
283     }
284   }
285
286   // At this point, all of the instructions and values of the method are now
287   // copied over.  The only problem is that they are still referencing values
288   // in the Source method as operands.  Loop through all of the operands of the
289   // methods and patch them up to point to the local versions...
290   //
291   for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
292        I != E; ++I) {
293     Instruction *Inst = *I;
294
295     for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
296          OI != OE; ++OI)
297       *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
298   }
299
300   return false;
301 }
302
303
304 // LinkMethodBodies - Link in the method bodies that are defined in the source
305 // module into the DestModule.  This consists basically of copying the method
306 // over and fixing up references to values.
307 //
308 static bool LinkMethodBodies(Module *Dest, const Module *Src,
309                              map<const Value*, Value*> &ValueMap,
310                              string *Err = 0) {
311
312   // Loop over all of the methods in the src module, mapping them over as we go
313   //
314   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
315     const Method *SM = *I;                     // Source Method
316     if (!SM->isExternal()) {                   // No body if method is external
317       Method *DM = cast<Method>(ValueMap[SM]); // Destination method
318
319       // DM not external SM external?
320       if (!DM->isExternal()) {
321         if (Err)
322           *Err = "Method '" + (SM->hasName() ? SM->getName() : string("")) +
323                  "' body multiply defined!";
324         return true;
325       }
326
327       if (LinkMethodBody(DM, SM, ValueMap, Err)) return true;
328     }
329   }
330   return false;
331 }
332
333
334
335 // LinkModules - This function links two modules together, with the resulting
336 // left module modified to be the composite of the two input modules.  If an
337 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
338 // the problem.  Upon failure, the Dest module could be in a modified state, and
339 // shouldn't be relied on to be consistent.
340 //
341 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
342   // ValueMap - Mapping of values from what they used to be in Src, to what they
343   // are now in Dest.
344   //
345   map<const Value*, Value*> ValueMap;
346
347   // Insert all of the globals in src into the Dest module... without
348   // initializers
349   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
350
351   // Update the initializers in the Dest module now that all globals that may
352   // be referenced are in Dest.
353   //
354   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
355
356   // Link the methods together between the two modules, without doing method
357   // bodies... this just adds external method prototypes to the Dest method...
358   // We do this so that when we begin processing method bodies, all of the
359   // global values that may be referenced are available in our ValueMap.
360   //
361   if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
362
363   // Link in the method bodies that are defined in the source module into the
364   // DestModule.  This consists basically of copying the method over and fixing
365   // up references to values.
366   //
367   if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
368
369   return false;
370 }
371