blob: 24449ea9f691769a9165c5c35af5dfc29c8d7b6e [file] [log] [blame]
Chris Lattner52f7e902001-10-13 07:03:50 +00001//===- Linker.cpp - Module Linker Implementation --------------------------===//
2//
3// This file implements the LLVM module linker.
4//
5// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +00006// * Merges global variables between the two modules
7// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00008// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10//===----------------------------------------------------------------------===//
11
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000012#include "llvm/Transforms/Utils/Linker.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000013#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000014#include "llvm/SymbolTable.h"
15#include "llvm/DerivedTypes.h"
16#include "llvm/iOther.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000017#include "llvm/Constants.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000018
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//
Chris Lattner8166e6e2003-05-13 21:33:43 +000022static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000023 if (E) *E = Message;
24 return true;
25}
26
Chris Lattner4c00e532003-05-15 16:30:55 +000027// ResolveTypes - Attempt to link the two specified types together. Return true
28// if there is an error and they cannot yet be linked.
29//
Chris Lattnere76c57a2003-08-22 06:07:12 +000030static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
31 SymbolTable *DestST, const std::string &Name) {
32 if (DestTy == SrcTy) return false; // If already equal, noop
33
Chris Lattner4c00e532003-05-15 16:30:55 +000034 // Does the type already exist in the module?
35 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000036 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
37 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000038 } else {
39 return true; // Cannot link types... neither is opaque and not-equal
40 }
41 } else { // Type not in dest module. Add it now.
42 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000043 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
44 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000045 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000046 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000047 }
48 return false;
49}
50
Chris Lattner43f4ba82003-08-22 19:12:55 +000051static const FunctionType *getFT(const PATypeHolder &TH) {
52 return cast<FunctionType>(TH.get());
53}
Chris Lattner9732be72003-08-22 20:16:48 +000054static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000055 return cast<StructType>(TH.get());
56}
Chris Lattnere76c57a2003-08-22 06:07:12 +000057
58// RecursiveResolveTypes - This is just like ResolveTypes, except that it
59// recurses down into derived types, merging the used types if the parent types
60// are compatible.
61//
Chris Lattnere3092c92003-08-23 21:25:54 +000062static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
63 const PATypeHolder &SrcTy,
64 SymbolTable *DestST, const std::string &Name,
65 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000066 const Type *SrcTyT = SrcTy.get();
67 const Type *DestTyT = DestTy.get();
68 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000069
70 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000071 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
72 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000073
74 // Two types cannot be resolved together if they are of different primitive
75 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +000076 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +000077
78 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +000079 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000080 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +000081 if (cast<FunctionType>(DestTyT)->isVarArg() !=
82 cast<FunctionType>(SrcTyT)->isVarArg())
83 return true;
84 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +000085 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
86 getFT(SrcTy)->getContainedType(i), DestST, "",
87 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +000088 return true;
89 return false;
90 }
91 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +000092 if (getST(DestTy)->getNumContainedTypes() !=
93 getST(SrcTy)->getNumContainedTypes()) return 1;
94 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +000095 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
96 getST(SrcTy)->getContainedType(i), DestST, "",
97 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +000098 return true;
99 return false;
100 }
101 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000102 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
103 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000104 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000105 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
106 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000107 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000108 case Type::PointerTyID: {
109 // If this is a pointer type, check to see if we have already seen it. If
110 // so, we are in a recursive branch. Cut off the search now. We cannot use
111 // an associative container for this search, because the type pointers (keys
112 // in the container) change whenever types get resolved...
113 //
114 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
115 if (Pointers[i].first == DestTy)
116 return Pointers[i].second != SrcTy;
117
118 // Otherwise, add the current pointers to the vector to stop recursion on
119 // this pair.
120 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
121 bool Result =
122 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
123 cast<PointerType>(SrcTy.get())->getElementType(),
124 DestST, "", Pointers);
125 Pointers.pop_back();
126 return Result;
127 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000128 default: assert(0 && "Unexpected type!"); return true;
129 }
130}
131
Chris Lattnere3092c92003-08-23 21:25:54 +0000132static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
133 const PATypeHolder &SrcTy,
134 SymbolTable *DestST, const std::string &Name){
135 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
136 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
137}
138
Chris Lattnere76c57a2003-08-22 06:07:12 +0000139
Chris Lattner2c236f32001-11-03 05:18:24 +0000140// LinkTypes - Go through the symbol table of the Src module and see if any
141// types are named in the src module that are not named in the Dst module.
142// Make sure there are no type name conflicts.
143//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000144static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000145 SymbolTable *DestST = &Dest->getSymbolTable();
146 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000147
148 // Look for a type plane for Type's...
149 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
150 if (PI == SrcST->end()) return false; // No named types, do nothing.
151
Chris Lattner4c00e532003-05-15 16:30:55 +0000152 // Some types cannot be resolved immediately becuse they depend on other types
153 // being resolved to each other first. This contains a list of types we are
154 // waiting to recheck.
155 std::vector<std::string> DelayedTypesToResolve;
156
Chris Lattner2c236f32001-11-03 05:18:24 +0000157 const SymbolTable::VarMap &VM = PI->second;
158 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
159 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000160 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000161 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000162
163 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000164 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000165
Chris Lattner4c00e532003-05-15 16:30:55 +0000166 if (ResolveTypes(Entry, RHS, DestST, Name)) {
167 // They look different, save the types 'till later to resolve.
168 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000169 }
170 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000171
172 // Iteratively resolve types while we can...
173 while (!DelayedTypesToResolve.empty()) {
174 // Loop over all of the types, attempting to resolve them if possible...
175 unsigned OldSize = DelayedTypesToResolve.size();
176
Chris Lattnere76c57a2003-08-22 06:07:12 +0000177 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000178 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
179 const std::string &Name = DelayedTypesToResolve[i];
180 Type *T1 = cast<Type>(VM.find(Name)->second);
181 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
182 if (!ResolveTypes(T2, T1, DestST, Name)) {
183 // We are making progress!
184 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
185 --i;
186 }
187 }
188
189 // Did we not eliminate any types?
190 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000191 // Attempt to resolve subelements of types. This allows us to merge these
192 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000193 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
194 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000195 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
196 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000197
198 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
199 // We are making progress!
200 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
201
202 // Go back to the main loop, perhaps we can resolve directly by name
203 // now...
204 break;
205 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000206 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000207
208 // If we STILL cannot resolve the types, then there is something wrong.
209 // Report the error.
210 if (DelayedTypesToResolve.size() == OldSize) {
211 // Build up an error message of all of the mismatched types.
212 std::string ErrorMessage;
213 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
214 const std::string &Name = DelayedTypesToResolve[i];
215 const Type *T1 = cast<Type>(VM.find(Name)->second);
216 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
217 ErrorMessage += " Type named '" + Name +
218 "' conflicts.\n Src='" + T1->getDescription() +
219 "'.\n Dest='" + T2->getDescription() + "'\n";
220 }
221 return Error(Err, "Type conflict between types in modules:\n" +
222 ErrorMessage);
223 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000224 }
225 }
226
227
Chris Lattner2c236f32001-11-03 05:18:24 +0000228 return false;
229}
230
Chris Lattner5c2d3352003-01-30 19:53:34 +0000231static void PrintMap(const std::map<const Value*, Value*> &M) {
232 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000233 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000234 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000235 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000236 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000237 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000238 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000239 }
240}
241
242
Chris Lattner5c377c52001-10-14 23:29:15 +0000243// RemapOperand - Use LocalMap and GlobalMap to convert references from one
244// module to another. This is somewhat sophisticated in that it can
245// automatically handle constant references correctly as well...
246//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000247static Value *RemapOperand(const Value *In,
248 std::map<const Value*, Value*> &LocalMap,
249 std::map<const Value*, Value*> *GlobalMap) {
250 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000251 if (I != LocalMap.end()) return I->second;
252
253 if (GlobalMap) {
254 I = GlobalMap->find(In);
255 if (I != GlobalMap->end()) return I->second;
256 }
257
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000258 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000259 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000260 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000261 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000262
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000263 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000264
Chris Lattner18961502002-06-25 16:12:52 +0000265 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000266 const std::vector<Use> &Ops = CPA->getValues();
267 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000268 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000269 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000270 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
271 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000272 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000273 const std::vector<Use> &Ops = CPS->getValues();
274 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000275 for (unsigned i = 0; i < Ops.size(); ++i)
276 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000277 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
278 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
279 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000280 Result = const_cast<Constant*>(CPV);
281 } else if (const ConstantPointerRef *CPR =
282 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000283 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000284 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000285 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000286 if (CE->getOpcode() == Instruction::GetElementPtr) {
287 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
288 std::vector<Constant*> Indices;
289 Indices.reserve(CE->getNumOperands()-1);
290 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
291 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
292 LocalMap, GlobalMap)));
293
294 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
295 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000296 // Cast instruction
297 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000298 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000299 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattner6cdf1972002-07-18 00:13:08 +0000300 } else if (CE->getNumOperands() == 2) {
301 // Binary operator...
302 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
303 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
304
305 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnere8e46052002-07-30 18:54:22 +0000306 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000307 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000308 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000309 }
310
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000311 } else {
312 assert(0 && "Unknown type of derived type constant value!");
313 }
314
315 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000316 if (GlobalMap)
317 GlobalMap->insert(std::make_pair(In, Result));
318 else
319 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000320 return Result;
321 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000322
Chris Lattner5c2d3352003-01-30 19:53:34 +0000323 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000324 PrintMap(LocalMap);
325
326 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000327 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000328 PrintMap(*GlobalMap);
329 }
330
Chris Lattner5c2d3352003-01-30 19:53:34 +0000331 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000332 assert(0 && "Couldn't remap value!");
333 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000334}
335
Chris Lattnerfcd02342003-08-23 20:31:10 +0000336/// FindGlobalNamed - Look in the specified symbol table for a global with the
337/// specified name and type. If an exactly matching global does not exist, see
338/// if there is a global which is "type compatible" with the specified
339/// name/type. This allows us to resolve things like '%x = global int*' with
340/// '%x = global opaque*'.
341///
342static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
343 SymbolTable *ST) {
344 // See if an exact match exists in the symbol table...
345 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
346
347 // It doesn't exist exactly, scan through all of the type planes in the symbol
348 // table, checking each of them for a type-compatible version.
349 //
350 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I) {
351 SymbolTable::VarMap &VM = I->second;
352 // Does this type plane contain an entry with the specified name?
353 SymbolTable::type_iterator TI = VM.find(Name);
354 if (TI != VM.end()) {
355 // Determine whether we can fold the two types together, resolving them.
356 // If so, we can use this value.
357 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
358 return cast<GlobalValue>(TI->second);
359 }
360 }
361 return 0; // Otherwise, nothing could be found.
362}
363
Chris Lattner5c377c52001-10-14 23:29:15 +0000364
365// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000366// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000367//
368static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000369 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000370 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000371 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000372 // We will need a module level symbol table if the src module has a module
373 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000374 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000375
376 // Loop over all of the globals in the src module, mapping them over as we go
377 //
378 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000379 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000380 GlobalVariable *DGV = 0;
381 if (SGV->hasName()) {
382 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000383 // that may be in a module level symbol table are Global Vars and
384 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000385 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000386 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
387 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000388 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000389
Chris Lattner4ad02e72003-04-16 20:28:45 +0000390 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
391 "Global must either be external or have an initializer!");
392
Chris Lattner0fec08e2003-04-21 21:07:05 +0000393 bool SGExtern = SGV->isExternal();
394 bool DGExtern = DGV ? DGV->isExternal() : false;
395
Chris Lattner4ad02e72003-04-16 20:28:45 +0000396 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
397 // No linking to be performed, simply create an identical version of the
398 // symbol over in the dest module... the initializer will be filled in
399 // later by LinkGlobalInits...
400 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000401 GlobalVariable *NewDGV =
402 new GlobalVariable(SGV->getType()->getElementType(),
403 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
404 SGV->getName(), Dest);
405
406 // If the LLVM runtime renamed the global, but it is an externally visible
407 // symbol, DGV must be an existing global with internal linkage. Rename
408 // it.
409 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
410 assert(DGV && DGV->getName() == SGV->getName() &&
411 DGV->hasInternalLinkage());
412 DGV->setName("");
413 NewDGV->setName(SGV->getName()); // Force the name back
414 DGV->setName(SGV->getName()); // This will cause a renaming
415 assert(NewDGV->getName() == SGV->getName() &&
416 DGV->getName() != SGV->getName());
417 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000418
419 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000420 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000421 if (SGV->hasAppendingLinkage())
422 // Keep track that this is an appending variable...
423 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
424
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000425 } else if (SGV->isExternal()) {
426 // If SGV is external or if both SGV & DGV are external.. Just link the
427 // external globals, we aren't adding anything.
428 ValueMap.insert(std::make_pair(SGV, DGV));
429
430 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
431 ValueMap.insert(std::make_pair(SGV, DGV));
432 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
433 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000434 return Error(Err, "Global variables named '" + SGV->getName() +
435 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000436 } else if (SGV->hasExternalLinkage()) {
437 // Allow linking two exactly identical external global variables...
438 if (SGV->isConstant() != DGV->isConstant() ||
439 SGV->getInitializer() != DGV->getInitializer())
440 return Error(Err, "Global Variable Collision on '" +
441 SGV->getType()->getDescription() + " %" + SGV->getName() +
442 "' - Global variables differ in const'ness");
443 ValueMap.insert(std::make_pair(SGV, DGV));
444 } else if (SGV->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000445 // If the global variable has a name, and that name is already in use in
446 // the Dest module, make sure that the name is a compatible global
447 // variable...
448 //
Chris Lattner5c377c52001-10-14 23:29:15 +0000449 // Check to see if the two GV's have the same Const'ness...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000450 if (SGV->isConstant() != DGV->isConstant())
Chris Lattner5c377c52001-10-14 23:29:15 +0000451 return Error(Err, "Global Variable Collision on '" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000452 SGV->getType()->getDescription() + " %" + SGV->getName() +
453 "' - Global variables differ in const'ness");
Chris Lattner0fec08e2003-04-21 21:07:05 +0000454
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000455 // Okay, everything is cool, remember the mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000456 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000457 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000458 // No linking is performed yet. Just insert a new copy of the global, and
459 // keep track of the fact that it is an appending variable in the
460 // AppendingVars map. The name is cleared out so that no linkage is
461 // performed.
462 GlobalVariable *NewDGV =
463 new GlobalVariable(SGV->getType()->getElementType(),
464 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
465 "", Dest);
466
467 // Make sure to remember this mapping...
468 ValueMap.insert(std::make_pair(SGV, NewDGV));
469
470 // Keep track that this is an appending variable...
471 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000472 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000473 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000474 }
475 }
476 return false;
477}
478
479
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000480// LinkGlobalInits - Update the initializers in the Dest module now that all
481// globals that may be referenced are in Dest.
482//
483static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000484 std::map<const Value*, Value*> &ValueMap,
485 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000486
487 // Loop over all of the globals in the src module, mapping them over as we go
488 //
489 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000490 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000491
492 if (SGV->hasInitializer()) { // Only process initialized GV's
493 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000494 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000495 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000496
497 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000498 if (DGV->hasInitializer()) {
499 assert(SGV->getLinkage() == DGV->getLinkage());
500 if (SGV->hasExternalLinkage()) {
501 if (DGV->getInitializer() != SInit)
502 return Error(Err, "Global Variable Collision on '" +
503 SGV->getType()->getDescription() +"':%"+SGV->getName()+
504 " - Global variables have different initializers");
505 } else if (DGV->hasLinkOnceLinkage()) {
506 // Nothing is required, mapped values will take the new global
507 // automatically.
508 } else if (DGV->hasAppendingLinkage()) {
509 assert(0 && "Appending linkage unimplemented!");
510 } else {
511 assert(0 && "Unknown linkage!");
512 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000513 } else {
514 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000515 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000516 }
517 }
518 }
519 return false;
520}
Chris Lattner5c377c52001-10-14 23:29:15 +0000521
Chris Lattner79df7c02002-03-26 18:01:55 +0000522// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000523// without doing function bodies... this just adds external function prototypes
524// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000525//
Chris Lattner79df7c02002-03-26 18:01:55 +0000526static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000527 std::map<const Value*, Value*> &ValueMap,
528 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000529 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000530
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000531 // Loop over all of the functions in the src module, mapping them over as we
532 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000533 //
534 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000535 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000536 Function *DF = 0;
537 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000538 // The same named thing is a Function, because the only two things
539 // that may be in a module level symbol table are Global Vars and
540 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000541 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000542 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
543 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000544
Chris Lattner4ad02e72003-04-16 20:28:45 +0000545 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000546 // Function does not already exist, simply insert an function signature
547 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000548 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
549 SF->getName(), Dest);
550
551 // If the LLVM runtime renamed the function, but it is an externally
552 // visible symbol, DF must be an existing function with internal linkage.
553 // Rename it.
554 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
555 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
556 DF->setName("");
557 NewDF->setName(SF->getName()); // Force the name back
558 DF->setName(SF->getName()); // This will cause a renaming
559 assert(NewDF->getName() == SF->getName() &&
560 DF->getName() != SF->getName());
561 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000562
563 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000564 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000565 } else if (SF->isExternal()) {
566 // If SF is external or if both SF & DF are external.. Just link the
567 // external functions, we aren't adding anything.
568 ValueMap.insert(std::make_pair(SF, DF));
569 } else if (DF->isExternal()) { // If DF is external but SF is not...
570 // Link the external functions, update linkage qualifiers
571 ValueMap.insert(std::make_pair(SF, DF));
572 DF->setLinkage(SF->getLinkage());
573
574 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000575 return Error(Err, "Functions named '" + SF->getName() +
576 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000577 } else if (SF->hasExternalLinkage()) {
578 // The function is defined in both modules!!
579 return Error(Err, "Function '" +
580 SF->getFunctionType()->getDescription() + "':\"" +
581 SF->getName() + "\" - Function is already defined!");
582 } else if (SF->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000583 // Completely ignore the source function.
Chris Lattner18961502002-06-25 16:12:52 +0000584 ValueMap.insert(std::make_pair(SF, DF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000585 } else {
586 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000587 }
588 }
589 return false;
590}
591
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000592// LinkFunctionBody - Copy the source function over into the dest function and
593// fix up references to values. At this point we know that Dest is an external
594// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000595//
Chris Lattner79df7c02002-03-26 18:01:55 +0000596static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000597 std::map<const Value*, Value*> &GlobalMap,
598 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000599 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000600 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000601
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000602 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000603 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000604 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000605 I != E; ++I, ++DI) {
606 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000607
608 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000609 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000610 }
611
612 // Loop over all of the basic blocks, copying the instructions over...
613 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000614 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000615 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000616 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
617 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000618
619 // Loop over all of the instructions in the src basic block, copying them
620 // over. Note that this is broken in a strict sense because the cloned
621 // instructions will still be referencing values in the Src module, not
622 // the remapped values. In our case, however, we will not get caught and
623 // so we can delay patching the values up until later...
624 //
Chris Lattner18961502002-06-25 16:12:52 +0000625 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000626 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000627 Instruction *DI = II->clone();
628 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000629 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000630 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000631 }
632 }
633
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000634 // At this point, all of the instructions and values of the function are now
635 // copied over. The only problem is that they are still referencing values in
636 // the Source function as operands. Loop through all of the operands of the
637 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000638 //
Chris Lattner18961502002-06-25 16:12:52 +0000639 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
640 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
641 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000642 OI != OE; ++OI)
643 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000644
645 return false;
646}
647
648
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000649// LinkFunctionBodies - Link in the function bodies that are defined in the
650// source module into the DestModule. This consists basically of copying the
651// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000652//
Chris Lattner79df7c02002-03-26 18:01:55 +0000653static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000654 std::map<const Value*, Value*> &ValueMap,
655 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000656
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000657 // Loop over all of the functions in the src module, mapping them over as we
658 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000659 //
Chris Lattner18961502002-06-25 16:12:52 +0000660 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
661 if (!SF->isExternal()) { // No body if function is external
662 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000663
Chris Lattner18961502002-06-25 16:12:52 +0000664 // DF not external SF external?
665 if (!DF->isExternal()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000666 if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000667 if (Err)
Chris Lattner5c2d3352003-01-30 19:53:34 +0000668 *Err = "Function '" + (SF->hasName() ? SF->getName() :std::string(""))
669 + "' body multiply defined!";
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000670 return true;
671 }
672
Chris Lattner18961502002-06-25 16:12:52 +0000673 if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000674 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000675 }
676 return false;
677}
678
Chris Lattner8166e6e2003-05-13 21:33:43 +0000679// LinkAppendingVars - If there were any appending global variables, link them
680// together now. Return true on error.
681//
682static bool LinkAppendingVars(Module *M,
683 std::multimap<std::string, GlobalVariable *> &AppendingVars,
684 std::string *ErrorMsg) {
685 if (AppendingVars.empty()) return false; // Nothing to do.
686
687 // Loop over the multimap of appending vars, processing any variables with the
688 // same name, forming a new appending global variable with both of the
689 // initializers merged together, then rewrite references to the old variables
690 // and delete them.
691 //
692 std::vector<Constant*> Inits;
693 while (AppendingVars.size() > 1) {
694 // Get the first two elements in the map...
695 std::multimap<std::string,
696 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
697
698 // If the first two elements are for different names, there is no pair...
699 // Otherwise there is a pair, so link them together...
700 if (First->first == Second->first) {
701 GlobalVariable *G1 = First->second, *G2 = Second->second;
702 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
703 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
704
705 // Check to see that they two arrays agree on type...
706 if (T1->getElementType() != T2->getElementType())
707 return Error(ErrorMsg,
708 "Appending variables with different element types need to be linked!");
709 if (G1->isConstant() != G2->isConstant())
710 return Error(ErrorMsg,
711 "Appending variables linked with different const'ness!");
712
713 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
714 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
715
716 // Create the new global variable...
717 GlobalVariable *NG =
718 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
719 /*init*/0, First->first, M);
720
721 // Merge the initializer...
722 Inits.reserve(NewSize);
723 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
724 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
725 Inits.push_back(cast<Constant>(I->getValues()[i]));
726 I = cast<ConstantArray>(G2->getInitializer());
727 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
728 Inits.push_back(cast<Constant>(I->getValues()[i]));
729 NG->setInitializer(ConstantArray::get(NewType, Inits));
730 Inits.clear();
731
732 // Replace any uses of the two global variables with uses of the new
733 // global...
734
735 // FIXME: This should rewrite simple/straight-forward uses such as
736 // getelementptr instructions to not use the Cast!
737 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
738 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
739 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
740
741 // Remove the two globals from the module now...
742 M->getGlobalList().erase(G1);
743 M->getGlobalList().erase(G2);
744
745 // Put the new global into the AppendingVars map so that we can handle
746 // linking of more than two vars...
747 Second->second = NG;
748 }
749 AppendingVars.erase(First);
750 }
751
752 return false;
753}
Chris Lattner52f7e902001-10-13 07:03:50 +0000754
755
756// LinkModules - This function links two modules together, with the resulting
757// left module modified to be the composite of the two input modules. If an
758// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000759// the problem. Upon failure, the Dest module could be in a modified state, and
760// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000761//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000762bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner43a99942003-04-22 19:13:20 +0000763 if (Dest->getEndianness() != Src->getEndianness())
764 std::cerr << "WARNING: Linking two modules of different endianness!\n";
765 if (Dest->getPointerSize() != Src->getPointerSize())
766 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000767
768 // LinkTypes - Go through the symbol table of the Src module and see if any
769 // types are named in the src module that are not named in the Dst module.
770 // Make sure there are no type name conflicts.
771 //
772 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
773
Chris Lattner5c377c52001-10-14 23:29:15 +0000774 // ValueMap - Mapping of values from what they used to be in Src, to what they
775 // are now in Dest.
776 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000777 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000778
Chris Lattner8166e6e2003-05-13 21:33:43 +0000779 // AppendingVars - Keep track of global variables in the destination module
780 // with appending linkage. After the module is linked together, they are
781 // appended and the module is rewritten.
782 //
783 std::multimap<std::string, GlobalVariable *> AppendingVars;
784
785 // Add all of the appending globals already in the Dest module to
786 // AppendingVars.
787 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000788 if (I->hasAppendingLinkage())
789 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000790
791 // Insert all of the globals in src into the Dest module... without linking
792 // initializers (which could refer to functions not yet mapped over).
793 //
794 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000795
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000796 // Link the functions together between the two modules, without doing function
797 // bodies... this just adds external function prototypes to the Dest
798 // function... We do this so that when we begin processing function bodies,
799 // all of the global values that may be referenced are available in our
800 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000801 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000802 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000803
Chris Lattner6cdf1972002-07-18 00:13:08 +0000804 // Update the initializers in the Dest module now that all globals that may
805 // be referenced are in Dest.
806 //
807 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
808
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000809 // Link in the function bodies that are defined in the source module into the
810 // DestModule. This consists basically of copying the function over and
811 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000812 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000813 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000814
Chris Lattner8166e6e2003-05-13 21:33:43 +0000815 // If there were any appending global variables, link them together now.
816 //
817 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
818
Chris Lattner52f7e902001-10-13 07:03:50 +0000819 return false;
820}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000821