blob: b241d9e333db6eb03781e171825efedc371d42a8 [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
Misha Brukmanc837dd92004-06-23 17:24:31 +000019#include "llvm/Support/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"
Reid Spencerc28a2242004-07-04 11:52:49 +000026#include <iostream>
27
Chris Lattnerf7703df2004-01-09 06:12:26 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner5c377c52001-10-14 23:29:15 +000030// Error - Simple wrapper function to conditionally assign to E and return true.
31// This just makes error return conditions a little bit simpler...
32//
Chris Lattner8166e6e2003-05-13 21:33:43 +000033static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000034 if (E) *E = Message;
35 return true;
36}
37
John Criswell700867b2003-11-04 15:22:26 +000038//
39// Function: ResolveTypes()
40//
41// Description:
42// Attempt to link the two specified types together.
43//
44// Inputs:
45// DestTy - The type to which we wish to resolve.
46// SrcTy - The original type which we want to resolve.
47// Name - The name of the type.
48//
49// Outputs:
50// DestST - The symbol table in which the new type should be placed.
51//
52// Return value:
53// true - There is an error and the types cannot yet be linked.
54// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000055//
Chris Lattnere76c57a2003-08-22 06:07:12 +000056static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
57 SymbolTable *DestST, const std::string &Name) {
58 if (DestTy == SrcTy) return false; // If already equal, noop
59
Chris Lattner4c00e532003-05-15 16:30:55 +000060 // Does the type already exist in the module?
61 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000062 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
63 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000064 } else {
65 return true; // Cannot link types... neither is opaque and not-equal
66 }
67 } else { // Type not in dest module. Add it now.
68 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000069 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
70 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000071 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000072 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000073 }
74 return false;
75}
76
Chris Lattner43f4ba82003-08-22 19:12:55 +000077static const FunctionType *getFT(const PATypeHolder &TH) {
78 return cast<FunctionType>(TH.get());
79}
Chris Lattner9732be72003-08-22 20:16:48 +000080static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000081 return cast<StructType>(TH.get());
82}
Chris Lattnere76c57a2003-08-22 06:07:12 +000083
84// RecursiveResolveTypes - This is just like ResolveTypes, except that it
85// recurses down into derived types, merging the used types if the parent types
86// are compatible.
87//
Chris Lattnere3092c92003-08-23 21:25:54 +000088static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
89 const PATypeHolder &SrcTy,
90 SymbolTable *DestST, const std::string &Name,
91 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000092 const Type *SrcTyT = SrcTy.get();
93 const Type *DestTyT = DestTy.get();
94 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000095
96 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000097 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
98 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000099
100 // Two types cannot be resolved together if they are of different primitive
101 // type. For example, we cannot resolve an int to a float.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000102 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000103
104 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000105 switch (DestTyT->getTypeID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000106 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000107 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000108 cast<FunctionType>(SrcTyT)->isVarArg() ||
109 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
110 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000111 return true;
112 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000113 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
114 getFT(SrcTy)->getContainedType(i), DestST, "",
115 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000116 return true;
117 return false;
118 }
119 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000120 if (getST(DestTy)->getNumContainedTypes() !=
121 getST(SrcTy)->getNumContainedTypes()) return 1;
122 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000123 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
124 getST(SrcTy)->getContainedType(i), DestST, "",
125 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000126 return true;
127 return false;
128 }
129 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000130 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
131 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000132 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000133 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
134 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000135 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000136 case Type::PointerTyID: {
137 // If this is a pointer type, check to see if we have already seen it. If
138 // so, we are in a recursive branch. Cut off the search now. We cannot use
139 // an associative container for this search, because the type pointers (keys
140 // in the container) change whenever types get resolved...
141 //
142 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
143 if (Pointers[i].first == DestTy)
144 return Pointers[i].second != SrcTy;
145
146 // Otherwise, add the current pointers to the vector to stop recursion on
147 // this pair.
148 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
149 bool Result =
150 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
151 cast<PointerType>(SrcTy.get())->getElementType(),
152 DestST, "", Pointers);
153 Pointers.pop_back();
154 return Result;
155 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000156 default: assert(0 && "Unexpected type!"); return true;
157 }
158}
159
Chris Lattnere3092c92003-08-23 21:25:54 +0000160static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
161 const PATypeHolder &SrcTy,
162 SymbolTable *DestST, const std::string &Name){
163 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
164 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
165}
166
Chris Lattnere76c57a2003-08-22 06:07:12 +0000167
Chris Lattner2c236f32001-11-03 05:18:24 +0000168// LinkTypes - Go through the symbol table of the Src module and see if any
169// types are named in the src module that are not named in the Dst module.
170// Make sure there are no type name conflicts.
171//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000172static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000173 SymbolTable *DestST = &Dest->getSymbolTable();
174 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000175
176 // Look for a type plane for Type's...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000177 SymbolTable::type_const_iterator TI = SrcST->type_begin();
178 SymbolTable::type_const_iterator TE = SrcST->type_end();
179 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000180
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000181 // Some types cannot be resolved immediately because they depend on other
182 // types being resolved to each other first. This contains a list of types we
183 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000184 std::vector<std::string> DelayedTypesToResolve;
185
Reid Spencer567bc2c2004-05-25 08:52:20 +0000186 for ( ; TI != TE; ++TI ) {
187 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000188 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000189
190 // Check to see if this type name is already in the dest module...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000191 Type *Entry = DestST->lookupType(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];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000207 Type *T1 = SrcST->lookupType(Name);
208 Type *T2 = DestST->lookupType(Name);
Chris Lattner4c00e532003-05-15 16:30:55 +0000209 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];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000222 PATypeHolder T1(SrcST->lookupType(Name));
223 PATypeHolder T2(DestST->lookupType(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
Reid Spencer567bc2c2004-05-25 08:52:20 +0000240 const Type *T1 = SrcST->lookupType(Name);
241 const Type *T2 = DestST->lookupType(Name);
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000242 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 Lattnerde512b52004-02-15 05:55:15 +0000288 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
289 isa<ConstantAggregateZero>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000290 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000291
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000292 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000293
Chris Lattner18961502002-06-25 16:12:52 +0000294 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000295 const std::vector<Use> &Ops = CPA->getValues();
296 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000297 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000298 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000299 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
300 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000301 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000302 const std::vector<Use> &Ops = CPS->getValues();
303 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000304 for (unsigned i = 0; i < Ops.size(); ++i)
305 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000306 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
307 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
308 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000309 Result = const_cast<Constant*>(CPV);
310 } else if (const ConstantPointerRef *CPR =
311 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000312 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000313 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000314 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000315 if (CE->getOpcode() == Instruction::GetElementPtr) {
316 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
317 std::vector<Constant*> Indices;
318 Indices.reserve(CE->getNumOperands()-1);
319 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
320 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
321 LocalMap, GlobalMap)));
322
323 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
324 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000325 // Cast instruction
326 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000327 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000328 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattner14381022004-03-31 02:58:28 +0000329 } else if (CE->getNumOperands() == 3) {
330 // Select instruction
331 assert(CE->getOpcode() == Instruction::Select);
332 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
333 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
334 Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
335 Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
336 cast<Constant>(V3));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000337 } else if (CE->getNumOperands() == 2) {
338 // Binary operator...
339 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
340 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
341
342 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000343 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000344 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000345 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000346 }
347
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000348 } else {
349 assert(0 && "Unknown type of derived type constant value!");
350 }
351
352 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000353 if (GlobalMap)
354 GlobalMap->insert(std::make_pair(In, Result));
355 else
356 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000357 return Result;
358 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000359
Chris Lattner5c2d3352003-01-30 19:53:34 +0000360 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000361 PrintMap(LocalMap);
362
363 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000364 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000365 PrintMap(*GlobalMap);
366 }
367
Chris Lattner5c2d3352003-01-30 19:53:34 +0000368 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000369 assert(0 && "Couldn't remap value!");
370 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000371}
372
Chris Lattnerfcd02342003-08-23 20:31:10 +0000373/// FindGlobalNamed - Look in the specified symbol table for a global with the
374/// specified name and type. If an exactly matching global does not exist, see
375/// if there is a global which is "type compatible" with the specified
376/// name/type. This allows us to resolve things like '%x = global int*' with
377/// '%x = global opaque*'.
378///
379static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
380 SymbolTable *ST) {
381 // See if an exact match exists in the symbol table...
382 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
383
384 // It doesn't exist exactly, scan through all of the type planes in the symbol
385 // table, checking each of them for a type-compatible version.
386 //
Reid Spencer567bc2c2004-05-25 08:52:20 +0000387 for (SymbolTable::plane_iterator PI = ST->plane_begin(), PE = ST->plane_end();
388 PI != PE; ++PI) {
389 SymbolTable::ValueMap &VM = PI->second;
John Criswell700867b2003-11-04 15:22:26 +0000390
Reid Spencer567bc2c2004-05-25 08:52:20 +0000391 // Does this type plane contain an entry with the specified name?
392 SymbolTable::value_iterator VI = VM.find(Name);
393 if (VI != VM.end()) {
John Criswell700867b2003-11-04 15:22:26 +0000394 //
395 // Ensure that this type if placed correctly into the symbol table.
396 //
Reid Spencer567bc2c2004-05-25 08:52:20 +0000397 assert(VI->second->getType() == PI->first && "Type conflict!");
John Criswell700867b2003-11-04 15:22:26 +0000398
399 //
400 // Save a reference to the new type. Resolving the type can modify the
401 // symbol table, invalidating the TI variable.
402 //
Reid Spencer567bc2c2004-05-25 08:52:20 +0000403 Value *ValPtr = VI->second;
John Criswell700867b2003-11-04 15:22:26 +0000404
405 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000406 // Determine whether we can fold the two types together, resolving them.
407 // If so, we can use this value.
John Criswell700867b2003-11-04 15:22:26 +0000408 //
Reid Spencer567bc2c2004-05-25 08:52:20 +0000409 if (!RecursiveResolveTypes(Ty, PI->first, ST, ""))
John Criswell700867b2003-11-04 15:22:26 +0000410 return cast<GlobalValue>(ValPtr);
Chris Lattnerf44c6052003-08-23 21:32:24 +0000411 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000412 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000413 return 0; // Otherwise, nothing could be found.
414}
415
Chris Lattner5c377c52001-10-14 23:29:15 +0000416
417// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000418// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000419//
420static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000421 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000422 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000423 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000424 // We will need a module level symbol table if the src module has a module
425 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000426 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000427
428 // Loop over all of the globals in the src module, mapping them over as we go
429 //
430 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000431 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000432 GlobalVariable *DGV = 0;
433 if (SGV->hasName()) {
434 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000435 // that may be in a module level symbol table are Global Vars and
436 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000437 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000438 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
439 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000440 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000441
Chris Lattner4ad02e72003-04-16 20:28:45 +0000442 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
443 "Global must either be external or have an initializer!");
444
Chris Lattner0fec08e2003-04-21 21:07:05 +0000445 bool SGExtern = SGV->isExternal();
446 bool DGExtern = DGV ? DGV->isExternal() : false;
447
Chris Lattner4ad02e72003-04-16 20:28:45 +0000448 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
449 // No linking to be performed, simply create an identical version of the
450 // symbol over in the dest module... the initializer will be filled in
451 // later by LinkGlobalInits...
452 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000453 GlobalVariable *NewDGV =
454 new GlobalVariable(SGV->getType()->getElementType(),
455 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
456 SGV->getName(), Dest);
457
458 // If the LLVM runtime renamed the global, but it is an externally visible
459 // symbol, DGV must be an existing global with internal linkage. Rename
460 // it.
461 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
462 assert(DGV && DGV->getName() == SGV->getName() &&
463 DGV->hasInternalLinkage());
464 DGV->setName("");
465 NewDGV->setName(SGV->getName()); // Force the name back
466 DGV->setName(SGV->getName()); // This will cause a renaming
467 assert(NewDGV->getName() == SGV->getName() &&
468 DGV->getName() != SGV->getName());
469 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000470
471 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000472 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000473 if (SGV->hasAppendingLinkage())
474 // Keep track that this is an appending variable...
475 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
476
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000477 } else if (SGV->isExternal()) {
478 // If SGV is external or if both SGV & DGV are external.. Just link the
479 // external globals, we aren't adding anything.
480 ValueMap.insert(std::make_pair(SGV, DGV));
481
482 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
483 ValueMap.insert(std::make_pair(SGV, DGV));
484 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner35956552003-10-27 16:39:39 +0000485 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000486 // At this point we know that DGV has LinkOnce, Appending, Weak, or
487 // External linkage. If DGV is Appending, this is an error.
488 if (DGV->hasAppendingLinkage())
489 return Error(Err, "Linking globals named '" + SGV->getName() +
490 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000491
492 if (SGV->isConstant() != DGV->isConstant())
493 return Error(Err, "Global Variable Collision on '" +
494 SGV->getType()->getDescription() + " %" + SGV->getName() +
495 "' - Global variables differ in const'ness");
496
Chris Lattner72ac148d2003-10-16 18:29:00 +0000497 // Otherwise, just perform the link.
498 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner35956552003-10-27 16:39:39 +0000499
500 // Linkonce+Weak = Weak
501 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
502 DGV->setLinkage(SGV->getLinkage());
503
504 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000505 // At this point we know that SGV has LinkOnce, Appending, or External
506 // linkage. If SGV is Appending, this is an error.
507 if (SGV->hasAppendingLinkage())
508 return Error(Err, "Linking globals named '" + SGV->getName() +
509 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000510
511 if (SGV->isConstant() != DGV->isConstant())
512 return Error(Err, "Global Variable Collision on '" +
513 SGV->getType()->getDescription() + " %" + SGV->getName() +
514 "' - Global variables differ in const'ness");
515
Chris Lattner72ac148d2003-10-16 18:29:00 +0000516 if (!SGV->hasLinkOnceLinkage())
517 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
518 ValueMap.insert(std::make_pair(SGV, DGV));
519
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000520 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000521 return Error(Err, "Global variables named '" + SGV->getName() +
522 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000523 } else if (SGV->hasExternalLinkage()) {
524 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000525 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000526 return Error(Err, "Global Variable Collision on '" +
527 SGV->getType()->getDescription() + " %" + SGV->getName() +
528 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000529
530 if (SGV->getInitializer() != DGV->getInitializer())
531 return Error(Err, "Global Variable Collision on '" +
532 SGV->getType()->getDescription() + " %" + SGV->getName() +
533 "' - External linkage globals have different initializers");
534
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000535 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000536 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000537 // No linking is performed yet. Just insert a new copy of the global, and
538 // keep track of the fact that it is an appending variable in the
539 // AppendingVars map. The name is cleared out so that no linkage is
540 // performed.
541 GlobalVariable *NewDGV =
542 new GlobalVariable(SGV->getType()->getElementType(),
543 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
544 "", Dest);
545
546 // Make sure to remember this mapping...
547 ValueMap.insert(std::make_pair(SGV, NewDGV));
548
549 // Keep track that this is an appending variable...
550 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000551 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000552 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000553 }
554 }
555 return false;
556}
557
558
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000559// LinkGlobalInits - Update the initializers in the Dest module now that all
560// globals that may be referenced are in Dest.
561//
562static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000563 std::map<const Value*, Value*> &ValueMap,
564 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000565
566 // Loop over all of the globals in the src module, mapping them over as we go
567 //
568 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000569 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000570
571 if (SGV->hasInitializer()) { // Only process initialized GV's
572 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000573 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000574 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000575
576 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000577 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000578 if (SGV->hasExternalLinkage()) {
579 if (DGV->getInitializer() != SInit)
580 return Error(Err, "Global Variable Collision on '" +
581 SGV->getType()->getDescription() +"':%"+SGV->getName()+
582 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000583 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000584 // Nothing is required, mapped values will take the new global
585 // automatically.
Chris Lattner57cb9882004-02-17 21:56:04 +0000586 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
587 // Nothing is required, mapped values will take the new global
588 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000589 } else if (DGV->hasAppendingLinkage()) {
590 assert(0 && "Appending linkage unimplemented!");
591 } else {
592 assert(0 && "Unknown linkage!");
593 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000594 } else {
595 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000596 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000597 }
598 }
599 }
600 return false;
601}
Chris Lattner5c377c52001-10-14 23:29:15 +0000602
Chris Lattner79df7c02002-03-26 18:01:55 +0000603// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000604// without doing function bodies... this just adds external function prototypes
605// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000606//
Chris Lattner79df7c02002-03-26 18:01:55 +0000607static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000608 std::map<const Value*, Value*> &ValueMap,
609 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000610 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000611
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000612 // Loop over all of the functions in the src module, mapping them over as we
613 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000614 //
615 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000616 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000617 Function *DF = 0;
618 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000619 // The same named thing is a Function, because the only two things
620 // that may be in a module level symbol table are Global Vars and
621 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000622 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000623 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
624 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000625
Chris Lattner4ad02e72003-04-16 20:28:45 +0000626 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000627 // Function does not already exist, simply insert an function signature
628 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000629 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
630 SF->getName(), Dest);
631
632 // If the LLVM runtime renamed the function, but it is an externally
633 // visible symbol, DF must be an existing function with internal linkage.
634 // Rename it.
635 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
636 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
637 DF->setName("");
638 NewDF->setName(SF->getName()); // Force the name back
639 DF->setName(SF->getName()); // This will cause a renaming
640 assert(NewDF->getName() == SF->getName() &&
641 DF->getName() != SF->getName());
642 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000643
644 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000645 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000646 } else if (SF->isExternal()) {
647 // If SF is external or if both SF & DF are external.. Just link the
648 // external functions, we aren't adding anything.
649 ValueMap.insert(std::make_pair(SF, DF));
650 } else if (DF->isExternal()) { // If DF is external but SF is not...
651 // Link the external functions, update linkage qualifiers
652 ValueMap.insert(std::make_pair(SF, DF));
653 DF->setLinkage(SF->getLinkage());
654
Chris Lattner35956552003-10-27 16:39:39 +0000655 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000656 // At this point we know that DF has LinkOnce, Weak, or External linkage.
657 ValueMap.insert(std::make_pair(SF, DF));
658
Chris Lattner35956552003-10-27 16:39:39 +0000659 // Linkonce+Weak = Weak
660 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
661 DF->setLinkage(SF->getLinkage());
662
663 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000664 // At this point we know that SF has LinkOnce or External linkage.
665 ValueMap.insert(std::make_pair(SF, DF));
666 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
667 DF->setLinkage(SF->getLinkage());
668
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000669 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000670 return Error(Err, "Functions named '" + SF->getName() +
671 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000672 } else if (SF->hasExternalLinkage()) {
673 // The function is defined in both modules!!
674 return Error(Err, "Function '" +
675 SF->getFunctionType()->getDescription() + "':\"" +
676 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000677 } else {
678 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000679 }
680 }
681 return false;
682}
683
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000684// LinkFunctionBody - Copy the source function over into the dest function and
685// fix up references to values. At this point we know that Dest is an external
686// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000687//
Chris Lattner79df7c02002-03-26 18:01:55 +0000688static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000689 std::map<const Value*, Value*> &GlobalMap,
690 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000691 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000692 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000693
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000694 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000695 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000696 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000697 I != E; ++I, ++DI) {
698 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000699
700 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000701 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000702 }
703
704 // Loop over all of the basic blocks, copying the instructions over...
705 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000706 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000707 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000708 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
709 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000710
711 // Loop over all of the instructions in the src basic block, copying them
712 // over. Note that this is broken in a strict sense because the cloned
713 // instructions will still be referencing values in the Src module, not
714 // the remapped values. In our case, however, we will not get caught and
715 // so we can delay patching the values up until later...
716 //
Chris Lattner18961502002-06-25 16:12:52 +0000717 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000718 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000719 Instruction *DI = II->clone();
720 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000721 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000722 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000723 }
724 }
725
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000726 // At this point, all of the instructions and values of the function are now
727 // copied over. The only problem is that they are still referencing values in
728 // the Source function as operands. Loop through all of the operands of the
729 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000730 //
Chris Lattner18961502002-06-25 16:12:52 +0000731 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
732 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
733 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000734 OI != OE; ++OI)
735 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000736
737 return false;
738}
739
740
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000741// LinkFunctionBodies - Link in the function bodies that are defined in the
742// source module into the DestModule. This consists basically of copying the
743// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000744//
Chris Lattner79df7c02002-03-26 18:01:55 +0000745static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000746 std::map<const Value*, Value*> &ValueMap,
747 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000748
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000749 // Loop over all of the functions in the src module, mapping them over as we
750 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000751 //
Chris Lattner18961502002-06-25 16:12:52 +0000752 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
753 if (!SF->isExternal()) { // No body if function is external
754 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000755
Chris Lattner18961502002-06-25 16:12:52 +0000756 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000757 if (DF->isExternal()) {
758 // Only provide the function body if there isn't one already.
759 if (LinkFunctionBody(DF, SF, ValueMap, Err))
760 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000761 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000762 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000763 }
764 return false;
765}
766
Chris Lattner8166e6e2003-05-13 21:33:43 +0000767// LinkAppendingVars - If there were any appending global variables, link them
768// together now. Return true on error.
769//
770static bool LinkAppendingVars(Module *M,
771 std::multimap<std::string, GlobalVariable *> &AppendingVars,
772 std::string *ErrorMsg) {
773 if (AppendingVars.empty()) return false; // Nothing to do.
774
775 // Loop over the multimap of appending vars, processing any variables with the
776 // same name, forming a new appending global variable with both of the
777 // initializers merged together, then rewrite references to the old variables
778 // and delete them.
779 //
780 std::vector<Constant*> Inits;
781 while (AppendingVars.size() > 1) {
782 // Get the first two elements in the map...
783 std::multimap<std::string,
784 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
785
786 // If the first two elements are for different names, there is no pair...
787 // Otherwise there is a pair, so link them together...
788 if (First->first == Second->first) {
789 GlobalVariable *G1 = First->second, *G2 = Second->second;
790 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
791 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
792
793 // Check to see that they two arrays agree on type...
794 if (T1->getElementType() != T2->getElementType())
795 return Error(ErrorMsg,
796 "Appending variables with different element types need to be linked!");
797 if (G1->isConstant() != G2->isConstant())
798 return Error(ErrorMsg,
799 "Appending variables linked with different const'ness!");
800
801 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
802 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
803
804 // Create the new global variable...
805 GlobalVariable *NG =
806 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
807 /*init*/0, First->first, M);
808
809 // Merge the initializer...
810 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +0000811 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
812 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
813 Inits.push_back(cast<Constant>(I->getValues()[i]));
814 } else {
815 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
816 Constant *CV = Constant::getNullValue(T1->getElementType());
817 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
818 Inits.push_back(CV);
819 }
820 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
821 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
822 Inits.push_back(cast<Constant>(I->getValues()[i]));
823 } else {
824 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
825 Constant *CV = Constant::getNullValue(T2->getElementType());
826 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
827 Inits.push_back(CV);
828 }
Chris Lattner8166e6e2003-05-13 21:33:43 +0000829 NG->setInitializer(ConstantArray::get(NewType, Inits));
830 Inits.clear();
831
832 // Replace any uses of the two global variables with uses of the new
833 // global...
834
835 // FIXME: This should rewrite simple/straight-forward uses such as
836 // getelementptr instructions to not use the Cast!
837 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
838 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
839 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
840
841 // Remove the two globals from the module now...
842 M->getGlobalList().erase(G1);
843 M->getGlobalList().erase(G2);
844
845 // Put the new global into the AppendingVars map so that we can handle
846 // linking of more than two vars...
847 Second->second = NG;
848 }
849 AppendingVars.erase(First);
850 }
851
852 return false;
853}
Chris Lattner52f7e902001-10-13 07:03:50 +0000854
855
856// LinkModules - This function links two modules together, with the resulting
857// left module modified to be the composite of the two input modules. If an
858// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000859// the problem. Upon failure, the Dest module could be in a modified state, and
860// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000861//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000862bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000863 if (Dest->getEndianness() == Module::AnyEndianness)
864 Dest->setEndianness(Src->getEndianness());
865 if (Dest->getPointerSize() == Module::AnyPointerSize)
866 Dest->setPointerSize(Src->getPointerSize());
867
868 if (Src->getEndianness() != Module::AnyEndianness &&
869 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000870 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000871 if (Src->getPointerSize() != Module::AnyPointerSize &&
872 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000873 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000874
875 // LinkTypes - Go through the symbol table of the Src module and see if any
876 // types are named in the src module that are not named in the Dst module.
877 // Make sure there are no type name conflicts.
878 //
879 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
880
Chris Lattner5c377c52001-10-14 23:29:15 +0000881 // ValueMap - Mapping of values from what they used to be in Src, to what they
882 // are now in Dest.
883 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000884 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000885
Chris Lattner8166e6e2003-05-13 21:33:43 +0000886 // AppendingVars - Keep track of global variables in the destination module
887 // with appending linkage. After the module is linked together, they are
888 // appended and the module is rewritten.
889 //
890 std::multimap<std::string, GlobalVariable *> AppendingVars;
891
892 // Add all of the appending globals already in the Dest module to
893 // AppendingVars.
894 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000895 if (I->hasAppendingLinkage())
896 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000897
898 // Insert all of the globals in src into the Dest module... without linking
899 // initializers (which could refer to functions not yet mapped over).
900 //
901 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000902
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000903 // Link the functions together between the two modules, without doing function
904 // bodies... this just adds external function prototypes to the Dest
905 // function... We do this so that when we begin processing function bodies,
906 // all of the global values that may be referenced are available in our
907 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000908 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000909 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000910
Chris Lattner6cdf1972002-07-18 00:13:08 +0000911 // Update the initializers in the Dest module now that all globals that may
912 // be referenced are in Dest.
913 //
914 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
915
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000916 // Link in the function bodies that are defined in the source module into the
917 // DestModule. This consists basically of copying the function over and
918 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000919 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000920 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000921
Chris Lattner8166e6e2003-05-13 21:33:43 +0000922 // If there were any appending global variables, link them together now.
923 //
924 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
925
Chris Lattner52f7e902001-10-13 07:03:50 +0000926 return false;
927}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000928
Reid Spencer567bc2c2004-05-25 08:52:20 +0000929// vim: sw=2