Implement linking of global variable constant references
[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 // 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...
33 //
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;
38
39   if (GlobalMap) {
40     I = GlobalMap->find(In);
41     if (I != GlobalMap->end()) return I->second;
42   }
43
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...
48
49     ConstPoolVal *Result = 0;
50
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)
55         Operands[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)
62         Operands[i] = 
63           cast<ConstPoolVal>(RemapOperand(Ops[i], LocalMap, GlobalMap));
64       Result = ConstPoolStruct::get(cast<StructType>(CPS->getType()), Operands);
65     } else if (isa<ConstPoolPointerNull>(CPV)) {
66       Result = 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));
71     } else {
72       assert(0 && "Unknown type of derived type constant value!");
73     }
74
75     // Cache the mapping in our local map structure...
76     LocalMap.insert(make_pair(In, CPV));
77     return Result;
78   }
79   
80   cerr << "Couldn't remap value: " << In << endl;
81   assert(0 && "Couldn't remap value!");
82   return 0;
83 }
84
85
86 // LinkGlobals - Loop through the global variables in the src module and merge
87 // them into the dest module...
88 //
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;
94   
95   // Loop over all of the globals in the src module, mapping them over as we go
96   //
97   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
98     const GlobalVariable *SGV = *I;
99     Value *V;
100
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...
103     //
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.
108       // 
109       GlobalVariable *DGV = cast<GlobalVariable>(V);
110
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");
116
117       // Okay, everything is cool, remember the mapping...
118       ValueMap.insert(make_pair(SGV, DGV));
119     } else {
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...
123       //
124       GlobalVariable *DGV = 
125         new GlobalVariable(SGV->getType()->getValueType(), SGV->isConstant(),
126                            0, SGV->getName());
127
128       // Add the new global to the dest module
129       Dest->getGlobalList().push_back(DGV);
130
131       // Make sure to remember this mapping...
132       ValueMap.insert(make_pair(SGV, DGV));
133     }
134   }
135   return false;
136 }
137
138
139 // LinkGlobalInits - Update the initializers in the Dest module now that all
140 // globals that may be referenced are in Dest.
141 //
142 static bool LinkGlobalInits(Module *Dest, const Module *Src,
143                             map<const Value*, Value*> &ValueMap,
144                             string *Err = 0) {
145
146   // Loop over all of the globals in the src module, mapping them over as we go
147   //
148   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
149     const GlobalVariable *SGV = *I;
150
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));
155
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");
162       } else {
163         // Copy the initializer over now...
164         DGV->setInitializer(DInit);
165       }
166     }
167   }
168   return false;
169 }
170
171 // LinkMethodProtos - Link the methods together between the two modules, without
172 // doing method bodies... this just adds external method prototypes to the Dest
173 // method...
174 //
175 static bool LinkMethodProtos(Module *Dest, const Module *Src,
176                              map<const Value*, Value*> &ValueMap,
177                              string *Err = 0) {
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;
181   
182   // Loop over all of the methods in the src module, mapping them over as we go
183   //
184   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
185     const Method *SM = *I;   // SrcMethod
186     Value *V;
187
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...
190     //
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.
195       // 
196       Method *DM = cast<Method>(V);   // DestMethod
197
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!");
203
204       // Otherwise, just remember this mapping...
205       ValueMap.insert(make_pair(SM, DM));
206     } else {
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());
210
211       // Add the method signature to the dest module...
212       Dest->getMethodList().push_back(DM);
213
214       // ... and remember this mapping...
215       ValueMap.insert(make_pair(SM, DM));
216     }
217   }
218   return false;
219 }
220
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.
224 //
225 static bool LinkMethodBody(Method *Dest, const Method *Src,
226                            const map<const Value*, Value*> &GlobalMap,
227                            string *Err = 0) {
228   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
229   map<const Value*, Value*> LocalMap;   // Map for method local values
230
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;
236
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);
240
241     // Add a mapping to our local map
242     LocalMap.insert(make_pair(SMA, DMA));
243   }
244
245   // Loop over all of the basic blocks, copying the instructions over...
246   //
247   for (Method::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
248     const BasicBlock *SBB = *I;
249
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));
253
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...
259     //
260     for (BasicBlock::const_iterator II = SBB->begin(), IE = SBB->end(); 
261          II != IE; ++II) {
262       const Instruction *SI = *II;
263       Instruction *DI = SI->clone();
264       DBB->getInstList().push_back(DI);
265       LocalMap.insert(make_pair(SI, DI));
266     }
267   }
268
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...
273   //
274   for (Method::inst_iterator I = Dest->inst_begin(), E = Dest->inst_end();
275        I != E; ++I) {
276     Instruction *Inst = *I;
277
278     for (Instruction::op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
279          OI != OE; ++OI)
280       *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
281   }
282
283   return false;
284 }
285
286
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.
290 //
291 static bool LinkMethodBodies(Module *Dest, const Module *Src,
292                              map<const Value*, Value*> &ValueMap,
293                              string *Err = 0) {
294
295   // Loop over all of the methods in the src module, mapping them over as we go
296   //
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
300
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;
304   }
305   return false;
306 }
307
308
309
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.
315 //
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
318   // are now in Dest.
319   //
320   map<const Value*, Value*> ValueMap;
321
322   // Insert all of the globals in src into the Dest module... without
323   // initializers
324   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
325
326   // Update the initializers in the Dest module now that all globals that may
327   // be referenced are in Dest.
328   //
329   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
330
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.
335   //
336   if (LinkMethodProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
337
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.
341   //
342   if (LinkMethodBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
343
344   return false;
345 }