blob: bdbdb7d4ccc263e9ae855387dc375ed005616e2f [file] [log] [blame]
Chris Lattner52f7e902001-10-13 07:03:50 +00001//===- Linker.cpp - Module Linker Implementation --------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +000013// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000015// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +000016//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000019#include "llvm/Transforms/Utils/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000022#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000023#include "llvm/SymbolTable.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000024#include "llvm/iOther.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000025#include "llvm/Assembly/Writer.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000026
Brian Gaeked0fde302003-11-11 22:41:34 +000027namespace llvm {
28
Chris Lattner5c377c52001-10-14 23:29:15 +000029// Error - Simple wrapper function to conditionally assign to E and return true.
30// This just makes error return conditions a little bit simpler...
31//
Chris Lattner8166e6e2003-05-13 21:33:43 +000032static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000033 if (E) *E = Message;
34 return true;
35}
36
John Criswell700867b2003-11-04 15:22:26 +000037//
38// Function: ResolveTypes()
39//
40// Description:
41// Attempt to link the two specified types together.
42//
43// Inputs:
44// DestTy - The type to which we wish to resolve.
45// SrcTy - The original type which we want to resolve.
46// Name - The name of the type.
47//
48// Outputs:
49// DestST - The symbol table in which the new type should be placed.
50//
51// Return value:
52// true - There is an error and the types cannot yet be linked.
53// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000054//
Chris Lattnere76c57a2003-08-22 06:07:12 +000055static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
56 SymbolTable *DestST, const std::string &Name) {
57 if (DestTy == SrcTy) return false; // If already equal, noop
58
Chris Lattner4c00e532003-05-15 16:30:55 +000059 // Does the type already exist in the module?
60 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000061 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
62 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000063 } else {
64 return true; // Cannot link types... neither is opaque and not-equal
65 }
66 } else { // Type not in dest module. Add it now.
67 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000068 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
69 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000070 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000071 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000072 }
73 return false;
74}
75
Chris Lattner43f4ba82003-08-22 19:12:55 +000076static const FunctionType *getFT(const PATypeHolder &TH) {
77 return cast<FunctionType>(TH.get());
78}
Chris Lattner9732be72003-08-22 20:16:48 +000079static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000080 return cast<StructType>(TH.get());
81}
Chris Lattnere76c57a2003-08-22 06:07:12 +000082
83// RecursiveResolveTypes - This is just like ResolveTypes, except that it
84// recurses down into derived types, merging the used types if the parent types
85// are compatible.
86//
Chris Lattnere3092c92003-08-23 21:25:54 +000087static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
88 const PATypeHolder &SrcTy,
89 SymbolTable *DestST, const std::string &Name,
90 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000091 const Type *SrcTyT = SrcTy.get();
92 const Type *DestTyT = DestTy.get();
93 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000094
95 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000096 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
97 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000098
99 // Two types cannot be resolved together if they are of different primitive
100 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +0000101 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000102
103 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +0000104 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000105 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000106 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000107 cast<FunctionType>(SrcTyT)->isVarArg() ||
108 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
109 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000110 return true;
111 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000112 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
113 getFT(SrcTy)->getContainedType(i), DestST, "",
114 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000115 return true;
116 return false;
117 }
118 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000119 if (getST(DestTy)->getNumContainedTypes() !=
120 getST(SrcTy)->getNumContainedTypes()) return 1;
121 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000122 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
123 getST(SrcTy)->getContainedType(i), DestST, "",
124 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000125 return true;
126 return false;
127 }
128 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000129 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
130 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000131 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000132 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
133 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000134 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000135 case Type::PointerTyID: {
136 // If this is a pointer type, check to see if we have already seen it. If
137 // so, we are in a recursive branch. Cut off the search now. We cannot use
138 // an associative container for this search, because the type pointers (keys
139 // in the container) change whenever types get resolved...
140 //
141 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
142 if (Pointers[i].first == DestTy)
143 return Pointers[i].second != SrcTy;
144
145 // Otherwise, add the current pointers to the vector to stop recursion on
146 // this pair.
147 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
148 bool Result =
149 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
150 cast<PointerType>(SrcTy.get())->getElementType(),
151 DestST, "", Pointers);
152 Pointers.pop_back();
153 return Result;
154 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000155 default: assert(0 && "Unexpected type!"); return true;
156 }
157}
158
Chris Lattnere3092c92003-08-23 21:25:54 +0000159static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
160 const PATypeHolder &SrcTy,
161 SymbolTable *DestST, const std::string &Name){
162 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
163 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
164}
165
Chris Lattnere76c57a2003-08-22 06:07:12 +0000166
Chris Lattner2c236f32001-11-03 05:18:24 +0000167// LinkTypes - Go through the symbol table of the Src module and see if any
168// types are named in the src module that are not named in the Dst module.
169// Make sure there are no type name conflicts.
170//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000171static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000172 SymbolTable *DestST = &Dest->getSymbolTable();
173 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000174
175 // Look for a type plane for Type's...
176 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
177 if (PI == SrcST->end()) return false; // No named types, do nothing.
178
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000179 // Some types cannot be resolved immediately because they depend on other
180 // types being resolved to each other first. This contains a list of types we
181 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000182 std::vector<std::string> DelayedTypesToResolve;
183
Chris Lattner2c236f32001-11-03 05:18:24 +0000184 const SymbolTable::VarMap &VM = PI->second;
185 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
186 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000187 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000188 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000189
190 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000191 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000192
Chris Lattner4c00e532003-05-15 16:30:55 +0000193 if (ResolveTypes(Entry, RHS, DestST, Name)) {
194 // They look different, save the types 'till later to resolve.
195 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000196 }
197 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000198
199 // Iteratively resolve types while we can...
200 while (!DelayedTypesToResolve.empty()) {
201 // Loop over all of the types, attempting to resolve them if possible...
202 unsigned OldSize = DelayedTypesToResolve.size();
203
Chris Lattnere76c57a2003-08-22 06:07:12 +0000204 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000205 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
206 const std::string &Name = DelayedTypesToResolve[i];
207 Type *T1 = cast<Type>(VM.find(Name)->second);
208 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
209 if (!ResolveTypes(T2, T1, DestST, Name)) {
210 // We are making progress!
211 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
212 --i;
213 }
214 }
215
216 // Did we not eliminate any types?
217 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000218 // Attempt to resolve subelements of types. This allows us to merge these
219 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000220 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
221 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000222 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
223 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000224
225 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
226 // We are making progress!
227 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
228
229 // Go back to the main loop, perhaps we can resolve directly by name
230 // now...
231 break;
232 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000233 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000234
235 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000236 // Report the warning and delete one of the names.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000237 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000238 const std::string &Name = DelayedTypesToResolve.back();
239
240 const Type *T1 = cast<Type>(VM.find(Name)->second);
241 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
242 std::cerr << "WARNING: Type conflict between types named '" << Name
Chris Lattneradbc0b52003-11-20 18:23:14 +0000243 << "'.\n Src='";
244 WriteTypeSymbolic(std::cerr, T1, Src);
245 std::cerr << "'.\n Dest='";
246 WriteTypeSymbolic(std::cerr, T2, Dest);
247 std::cerr << "'\n";
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000248
249 // Remove the symbol name from the destination.
250 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000251 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000252 }
253 }
254
255
Chris Lattner2c236f32001-11-03 05:18:24 +0000256 return false;
257}
258
Chris Lattner5c2d3352003-01-30 19:53:34 +0000259static void PrintMap(const std::map<const Value*, Value*> &M) {
260 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000261 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000262 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000263 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000264 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000265 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000266 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000267 }
268}
269
270
Chris Lattner5c377c52001-10-14 23:29:15 +0000271// RemapOperand - Use LocalMap and GlobalMap to convert references from one
272// module to another. This is somewhat sophisticated in that it can
273// automatically handle constant references correctly as well...
274//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000275static Value *RemapOperand(const Value *In,
276 std::map<const Value*, Value*> &LocalMap,
277 std::map<const Value*, Value*> *GlobalMap) {
278 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000279 if (I != LocalMap.end()) return I->second;
280
281 if (GlobalMap) {
282 I = GlobalMap->find(In);
283 if (I != GlobalMap->end()) return I->second;
284 }
285
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000286 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000287 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000288 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000289 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000290
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000291 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000292
Chris Lattner18961502002-06-25 16:12:52 +0000293 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000294 const std::vector<Use> &Ops = CPA->getValues();
295 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000296 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000297 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000298 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
299 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000300 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000301 const std::vector<Use> &Ops = CPS->getValues();
302 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000303 for (unsigned i = 0; i < Ops.size(); ++i)
304 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000305 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
306 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
307 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000308 Result = const_cast<Constant*>(CPV);
309 } else if (const ConstantPointerRef *CPR =
310 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000311 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000312 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000313 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000314 if (CE->getOpcode() == Instruction::GetElementPtr) {
315 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
316 std::vector<Constant*> Indices;
317 Indices.reserve(CE->getNumOperands()-1);
318 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
319 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
320 LocalMap, GlobalMap)));
321
322 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
323 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000324 // Cast instruction
325 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000326 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000327 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000328 } else if (CE->getOpcode() == Instruction::Shl ||
329 CE->getOpcode() == Instruction::Shr) { // Shift
330 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
331 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
332 Result = ConstantExpr::getShift(CE->getOpcode(), cast<Constant>(V1),
333 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000334 } else if (CE->getNumOperands() == 2) {
335 // Binary operator...
336 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
337 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
338
339 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000340 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000341 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000342 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000343 }
344
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000345 } else {
346 assert(0 && "Unknown type of derived type constant value!");
347 }
348
349 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000350 if (GlobalMap)
351 GlobalMap->insert(std::make_pair(In, Result));
352 else
353 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000354 return Result;
355 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000356
Chris Lattner5c2d3352003-01-30 19:53:34 +0000357 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000358 PrintMap(LocalMap);
359
360 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000361 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000362 PrintMap(*GlobalMap);
363 }
364
Chris Lattner5c2d3352003-01-30 19:53:34 +0000365 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000366 assert(0 && "Couldn't remap value!");
367 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000368}
369
Chris Lattnerfcd02342003-08-23 20:31:10 +0000370/// FindGlobalNamed - Look in the specified symbol table for a global with the
371/// specified name and type. If an exactly matching global does not exist, see
372/// if there is a global which is "type compatible" with the specified
373/// name/type. This allows us to resolve things like '%x = global int*' with
374/// '%x = global opaque*'.
375///
376static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
377 SymbolTable *ST) {
378 // See if an exact match exists in the symbol table...
379 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
380
381 // It doesn't exist exactly, scan through all of the type planes in the symbol
382 // table, checking each of them for a type-compatible version.
383 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000384 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattner77c5f732003-08-24 19:30:20 +0000385 if (I->first != Type::TypeTy) {
Chris Lattnerf44c6052003-08-23 21:32:24 +0000386 SymbolTable::VarMap &VM = I->second;
John Criswell700867b2003-11-04 15:22:26 +0000387
Chris Lattnerf44c6052003-08-23 21:32:24 +0000388 // Does this type plane contain an entry with the specified name?
389 SymbolTable::type_iterator TI = VM.find(Name);
390 if (TI != VM.end()) {
John Criswell700867b2003-11-04 15:22:26 +0000391 //
392 // Ensure that this type if placed correctly into the symbol table.
393 //
394 assert(TI->second->getType() == I->first && "Type conflict!");
395
396 //
397 // Save a reference to the new type. Resolving the type can modify the
398 // symbol table, invalidating the TI variable.
399 //
400 Value *ValPtr = TI->second;
401
402 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000403 // Determine whether we can fold the two types together, resolving them.
404 // If so, we can use this value.
John Criswell700867b2003-11-04 15:22:26 +0000405 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000406 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
John Criswell700867b2003-11-04 15:22:26 +0000407 return cast<GlobalValue>(ValPtr);
Chris Lattnerf44c6052003-08-23 21:32:24 +0000408 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000409 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000410 return 0; // Otherwise, nothing could be found.
411}
412
Chris Lattner5c377c52001-10-14 23:29:15 +0000413
414// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000415// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000416//
417static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000418 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000419 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000420 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000421 // We will need a module level symbol table if the src module has a module
422 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000423 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000424
425 // Loop over all of the globals in the src module, mapping them over as we go
426 //
427 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000428 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000429 GlobalVariable *DGV = 0;
430 if (SGV->hasName()) {
431 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000432 // that may be in a module level symbol table are Global Vars and
433 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000434 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000435 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
436 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000437 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000438
Chris Lattner4ad02e72003-04-16 20:28:45 +0000439 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
440 "Global must either be external or have an initializer!");
441
Chris Lattner0fec08e2003-04-21 21:07:05 +0000442 bool SGExtern = SGV->isExternal();
443 bool DGExtern = DGV ? DGV->isExternal() : false;
444
Chris Lattner4ad02e72003-04-16 20:28:45 +0000445 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
446 // No linking to be performed, simply create an identical version of the
447 // symbol over in the dest module... the initializer will be filled in
448 // later by LinkGlobalInits...
449 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000450 GlobalVariable *NewDGV =
451 new GlobalVariable(SGV->getType()->getElementType(),
452 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
453 SGV->getName(), Dest);
454
455 // If the LLVM runtime renamed the global, but it is an externally visible
456 // symbol, DGV must be an existing global with internal linkage. Rename
457 // it.
458 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
459 assert(DGV && DGV->getName() == SGV->getName() &&
460 DGV->hasInternalLinkage());
461 DGV->setName("");
462 NewDGV->setName(SGV->getName()); // Force the name back
463 DGV->setName(SGV->getName()); // This will cause a renaming
464 assert(NewDGV->getName() == SGV->getName() &&
465 DGV->getName() != SGV->getName());
466 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000467
468 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000469 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000470 if (SGV->hasAppendingLinkage())
471 // Keep track that this is an appending variable...
472 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
473
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000474 } else if (SGV->isExternal()) {
475 // If SGV is external or if both SGV & DGV are external.. Just link the
476 // external globals, we aren't adding anything.
477 ValueMap.insert(std::make_pair(SGV, DGV));
478
479 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
480 ValueMap.insert(std::make_pair(SGV, DGV));
481 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner35956552003-10-27 16:39:39 +0000482 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000483 // At this point we know that DGV has LinkOnce, Appending, Weak, or
484 // External linkage. If DGV is Appending, this is an error.
485 if (DGV->hasAppendingLinkage())
486 return Error(Err, "Linking globals named '" + SGV->getName() +
487 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000488
489 if (SGV->isConstant() != DGV->isConstant())
490 return Error(Err, "Global Variable Collision on '" +
491 SGV->getType()->getDescription() + " %" + SGV->getName() +
492 "' - Global variables differ in const'ness");
493
Chris Lattner72ac148d2003-10-16 18:29:00 +0000494 // Otherwise, just perform the link.
495 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner35956552003-10-27 16:39:39 +0000496
497 // Linkonce+Weak = Weak
498 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
499 DGV->setLinkage(SGV->getLinkage());
500
501 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000502 // At this point we know that SGV has LinkOnce, Appending, or External
503 // linkage. If SGV is Appending, this is an error.
504 if (SGV->hasAppendingLinkage())
505 return Error(Err, "Linking globals named '" + SGV->getName() +
506 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000507
508 if (SGV->isConstant() != DGV->isConstant())
509 return Error(Err, "Global Variable Collision on '" +
510 SGV->getType()->getDescription() + " %" + SGV->getName() +
511 "' - Global variables differ in const'ness");
512
Chris Lattner72ac148d2003-10-16 18:29:00 +0000513 if (!SGV->hasLinkOnceLinkage())
514 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
515 ValueMap.insert(std::make_pair(SGV, DGV));
516
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000517 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000518 return Error(Err, "Global variables named '" + SGV->getName() +
519 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000520 } else if (SGV->hasExternalLinkage()) {
521 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000522 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000523 return Error(Err, "Global Variable Collision on '" +
524 SGV->getType()->getDescription() + " %" + SGV->getName() +
525 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000526
527 if (SGV->getInitializer() != DGV->getInitializer())
528 return Error(Err, "Global Variable Collision on '" +
529 SGV->getType()->getDescription() + " %" + SGV->getName() +
530 "' - External linkage globals have different initializers");
531
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000532 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000533 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000534 // No linking is performed yet. Just insert a new copy of the global, and
535 // keep track of the fact that it is an appending variable in the
536 // AppendingVars map. The name is cleared out so that no linkage is
537 // performed.
538 GlobalVariable *NewDGV =
539 new GlobalVariable(SGV->getType()->getElementType(),
540 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
541 "", Dest);
542
543 // Make sure to remember this mapping...
544 ValueMap.insert(std::make_pair(SGV, NewDGV));
545
546 // Keep track that this is an appending variable...
547 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000548 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000549 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000550 }
551 }
552 return false;
553}
554
555
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000556// LinkGlobalInits - Update the initializers in the Dest module now that all
557// globals that may be referenced are in Dest.
558//
559static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000560 std::map<const Value*, Value*> &ValueMap,
561 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000562
563 // Loop over all of the globals in the src module, mapping them over as we go
564 //
565 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000566 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000567
568 if (SGV->hasInitializer()) { // Only process initialized GV's
569 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000570 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000571 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000572
573 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000574 if (DGV->hasInitializer()) {
575 assert(SGV->getLinkage() == DGV->getLinkage());
576 if (SGV->hasExternalLinkage()) {
577 if (DGV->getInitializer() != SInit)
578 return Error(Err, "Global Variable Collision on '" +
579 SGV->getType()->getDescription() +"':%"+SGV->getName()+
580 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000581 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000582 // Nothing is required, mapped values will take the new global
583 // automatically.
584 } else if (DGV->hasAppendingLinkage()) {
585 assert(0 && "Appending linkage unimplemented!");
586 } else {
587 assert(0 && "Unknown linkage!");
588 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000589 } else {
590 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000591 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000592 }
593 }
594 }
595 return false;
596}
Chris Lattner5c377c52001-10-14 23:29:15 +0000597
Chris Lattner79df7c02002-03-26 18:01:55 +0000598// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000599// without doing function bodies... this just adds external function prototypes
600// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000601//
Chris Lattner79df7c02002-03-26 18:01:55 +0000602static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000603 std::map<const Value*, Value*> &ValueMap,
604 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000605 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000606
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000607 // Loop over all of the functions in the src module, mapping them over as we
608 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000609 //
610 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000611 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000612 Function *DF = 0;
613 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000614 // The same named thing is a Function, because the only two things
615 // that may be in a module level symbol table are Global Vars and
616 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000617 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000618 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
619 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000620
Chris Lattner4ad02e72003-04-16 20:28:45 +0000621 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000622 // Function does not already exist, simply insert an function signature
623 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000624 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
625 SF->getName(), Dest);
626
627 // If the LLVM runtime renamed the function, but it is an externally
628 // visible symbol, DF must be an existing function with internal linkage.
629 // Rename it.
630 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
631 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
632 DF->setName("");
633 NewDF->setName(SF->getName()); // Force the name back
634 DF->setName(SF->getName()); // This will cause a renaming
635 assert(NewDF->getName() == SF->getName() &&
636 DF->getName() != SF->getName());
637 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000638
639 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000640 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000641 } else if (SF->isExternal()) {
642 // If SF is external or if both SF & DF are external.. Just link the
643 // external functions, we aren't adding anything.
644 ValueMap.insert(std::make_pair(SF, DF));
645 } else if (DF->isExternal()) { // If DF is external but SF is not...
646 // Link the external functions, update linkage qualifiers
647 ValueMap.insert(std::make_pair(SF, DF));
648 DF->setLinkage(SF->getLinkage());
649
Chris Lattner35956552003-10-27 16:39:39 +0000650 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000651 // At this point we know that DF has LinkOnce, Weak, or External linkage.
652 ValueMap.insert(std::make_pair(SF, DF));
653
Chris Lattner35956552003-10-27 16:39:39 +0000654 // Linkonce+Weak = Weak
655 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
656 DF->setLinkage(SF->getLinkage());
657
658 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000659 // At this point we know that SF has LinkOnce or External linkage.
660 ValueMap.insert(std::make_pair(SF, DF));
661 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
662 DF->setLinkage(SF->getLinkage());
663
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000664 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000665 return Error(Err, "Functions named '" + SF->getName() +
666 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000667 } else if (SF->hasExternalLinkage()) {
668 // The function is defined in both modules!!
669 return Error(Err, "Function '" +
670 SF->getFunctionType()->getDescription() + "':\"" +
671 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000672 } else {
673 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000674 }
675 }
676 return false;
677}
678
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000679// LinkFunctionBody - Copy the source function over into the dest function and
680// fix up references to values. At this point we know that Dest is an external
681// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000682//
Chris Lattner79df7c02002-03-26 18:01:55 +0000683static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000684 std::map<const Value*, Value*> &GlobalMap,
685 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000686 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000687 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000688
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000689 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000690 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000691 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000692 I != E; ++I, ++DI) {
693 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000694
695 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000696 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000697 }
698
699 // Loop over all of the basic blocks, copying the instructions over...
700 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000701 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000702 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000703 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
704 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000705
706 // Loop over all of the instructions in the src basic block, copying them
707 // over. Note that this is broken in a strict sense because the cloned
708 // instructions will still be referencing values in the Src module, not
709 // the remapped values. In our case, however, we will not get caught and
710 // so we can delay patching the values up until later...
711 //
Chris Lattner18961502002-06-25 16:12:52 +0000712 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000713 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000714 Instruction *DI = II->clone();
715 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000716 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000717 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000718 }
719 }
720
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000721 // At this point, all of the instructions and values of the function are now
722 // copied over. The only problem is that they are still referencing values in
723 // the Source function as operands. Loop through all of the operands of the
724 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000725 //
Chris Lattner18961502002-06-25 16:12:52 +0000726 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
727 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
728 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000729 OI != OE; ++OI)
730 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000731
732 return false;
733}
734
735
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000736// LinkFunctionBodies - Link in the function bodies that are defined in the
737// source module into the DestModule. This consists basically of copying the
738// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000739//
Chris Lattner79df7c02002-03-26 18:01:55 +0000740static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000741 std::map<const Value*, Value*> &ValueMap,
742 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000743
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000744 // Loop over all of the functions in the src module, mapping them over as we
745 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000746 //
Chris Lattner18961502002-06-25 16:12:52 +0000747 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
748 if (!SF->isExternal()) { // No body if function is external
749 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000750
Chris Lattner18961502002-06-25 16:12:52 +0000751 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000752 if (DF->isExternal()) {
753 // Only provide the function body if there isn't one already.
754 if (LinkFunctionBody(DF, SF, ValueMap, Err))
755 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000756 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000757 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000758 }
759 return false;
760}
761
Chris Lattner8166e6e2003-05-13 21:33:43 +0000762// LinkAppendingVars - If there were any appending global variables, link them
763// together now. Return true on error.
764//
765static bool LinkAppendingVars(Module *M,
766 std::multimap<std::string, GlobalVariable *> &AppendingVars,
767 std::string *ErrorMsg) {
768 if (AppendingVars.empty()) return false; // Nothing to do.
769
770 // Loop over the multimap of appending vars, processing any variables with the
771 // same name, forming a new appending global variable with both of the
772 // initializers merged together, then rewrite references to the old variables
773 // and delete them.
774 //
775 std::vector<Constant*> Inits;
776 while (AppendingVars.size() > 1) {
777 // Get the first two elements in the map...
778 std::multimap<std::string,
779 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
780
781 // If the first two elements are for different names, there is no pair...
782 // Otherwise there is a pair, so link them together...
783 if (First->first == Second->first) {
784 GlobalVariable *G1 = First->second, *G2 = Second->second;
785 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
786 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
787
788 // Check to see that they two arrays agree on type...
789 if (T1->getElementType() != T2->getElementType())
790 return Error(ErrorMsg,
791 "Appending variables with different element types need to be linked!");
792 if (G1->isConstant() != G2->isConstant())
793 return Error(ErrorMsg,
794 "Appending variables linked with different const'ness!");
795
796 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
797 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
798
799 // Create the new global variable...
800 GlobalVariable *NG =
801 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
802 /*init*/0, First->first, M);
803
804 // Merge the initializer...
805 Inits.reserve(NewSize);
806 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
807 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
808 Inits.push_back(cast<Constant>(I->getValues()[i]));
809 I = cast<ConstantArray>(G2->getInitializer());
810 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
811 Inits.push_back(cast<Constant>(I->getValues()[i]));
812 NG->setInitializer(ConstantArray::get(NewType, Inits));
813 Inits.clear();
814
815 // Replace any uses of the two global variables with uses of the new
816 // global...
817
818 // FIXME: This should rewrite simple/straight-forward uses such as
819 // getelementptr instructions to not use the Cast!
820 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
821 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
822 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
823
824 // Remove the two globals from the module now...
825 M->getGlobalList().erase(G1);
826 M->getGlobalList().erase(G2);
827
828 // Put the new global into the AppendingVars map so that we can handle
829 // linking of more than two vars...
830 Second->second = NG;
831 }
832 AppendingVars.erase(First);
833 }
834
835 return false;
836}
Chris Lattner52f7e902001-10-13 07:03:50 +0000837
838
839// LinkModules - This function links two modules together, with the resulting
840// left module modified to be the composite of the two input modules. If an
841// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000842// the problem. Upon failure, the Dest module could be in a modified state, and
843// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000844//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000845bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000846 if (Dest->getEndianness() == Module::AnyEndianness)
847 Dest->setEndianness(Src->getEndianness());
848 if (Dest->getPointerSize() == Module::AnyPointerSize)
849 Dest->setPointerSize(Src->getPointerSize());
850
851 if (Src->getEndianness() != Module::AnyEndianness &&
852 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000853 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000854 if (Src->getPointerSize() != Module::AnyPointerSize &&
855 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000856 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000857
858 // LinkTypes - Go through the symbol table of the Src module and see if any
859 // types are named in the src module that are not named in the Dst module.
860 // Make sure there are no type name conflicts.
861 //
862 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
863
Chris Lattner5c377c52001-10-14 23:29:15 +0000864 // ValueMap - Mapping of values from what they used to be in Src, to what they
865 // are now in Dest.
866 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000867 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000868
Chris Lattner8166e6e2003-05-13 21:33:43 +0000869 // AppendingVars - Keep track of global variables in the destination module
870 // with appending linkage. After the module is linked together, they are
871 // appended and the module is rewritten.
872 //
873 std::multimap<std::string, GlobalVariable *> AppendingVars;
874
875 // Add all of the appending globals already in the Dest module to
876 // AppendingVars.
877 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000878 if (I->hasAppendingLinkage())
879 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000880
881 // Insert all of the globals in src into the Dest module... without linking
882 // initializers (which could refer to functions not yet mapped over).
883 //
884 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000885
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000886 // Link the functions together between the two modules, without doing function
887 // bodies... this just adds external function prototypes to the Dest
888 // function... We do this so that when we begin processing function bodies,
889 // all of the global values that may be referenced are available in our
890 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000891 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000892 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000893
Chris Lattner6cdf1972002-07-18 00:13:08 +0000894 // Update the initializers in the Dest module now that all globals that may
895 // be referenced are in Dest.
896 //
897 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
898
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000899 // Link in the function bodies that are defined in the source module into the
900 // DestModule. This consists basically of copying the function over and
901 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000902 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000903 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000904
Chris Lattner8166e6e2003-05-13 21:33:43 +0000905 // If there were any appending global variables, link them together now.
906 //
907 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
908
Chris Lattner52f7e902001-10-13 07:03:50 +0000909 return false;
910}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000911
Brian Gaeked0fde302003-11-11 22:41:34 +0000912} // End llvm namespace