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 functions between two modules
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Module.h"
14 #include "llvm/Function.h"
15 #include "llvm/BasicBlock.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Argument.h"
27 // Error - Simple wrapper function to conditionally assign to E and return true.
28 // This just makes error return conditions a little bit simpler...
30 static inline bool Error(string *E, string Message) {
35 // LinkTypes - Go through the symbol table of the Src module and see if any
36 // types are named in the src module that are not named in the Dst module.
37 // Make sure there are no type name conflicts.
39 static bool LinkTypes(Module *Dest, const Module *Src, string *Err = 0) {
40 // No symbol table? Can't have named types.
41 if (!Src->hasSymbolTable()) return false;
43 SymbolTable *DestST = Dest->getSymbolTableSure();
44 const SymbolTable *SrcST = Src->getSymbolTable();
46 // Look for a type plane for Type's...
47 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
48 if (PI == SrcST->end()) return false; // No named types, do nothing.
50 const SymbolTable::VarMap &VM = PI->second;
51 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
53 const string &Name = I->first;
54 const Type *RHS = cast<Type>(I->second);
56 // Check to see if this type name is already in the dest module...
57 const Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
58 if (Entry) { // Yup, the value already exists...
59 if (Entry != RHS) // If it's the same, noop. Otherwise, error.
60 return Error(Err, "Type named '" + Name +
61 "' of different shape in modules.\n Src='" +
62 Entry->getDescription() + "'.\n Dst='" +
63 RHS->getDescription() + "'");
64 } else { // Type not in dest module. Add it now.
65 // TODO: FIXME WHEN TYPES AREN'T CONST
66 DestST->insert(Name, const_cast<Type*>(RHS));
72 static void PrintMap(const map<const Value*, Value*> &M) {
73 for (map<const Value*, Value*>::const_iterator I = M.begin(), E = M.end();
75 cerr << " Fr: " << (void*)I->first << " ";
77 cerr << " To: " << (void*)I->second << " ";
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...
88 static Value *RemapOperand(const Value *In, map<const Value*, Value*> &LocalMap,
89 const map<const Value*, Value*> *GlobalMap = 0) {
90 map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
91 if (I != LocalMap.end()) return I->second;
94 I = GlobalMap->find(In);
95 if (I != GlobalMap->end()) return I->second;
98 // Check to see if it's a constant that we are interesting in transforming...
99 if (const Constant *CPV = dyn_cast<Constant>(In)) {
100 if (!isa<DerivedType>(CPV->getType()))
101 return const_cast<Constant*>(CPV); // Simple constants stay identical...
103 Constant *Result = 0;
105 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
106 const std::vector<Use> &Ops = CPA->getValues();
107 std::vector<Constant*> Operands(Ops.size());
108 for (unsigned i = 0; i < Ops.size(); ++i)
110 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
111 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
112 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
113 const std::vector<Use> &Ops = CPS->getValues();
114 std::vector<Constant*> Operands(Ops.size());
115 for (unsigned i = 0; i < Ops.size(); ++i)
117 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
118 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
119 } else if (isa<ConstantPointerNull>(CPV)) {
120 Result = const_cast<Constant*>(CPV);
121 } else if (const ConstantPointerRef *CPR =
122 dyn_cast<ConstantPointerRef>(CPV)) {
123 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
124 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
126 assert(0 && "Unknown type of derived type constant value!");
129 // Cache the mapping in our local map structure...
130 LocalMap.insert(std::make_pair(In, const_cast<Constant*>(CPV)));
134 cerr << "XXX LocalMap: \n";
138 cerr << "XXX GlobalMap: \n";
139 PrintMap(*GlobalMap);
142 cerr << "Couldn't remap value: " << (void*)In << " ";
145 assert(0 && "Couldn't remap value!");
150 // LinkGlobals - Loop through the global variables in the src module and merge
151 // them into the dest module...
153 static bool LinkGlobals(Module *Dest, const Module *Src,
154 map<const Value*, Value*> &ValueMap, string *Err = 0) {
155 // We will need a module level symbol table if the src module has a module
156 // level symbol table...
157 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
159 // Loop over all of the globals in the src module, mapping them over as we go
161 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
162 const GlobalVariable *SGV = I;
165 // If the global variable has a name, and that name is already in use in the
166 // Dest module, make sure that the name is a compatible global variable...
168 if (SGV->hasExternalLinkage() && SGV->hasName() &&
169 (V = ST->lookup(SGV->getType(), SGV->getName())) &&
170 cast<GlobalVariable>(V)->hasExternalLinkage()) {
171 // The same named thing is a global variable, because the only two things
172 // that may be in a module level symbol table are Global Vars and
173 // Functions, and they both have distinct, nonoverlapping, possible types.
175 GlobalVariable *DGV = cast<GlobalVariable>(V);
177 // Check to see if the two GV's have the same Const'ness...
178 if (SGV->isConstant() != DGV->isConstant())
179 return Error(Err, "Global Variable Collision on '" +
180 SGV->getType()->getDescription() + "':%" + SGV->getName() +
181 " - Global variables differ in const'ness");
183 // Okay, everything is cool, remember the mapping...
184 ValueMap.insert(std::make_pair(SGV, DGV));
186 // No linking to be performed, simply create an identical version of the
187 // symbol over in the dest module... the initializer will be filled in
188 // later by LinkGlobalInits...
190 GlobalVariable *DGV =
191 new GlobalVariable(SGV->getType()->getElementType(), SGV->isConstant(),
192 SGV->hasInternalLinkage(), 0, SGV->getName());
194 // Add the new global to the dest module
195 Dest->getGlobalList().push_back(DGV);
197 // Make sure to remember this mapping...
198 ValueMap.insert(std::make_pair(SGV, DGV));
205 // LinkGlobalInits - Update the initializers in the Dest module now that all
206 // globals that may be referenced are in Dest.
208 static bool LinkGlobalInits(Module *Dest, const Module *Src,
209 map<const Value*, Value*> &ValueMap,
212 // Loop over all of the globals in the src module, mapping them over as we go
214 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
215 const GlobalVariable *SGV = I;
217 if (SGV->hasInitializer()) { // Only process initialized GV's
218 // Figure out what the initializer looks like in the dest module...
220 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
222 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
223 if (DGV->hasInitializer() && SGV->hasExternalLinkage() &&
224 DGV->hasExternalLinkage()) {
225 if (DGV->getInitializer() != DInit)
226 return Error(Err, "Global Variable Collision on '" +
227 SGV->getType()->getDescription() + "':%" +SGV->getName()+
228 " - Global variables have different initializers");
230 // Copy the initializer over now...
231 DGV->setInitializer(DInit);
238 // LinkFunctionProtos - Link the functions together between the two modules,
239 // without doing function bodies... this just adds external function prototypes
240 // to the Dest function...
242 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
243 map<const Value*, Value*> &ValueMap,
245 // We will need a module level symbol table if the src module has a module
246 // level symbol table...
247 SymbolTable *ST = Src->getSymbolTable() ? Dest->getSymbolTableSure() : 0;
249 // Loop over all of the functions in the src module, mapping them over as we
252 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
253 const Function *SF = I; // SrcFunction
256 // If the function has a name, and that name is already in use in the Dest
257 // module, make sure that the name is a compatible function...
259 if (SF->hasExternalLinkage() && SF->hasName() &&
260 (V = ST->lookup(SF->getType(), SF->getName())) &&
261 cast<Function>(V)->hasExternalLinkage()) {
262 // The same named thing is a Function, because the only two things
263 // that may be in a module level symbol table are Global Vars and
264 // Functions, and they both have distinct, nonoverlapping, possible types.
266 Function *DF = cast<Function>(V); // DestFunction
268 // Check to make sure the function is not defined in both modules...
269 if (!SF->isExternal() && !DF->isExternal())
270 return Error(Err, "Function '" +
271 SF->getFunctionType()->getDescription() + "':\"" +
272 SF->getName() + "\" - Function is already defined!");
274 // Otherwise, just remember this mapping...
275 ValueMap.insert(std::make_pair(SF, DF));
277 // Function does not already exist, simply insert an external function
278 // signature identical to SF into the dest module...
279 Function *DF = new Function(SF->getFunctionType(),
280 SF->hasInternalLinkage(),
283 // Add the function signature to the dest module...
284 Dest->getFunctionList().push_back(DF);
286 // ... and remember this mapping...
287 ValueMap.insert(std::make_pair(SF, DF));
293 // LinkFunctionBody - Copy the source function over into the dest function and
294 // fix up references to values. At this point we know that Dest is an external
295 // function, and that Src is not.
297 static bool LinkFunctionBody(Function *Dest, const Function *Src,
298 const map<const Value*, Value*> &GlobalMap,
300 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
301 map<const Value*, Value*> LocalMap; // Map for function local values
303 // Go through and convert function arguments over...
304 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
306 // Create the new function argument and add to the dest function...
307 Argument *DFA = new Argument(I->getType(), I->getName());
308 Dest->getArgumentList().push_back(DFA);
310 // Add a mapping to our local map
311 LocalMap.insert(std::make_pair(I, DFA));
314 // Loop over all of the basic blocks, copying the instructions over...
316 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
317 // Create new basic block and add to mapping and the Dest function...
318 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
319 LocalMap.insert(std::make_pair(I, DBB));
321 // Loop over all of the instructions in the src basic block, copying them
322 // over. Note that this is broken in a strict sense because the cloned
323 // instructions will still be referencing values in the Src module, not
324 // the remapped values. In our case, however, we will not get caught and
325 // so we can delay patching the values up until later...
327 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
329 Instruction *DI = II->clone();
330 DI->setName(II->getName());
331 DBB->getInstList().push_back(DI);
332 LocalMap.insert(std::make_pair(II, DI));
336 // At this point, all of the instructions and values of the function are now
337 // copied over. The only problem is that they are still referencing values in
338 // the Source function as operands. Loop through all of the operands of the
339 // functions and patch them up to point to the local versions...
341 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
343 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
345 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
351 // LinkFunctionBodies - Link in the function bodies that are defined in the
352 // source module into the DestModule. This consists basically of copying the
353 // function over and fixing up references to values.
355 static bool LinkFunctionBodies(Module *Dest, const Module *Src,
356 map<const Value*, Value*> &ValueMap,
359 // Loop over all of the functions in the src module, mapping them over as we
362 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
363 if (!SF->isExternal()) { // No body if function is external
364 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
366 // DF not external SF external?
367 if (!DF->isExternal()) {
369 *Err = "Function '" + (SF->hasName() ? SF->getName() : string("")) +
370 "' body multiply defined!";
374 if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
382 // LinkModules - This function links two modules together, with the resulting
383 // left module modified to be the composite of the two input modules. If an
384 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
385 // the problem. Upon failure, the Dest module could be in a modified state, and
386 // shouldn't be relied on to be consistent.
388 bool LinkModules(Module *Dest, const Module *Src, string *ErrorMsg = 0) {
390 // LinkTypes - Go through the symbol table of the Src module and see if any
391 // types are named in the src module that are not named in the Dst module.
392 // Make sure there are no type name conflicts.
394 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
396 // ValueMap - Mapping of values from what they used to be in Src, to what they
399 map<const Value*, Value*> ValueMap;
401 // Insert all of the globals in src into the Dest module... without
403 if (LinkGlobals(Dest, Src, ValueMap, ErrorMsg)) return true;
405 // Update the initializers in the Dest module now that all globals that may
406 // be referenced are in Dest.
408 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
410 // Link the functions together between the two modules, without doing function
411 // bodies... this just adds external function prototypes to the Dest
412 // function... We do this so that when we begin processing function bodies,
413 // all of the global values that may be referenced are available in our
416 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
418 // Link in the function bodies that are defined in the source module into the
419 // DestModule. This consists basically of copying the function over and
420 // fixing up references to values.
422 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;