Fix linking a function with qualifiers to a external function declaration:
[oota-llvm.git] / lib / VMCore / 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 functions between two modules
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Module.h"
14 #include "llvm/SymbolTable.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/iOther.h"
17 #include "llvm/Constants.h"
18
19 // Error - Simple wrapper function to conditionally assign to E and return true.
20 // This just makes error return conditions a little bit simpler...
21 //
22 static inline bool Error(std::string *E, std::string Message) {
23   if (E) *E = Message;
24   return true;
25 }
26
27 // LinkTypes - Go through the symbol table of the Src module and see if any
28 // types are named in the src module that are not named in the Dst module.
29 // Make sure there are no type name conflicts.
30 //
31 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
32   SymbolTable       *DestST = &Dest->getSymbolTable();
33   const SymbolTable *SrcST  = &Src->getSymbolTable();
34
35   // Look for a type plane for Type's...
36   SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
37   if (PI == SrcST->end()) return false;  // No named types, do nothing.
38
39   const SymbolTable::VarMap &VM = PI->second;
40   for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
41        I != E; ++I) {
42     const std::string &Name = I->first;
43     const Type *RHS = cast<Type>(I->second);
44
45     // Check to see if this type name is already in the dest module...
46     const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
47     if (Entry && !isa<OpaqueType>(Entry)) {  // Yup, the value already exists...
48       if (Entry != RHS) {
49         if (OpaqueType *OT = dyn_cast<OpaqueType>(const_cast<Type*>(RHS))) {
50           OT->refineAbstractTypeTo(Entry);
51         } else {
52           // If it's the same, noop.  Otherwise, error.
53           return Error(Err, "Type named '" + Name + 
54                        "' of different shape in modules.\n  Src='" + 
55                        Entry->getDescription() + "'.\n  Dst='" + 
56                        RHS->getDescription() + "'");
57         }
58       }
59     } else {                       // Type not in dest module.  Add it now.
60       if (Entry) {
61         OpaqueType *OT = cast<OpaqueType>(const_cast<Type*>(Entry));
62         OT->refineAbstractTypeTo(RHS);
63       }
64
65       // TODO: FIXME WHEN TYPES AREN'T CONST
66       DestST->insert(Name, const_cast<Type*>(RHS));
67     }
68   }
69   return false;
70 }
71
72 static void PrintMap(const std::map<const Value*, Value*> &M) {
73   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
74        I != E; ++I) {
75     std::cerr << " Fr: " << (void*)I->first << " ";
76     I->first->dump();
77     std::cerr << " To: " << (void*)I->second << " ";
78     I->second->dump();
79     std::cerr << "\n";
80   }
81 }
82
83
84 // RemapOperand - Use LocalMap and GlobalMap to convert references from one
85 // module to another.  This is somewhat sophisticated in that it can
86 // automatically handle constant references correctly as well...
87 //
88 static Value *RemapOperand(const Value *In,
89                            std::map<const Value*, Value*> &LocalMap,
90                            std::map<const Value*, Value*> *GlobalMap) {
91   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
92   if (I != LocalMap.end()) return I->second;
93
94   if (GlobalMap) {
95     I = GlobalMap->find(In);
96     if (I != GlobalMap->end()) return I->second;
97   }
98
99   // Check to see if it's a constant that we are interesting in transforming...
100   if (const Constant *CPV = dyn_cast<Constant>(In)) {
101     if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
102       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
103
104     Constant *Result = 0;
105
106     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
107       const std::vector<Use> &Ops = CPA->getValues();
108       std::vector<Constant*> Operands(Ops.size());
109       for (unsigned i = 0, e = Ops.size(); i != e; ++i)
110         Operands[i] = 
111           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
112       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
113     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
114       const std::vector<Use> &Ops = CPS->getValues();
115       std::vector<Constant*> Operands(Ops.size());
116       for (unsigned i = 0; i < Ops.size(); ++i)
117         Operands[i] = 
118           cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
119       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
120     } else if (isa<ConstantPointerNull>(CPV)) {
121       Result = const_cast<Constant*>(CPV);
122     } else if (const ConstantPointerRef *CPR =
123                       dyn_cast<ConstantPointerRef>(CPV)) {
124       Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
125       Result = ConstantPointerRef::get(cast<GlobalValue>(V));
126     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
127       if (CE->getOpcode() == Instruction::GetElementPtr) {
128         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
129         std::vector<Constant*> Indices;
130         Indices.reserve(CE->getNumOperands()-1);
131         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
132           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
133                                                         LocalMap, GlobalMap)));
134
135         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
136       } else if (CE->getNumOperands() == 1) {
137         // Cast instruction
138         assert(CE->getOpcode() == Instruction::Cast);
139         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
140         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
141       } else if (CE->getNumOperands() == 2) {
142         // Binary operator...
143         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
144         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
145
146         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
147                                    cast<Constant>(V2));        
148       } else {
149         assert(0 && "Unknown constant expr type!");
150       }
151
152     } else {
153       assert(0 && "Unknown type of derived type constant value!");
154     }
155
156     // Cache the mapping in our local map structure...
157     if (GlobalMap)
158       GlobalMap->insert(std::make_pair(In, Result));
159     else
160       LocalMap.insert(std::make_pair(In, Result));
161     return Result;
162   }
163
164   std::cerr << "XXX LocalMap: \n";
165   PrintMap(LocalMap);
166
167   if (GlobalMap) {
168     std::cerr << "XXX GlobalMap: \n";
169     PrintMap(*GlobalMap);
170   }
171
172   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
173   assert(0 && "Couldn't remap value!");
174   return 0;
175 }
176
177
178 // LinkGlobals - Loop through the global variables in the src module and merge
179 // them into the dest module...
180 //
181 static bool LinkGlobals(Module *Dest, const Module *Src,
182                         std::map<const Value*, Value*> &ValueMap,
183                         std::string *Err) {
184   // We will need a module level symbol table if the src module has a module
185   // level symbol table...
186   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
187   
188   // Loop over all of the globals in the src module, mapping them over as we go
189   //
190   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
191     const GlobalVariable *SGV = I;
192     GlobalVariable *DGV = 0;
193     if (SGV->hasName()) {
194       // A same named thing is a global variable, because the only two things
195       // that may be in a module level symbol table are Global Vars and
196       // Functions, and they both have distinct, nonoverlapping, possible types.
197       // 
198       DGV = cast_or_null<GlobalVariable>(ST->lookup(SGV->getType(),
199                                                     SGV->getName()));
200     }
201
202     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
203            "Global must either be external or have an initializer!");
204
205     bool SGExtern = SGV->isExternal();
206     bool DGExtern = DGV ? DGV->isExternal() : false;
207
208     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
209       // No linking to be performed, simply create an identical version of the
210       // symbol over in the dest module... the initializer will be filled in
211       // later by LinkGlobalInits...
212       //
213       DGV = new GlobalVariable(SGV->getType()->getElementType(),
214                                SGV->isConstant(), SGV->getLinkage(), /*init*/0,
215                                SGV->getName(), Dest);
216
217       // Make sure to remember this mapping...
218       ValueMap.insert(std::make_pair(SGV, DGV));
219     } else if (!SGExtern && !DGExtern && SGV->getLinkage() !=DGV->getLinkage()){
220       return Error(Err, "Global variables named '" + SGV->getName() +
221                    "' have different linkage specifiers!");
222     } else if (SGV->hasExternalLinkage() || SGV->hasLinkOnceLinkage() ||
223                SGV->hasAppendingLinkage()) {
224       // If the global variable has a name, and that name is already in use in
225       // the Dest module, make sure that the name is a compatible global
226       // variable...
227       //
228       // Check to see if the two GV's have the same Const'ness...
229       if (SGV->isConstant() != DGV->isConstant())
230         return Error(Err, "Global Variable Collision on '" + 
231                      SGV->getType()->getDescription() + "':%" + SGV->getName() +
232                      " - Global variables differ in const'ness");
233       if (DGExtern)
234         DGV->setLinkage(SGV->getLinkage());
235
236       // Okay, everything is cool, remember the mapping...
237       ValueMap.insert(std::make_pair(SGV, DGV));
238     } else {
239       assert(0 && "Unknown linkage!");
240     }
241   }
242   return false;
243 }
244
245
246 // LinkGlobalInits - Update the initializers in the Dest module now that all
247 // globals that may be referenced are in Dest.
248 //
249 static bool LinkGlobalInits(Module *Dest, const Module *Src,
250                             std::map<const Value*, Value*> &ValueMap,
251                             std::string *Err) {
252
253   // Loop over all of the globals in the src module, mapping them over as we go
254   //
255   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
256     const GlobalVariable *SGV = I;
257
258     if (SGV->hasInitializer()) {      // Only process initialized GV's
259       // Figure out what the initializer looks like in the dest module...
260       Constant *SInit =
261         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
262
263       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);    
264       if (DGV->hasInitializer()) {
265         assert(SGV->getLinkage() == DGV->getLinkage());
266         if (SGV->hasExternalLinkage()) {
267           if (DGV->getInitializer() != SInit)
268             return Error(Err, "Global Variable Collision on '" + 
269                          SGV->getType()->getDescription() +"':%"+SGV->getName()+
270                          " - Global variables have different initializers");
271         } else if (DGV->hasLinkOnceLinkage()) {
272           // Nothing is required, mapped values will take the new global
273           // automatically.
274         } else if (DGV->hasAppendingLinkage()) {
275           assert(0 && "Appending linkage unimplemented!");
276         } else {
277           assert(0 && "Unknown linkage!");
278         }
279       } else {
280         // Copy the initializer over now...
281         DGV->setInitializer(SInit);
282       }
283     }
284   }
285   return false;
286 }
287
288 // LinkFunctionProtos - Link the functions together between the two modules,
289 // without doing function bodies... this just adds external function prototypes
290 // to the Dest function...
291 //
292 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
293                                std::map<const Value*, Value*> &ValueMap,
294                                std::string *Err) {
295   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
296   
297   // Loop over all of the functions in the src module, mapping them over as we
298   // go
299   //
300   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
301     const Function *SF = I;   // SrcFunction
302     Function *DF = 0;
303     if (SF->hasName())
304       // The same named thing is a Function, because the only two things
305       // that may be in a module level symbol table are Global Vars and
306       // Functions, and they both have distinct, nonoverlapping, possible types.
307       // 
308       DF = cast_or_null<Function>(ST->lookup(SF->getType(), SF->getName()));
309
310     bool SFExtern = SF->isExternal();
311     bool DFExtern = DF ? DF->isExternal() : false;
312
313     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
314       // Function does not already exist, simply insert an function signature
315       // identical to SF into the dest module...
316       Function *DF = new Function(SF->getFunctionType(), SF->getLinkage(),
317                                   SF->getName(), Dest);
318
319       // ... and remember this mapping...
320       ValueMap.insert(std::make_pair(SF, DF));
321     } else if (SF->getLinkage() == GlobalValue::AppendingLinkage) {
322       return Error(Err, "Functions named '" + SF->getName() +
323                    "' have appending linkage!");
324     } else if (!SFExtern && !DFExtern && SF->getLinkage() != DF->getLinkage()) {
325       return Error(Err, "Functions named '" + SF->getName() +
326                    "' have different linkage specifiers!");
327     } else if (SF->getLinkage() == GlobalValue::ExternalLinkage) {
328       // If the function has a name, and that name is already in use in the Dest
329       // module, make sure that the name is a compatible function...
330       //
331       // Check to make sure the function is not defined in both modules...
332       if (!SF->isExternal() && !DF->isExternal())
333         return Error(Err, "Function '" + 
334                      SF->getFunctionType()->getDescription() + "':\"" + 
335                      SF->getName() + "\" - Function is already defined!");
336       
337       if (DFExtern)
338         DF->setLinkage(SF->getLinkage());
339       
340       // Otherwise, just remember this mapping...
341       ValueMap.insert(std::make_pair(SF, DF));
342     } else if (SF->getLinkage() == GlobalValue::LinkOnceLinkage) {
343       // Completely ignore the source function.
344       ValueMap.insert(std::make_pair(SF, DF));
345     }
346   }
347   return false;
348 }
349
350 // LinkFunctionBody - Copy the source function over into the dest function and
351 // fix up references to values.  At this point we know that Dest is an external
352 // function, and that Src is not.
353 //
354 static bool LinkFunctionBody(Function *Dest, const Function *Src,
355                              std::map<const Value*, Value*> &GlobalMap,
356                              std::string *Err) {
357   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
358   std::map<const Value*, Value*> LocalMap;   // Map for function local values
359
360   // Go through and convert function arguments over...
361   Function::aiterator DI = Dest->abegin();
362   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
363        I != E; ++I, ++DI) {
364     DI->setName(I->getName());  // Copy the name information over...
365
366     // Add a mapping to our local map
367     LocalMap.insert(std::make_pair(I, DI));
368   }
369
370   // Loop over all of the basic blocks, copying the instructions over...
371   //
372   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
373     // Create new basic block and add to mapping and the Dest function...
374     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
375     LocalMap.insert(std::make_pair(I, DBB));
376
377     // Loop over all of the instructions in the src basic block, copying them
378     // over.  Note that this is broken in a strict sense because the cloned
379     // instructions will still be referencing values in the Src module, not
380     // the remapped values.  In our case, however, we will not get caught and 
381     // so we can delay patching the values up until later...
382     //
383     for (BasicBlock::const_iterator II = I->begin(), IE = I->end(); 
384          II != IE; ++II) {
385       Instruction *DI = II->clone();
386       DI->setName(II->getName());
387       DBB->getInstList().push_back(DI);
388       LocalMap.insert(std::make_pair(II, DI));
389     }
390   }
391
392   // At this point, all of the instructions and values of the function are now
393   // copied over.  The only problem is that they are still referencing values in
394   // the Source function as operands.  Loop through all of the operands of the
395   // functions and patch them up to point to the local versions...
396   //
397   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
398     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
399       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
400            OI != OE; ++OI)
401         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
402
403   return false;
404 }
405
406
407 // LinkFunctionBodies - Link in the function bodies that are defined in the
408 // source module into the DestModule.  This consists basically of copying the
409 // function over and fixing up references to values.
410 //
411 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
412                                std::map<const Value*, Value*> &ValueMap,
413                                std::string *Err) {
414
415   // Loop over all of the functions in the src module, mapping them over as we
416   // go
417   //
418   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
419     if (!SF->isExternal()) {                  // No body if function is external
420       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
421
422       // DF not external SF external?
423       if (!DF->isExternal()) {
424         if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
425         if (Err)
426           *Err = "Function '" + (SF->hasName() ? SF->getName() :std::string(""))
427                + "' body multiply defined!";
428         return true;
429       }
430
431       if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
432     }
433   }
434   return false;
435 }
436
437
438
439 // LinkModules - This function links two modules together, with the resulting
440 // left module modified to be the composite of the two input modules.  If an
441 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
442 // the problem.  Upon failure, the Dest module could be in a modified state, and
443 // shouldn't be relied on to be consistent.
444 //
445 bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
446
447   // LinkTypes - Go through the symbol table of the Src module and see if any
448   // types are named in the src module that are not named in the Dst module.
449   // Make sure there are no type name conflicts.
450   //
451   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
452
453   // ValueMap - Mapping of values from what they used to be in Src, to what they
454   // are now in Dest.
455   //
456   std::map<const Value*, Value*> ValueMap;
457
458   // Insert all of the globals in src into the Dest module... without
459   // initializers
460   if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
461
462   // Link the functions together between the two modules, without doing function
463   // bodies... this just adds external function prototypes to the Dest
464   // function...  We do this so that when we begin processing function bodies,
465   // all of the global values that may be referenced are available in our
466   // ValueMap.
467   //
468   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
469
470   // Update the initializers in the Dest module now that all globals that may
471   // be referenced are in Dest.
472   //
473   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
474
475   // Link in the function bodies that are defined in the source module into the
476   // DestModule.  This consists basically of copying the function over and
477   // fixing up references to values.
478   //
479   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
480
481   return false;
482 }
483