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