blob: 0be840fb6cd8189df793db59ab5325435e788857 [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 Lattner5c377c52001-10-14 23:29:15 +000020#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000021#include "llvm/SymbolTable.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/iOther.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000024#include "llvm/Constants.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000025
26// Error - Simple wrapper function to conditionally assign to E and return true.
27// This just makes error return conditions a little bit simpler...
28//
Chris Lattner8166e6e2003-05-13 21:33:43 +000029static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000030 if (E) *E = Message;
31 return true;
32}
33
John Criswell700867b2003-11-04 15:22:26 +000034//
35// Function: ResolveTypes()
36//
37// Description:
38// Attempt to link the two specified types together.
39//
40// Inputs:
41// DestTy - The type to which we wish to resolve.
42// SrcTy - The original type which we want to resolve.
43// Name - The name of the type.
44//
45// Outputs:
46// DestST - The symbol table in which the new type should be placed.
47//
48// Return value:
49// true - There is an error and the types cannot yet be linked.
50// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000051//
Chris Lattnere76c57a2003-08-22 06:07:12 +000052static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
53 SymbolTable *DestST, const std::string &Name) {
54 if (DestTy == SrcTy) return false; // If already equal, noop
55
Chris Lattner4c00e532003-05-15 16:30:55 +000056 // Does the type already exist in the module?
57 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000058 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
59 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000060 } else {
61 return true; // Cannot link types... neither is opaque and not-equal
62 }
63 } else { // Type not in dest module. Add it now.
64 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000065 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
66 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000067 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000068 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000069 }
70 return false;
71}
72
Chris Lattner43f4ba82003-08-22 19:12:55 +000073static const FunctionType *getFT(const PATypeHolder &TH) {
74 return cast<FunctionType>(TH.get());
75}
Chris Lattner9732be72003-08-22 20:16:48 +000076static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000077 return cast<StructType>(TH.get());
78}
Chris Lattnere76c57a2003-08-22 06:07:12 +000079
80// RecursiveResolveTypes - This is just like ResolveTypes, except that it
81// recurses down into derived types, merging the used types if the parent types
82// are compatible.
83//
Chris Lattnere3092c92003-08-23 21:25:54 +000084static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
85 const PATypeHolder &SrcTy,
86 SymbolTable *DestST, const std::string &Name,
87 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000088 const Type *SrcTyT = SrcTy.get();
89 const Type *DestTyT = DestTy.get();
90 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000091
92 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000093 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
94 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000095
96 // Two types cannot be resolved together if they are of different primitive
97 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +000098 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +000099
100 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +0000101 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000102 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000103 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000104 cast<FunctionType>(SrcTyT)->isVarArg() ||
105 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
106 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000107 return true;
108 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000109 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
110 getFT(SrcTy)->getContainedType(i), DestST, "",
111 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000112 return true;
113 return false;
114 }
115 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000116 if (getST(DestTy)->getNumContainedTypes() !=
117 getST(SrcTy)->getNumContainedTypes()) return 1;
118 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000119 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
120 getST(SrcTy)->getContainedType(i), DestST, "",
121 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000122 return true;
123 return false;
124 }
125 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000126 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
127 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000128 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000129 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
130 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000131 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000132 case Type::PointerTyID: {
133 // If this is a pointer type, check to see if we have already seen it. If
134 // so, we are in a recursive branch. Cut off the search now. We cannot use
135 // an associative container for this search, because the type pointers (keys
136 // in the container) change whenever types get resolved...
137 //
138 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
139 if (Pointers[i].first == DestTy)
140 return Pointers[i].second != SrcTy;
141
142 // Otherwise, add the current pointers to the vector to stop recursion on
143 // this pair.
144 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
145 bool Result =
146 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
147 cast<PointerType>(SrcTy.get())->getElementType(),
148 DestST, "", Pointers);
149 Pointers.pop_back();
150 return Result;
151 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000152 default: assert(0 && "Unexpected type!"); return true;
153 }
154}
155
Chris Lattnere3092c92003-08-23 21:25:54 +0000156static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
157 const PATypeHolder &SrcTy,
158 SymbolTable *DestST, const std::string &Name){
159 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
160 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
161}
162
Chris Lattnere76c57a2003-08-22 06:07:12 +0000163
Chris Lattner2c236f32001-11-03 05:18:24 +0000164// LinkTypes - Go through the symbol table of the Src module and see if any
165// types are named in the src module that are not named in the Dst module.
166// Make sure there are no type name conflicts.
167//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000168static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000169 SymbolTable *DestST = &Dest->getSymbolTable();
170 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000171
172 // Look for a type plane for Type's...
173 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
174 if (PI == SrcST->end()) return false; // No named types, do nothing.
175
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000176 // Some types cannot be resolved immediately because they depend on other
177 // types being resolved to each other first. This contains a list of types we
178 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000179 std::vector<std::string> DelayedTypesToResolve;
180
Chris Lattner2c236f32001-11-03 05:18:24 +0000181 const SymbolTable::VarMap &VM = PI->second;
182 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
183 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000184 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000185 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000186
187 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000188 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000189
Chris Lattner4c00e532003-05-15 16:30:55 +0000190 if (ResolveTypes(Entry, RHS, DestST, Name)) {
191 // They look different, save the types 'till later to resolve.
192 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000193 }
194 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000195
196 // Iteratively resolve types while we can...
197 while (!DelayedTypesToResolve.empty()) {
198 // Loop over all of the types, attempting to resolve them if possible...
199 unsigned OldSize = DelayedTypesToResolve.size();
200
Chris Lattnere76c57a2003-08-22 06:07:12 +0000201 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000202 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
203 const std::string &Name = DelayedTypesToResolve[i];
204 Type *T1 = cast<Type>(VM.find(Name)->second);
205 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
206 if (!ResolveTypes(T2, T1, DestST, Name)) {
207 // We are making progress!
208 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
209 --i;
210 }
211 }
212
213 // Did we not eliminate any types?
214 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000215 // Attempt to resolve subelements of types. This allows us to merge these
216 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000217 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
218 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000219 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
220 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000221
222 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
223 // We are making progress!
224 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
225
226 // Go back to the main loop, perhaps we can resolve directly by name
227 // now...
228 break;
229 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000230 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000231
232 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000233 // Report the warning and delete one of the names.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000234 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000235 const std::string &Name = DelayedTypesToResolve.back();
236
237 const Type *T1 = cast<Type>(VM.find(Name)->second);
238 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
239 std::cerr << "WARNING: Type conflict between types named '" << Name
240 << "'.\n Src='" << *T1 << "'.\n Dest='" << *T2 << "'\n";
241
242 // Remove the symbol name from the destination.
243 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000244 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000245 }
246 }
247
248
Chris Lattner2c236f32001-11-03 05:18:24 +0000249 return false;
250}
251
Chris Lattner5c2d3352003-01-30 19:53:34 +0000252static void PrintMap(const std::map<const Value*, Value*> &M) {
253 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000254 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000255 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000256 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000257 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000258 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000259 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000260 }
261}
262
263
Chris Lattner5c377c52001-10-14 23:29:15 +0000264// RemapOperand - Use LocalMap and GlobalMap to convert references from one
265// module to another. This is somewhat sophisticated in that it can
266// automatically handle constant references correctly as well...
267//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000268static Value *RemapOperand(const Value *In,
269 std::map<const Value*, Value*> &LocalMap,
270 std::map<const Value*, Value*> *GlobalMap) {
271 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000272 if (I != LocalMap.end()) return I->second;
273
274 if (GlobalMap) {
275 I = GlobalMap->find(In);
276 if (I != GlobalMap->end()) return I->second;
277 }
278
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000279 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000280 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000281 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000282 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000283
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000284 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000285
Chris Lattner18961502002-06-25 16:12:52 +0000286 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000287 const std::vector<Use> &Ops = CPA->getValues();
288 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000289 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000290 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000291 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
292 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000293 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000294 const std::vector<Use> &Ops = CPS->getValues();
295 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000296 for (unsigned i = 0; i < Ops.size(); ++i)
297 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000298 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
299 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
300 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000301 Result = const_cast<Constant*>(CPV);
302 } else if (const ConstantPointerRef *CPR =
303 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000304 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000305 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000306 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000307 if (CE->getOpcode() == Instruction::GetElementPtr) {
308 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
309 std::vector<Constant*> Indices;
310 Indices.reserve(CE->getNumOperands()-1);
311 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
312 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
313 LocalMap, GlobalMap)));
314
315 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
316 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000317 // Cast instruction
318 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000319 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000320 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000321 } else if (CE->getOpcode() == Instruction::Shl ||
322 CE->getOpcode() == Instruction::Shr) { // Shift
323 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
324 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
325 Result = ConstantExpr::getShift(CE->getOpcode(), cast<Constant>(V1),
326 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000327 } else if (CE->getNumOperands() == 2) {
328 // Binary operator...
329 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
330 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
331
332 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000333 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000334 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000335 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000336 }
337
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000338 } else {
339 assert(0 && "Unknown type of derived type constant value!");
340 }
341
342 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000343 if (GlobalMap)
344 GlobalMap->insert(std::make_pair(In, Result));
345 else
346 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000347 return Result;
348 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000349
Chris Lattner5c2d3352003-01-30 19:53:34 +0000350 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000351 PrintMap(LocalMap);
352
353 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000354 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000355 PrintMap(*GlobalMap);
356 }
357
Chris Lattner5c2d3352003-01-30 19:53:34 +0000358 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000359 assert(0 && "Couldn't remap value!");
360 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000361}
362
Chris Lattnerfcd02342003-08-23 20:31:10 +0000363/// FindGlobalNamed - Look in the specified symbol table for a global with the
364/// specified name and type. If an exactly matching global does not exist, see
365/// if there is a global which is "type compatible" with the specified
366/// name/type. This allows us to resolve things like '%x = global int*' with
367/// '%x = global opaque*'.
368///
369static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
370 SymbolTable *ST) {
371 // See if an exact match exists in the symbol table...
372 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
373
374 // It doesn't exist exactly, scan through all of the type planes in the symbol
375 // table, checking each of them for a type-compatible version.
376 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000377 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattner77c5f732003-08-24 19:30:20 +0000378 if (I->first != Type::TypeTy) {
Chris Lattnerf44c6052003-08-23 21:32:24 +0000379 SymbolTable::VarMap &VM = I->second;
John Criswell700867b2003-11-04 15:22:26 +0000380
Chris Lattnerf44c6052003-08-23 21:32:24 +0000381 // Does this type plane contain an entry with the specified name?
382 SymbolTable::type_iterator TI = VM.find(Name);
383 if (TI != VM.end()) {
John Criswell700867b2003-11-04 15:22:26 +0000384 //
385 // Ensure that this type if placed correctly into the symbol table.
386 //
387 assert(TI->second->getType() == I->first && "Type conflict!");
388
389 //
390 // Save a reference to the new type. Resolving the type can modify the
391 // symbol table, invalidating the TI variable.
392 //
393 Value *ValPtr = TI->second;
394
395 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000396 // Determine whether we can fold the two types together, resolving them.
397 // If so, we can use this value.
John Criswell700867b2003-11-04 15:22:26 +0000398 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000399 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
John Criswell700867b2003-11-04 15:22:26 +0000400 return cast<GlobalValue>(ValPtr);
Chris Lattnerf44c6052003-08-23 21:32:24 +0000401 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000402 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000403 return 0; // Otherwise, nothing could be found.
404}
405
Chris Lattner5c377c52001-10-14 23:29:15 +0000406
407// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000408// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000409//
410static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000411 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000412 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000413 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000414 // We will need a module level symbol table if the src module has a module
415 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000416 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000417
418 // Loop over all of the globals in the src module, mapping them over as we go
419 //
420 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000421 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000422 GlobalVariable *DGV = 0;
423 if (SGV->hasName()) {
424 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000425 // that may be in a module level symbol table are Global Vars and
426 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000427 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000428 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
429 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000430 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000431
Chris Lattner4ad02e72003-04-16 20:28:45 +0000432 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
433 "Global must either be external or have an initializer!");
434
Chris Lattner0fec08e2003-04-21 21:07:05 +0000435 bool SGExtern = SGV->isExternal();
436 bool DGExtern = DGV ? DGV->isExternal() : false;
437
Chris Lattner4ad02e72003-04-16 20:28:45 +0000438 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
439 // No linking to be performed, simply create an identical version of the
440 // symbol over in the dest module... the initializer will be filled in
441 // later by LinkGlobalInits...
442 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000443 GlobalVariable *NewDGV =
444 new GlobalVariable(SGV->getType()->getElementType(),
445 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
446 SGV->getName(), Dest);
447
448 // If the LLVM runtime renamed the global, but it is an externally visible
449 // symbol, DGV must be an existing global with internal linkage. Rename
450 // it.
451 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
452 assert(DGV && DGV->getName() == SGV->getName() &&
453 DGV->hasInternalLinkage());
454 DGV->setName("");
455 NewDGV->setName(SGV->getName()); // Force the name back
456 DGV->setName(SGV->getName()); // This will cause a renaming
457 assert(NewDGV->getName() == SGV->getName() &&
458 DGV->getName() != SGV->getName());
459 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000460
461 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000462 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000463 if (SGV->hasAppendingLinkage())
464 // Keep track that this is an appending variable...
465 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
466
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000467 } else if (SGV->isExternal()) {
468 // If SGV is external or if both SGV & DGV are external.. Just link the
469 // external globals, we aren't adding anything.
470 ValueMap.insert(std::make_pair(SGV, DGV));
471
472 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
473 ValueMap.insert(std::make_pair(SGV, DGV));
474 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner35956552003-10-27 16:39:39 +0000475 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000476 // At this point we know that DGV has LinkOnce, Appending, Weak, or
477 // External linkage. If DGV is Appending, this is an error.
478 if (DGV->hasAppendingLinkage())
479 return Error(Err, "Linking globals named '" + SGV->getName() +
480 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000481
482 if (SGV->isConstant() != DGV->isConstant())
483 return Error(Err, "Global Variable Collision on '" +
484 SGV->getType()->getDescription() + " %" + SGV->getName() +
485 "' - Global variables differ in const'ness");
486
Chris Lattner72ac148d2003-10-16 18:29:00 +0000487 // Otherwise, just perform the link.
488 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner35956552003-10-27 16:39:39 +0000489
490 // Linkonce+Weak = Weak
491 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
492 DGV->setLinkage(SGV->getLinkage());
493
494 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000495 // At this point we know that SGV has LinkOnce, Appending, or External
496 // linkage. If SGV is Appending, this is an error.
497 if (SGV->hasAppendingLinkage())
498 return Error(Err, "Linking globals named '" + SGV->getName() +
499 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000500
501 if (SGV->isConstant() != DGV->isConstant())
502 return Error(Err, "Global Variable Collision on '" +
503 SGV->getType()->getDescription() + " %" + SGV->getName() +
504 "' - Global variables differ in const'ness");
505
Chris Lattner72ac148d2003-10-16 18:29:00 +0000506 if (!SGV->hasLinkOnceLinkage())
507 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
508 ValueMap.insert(std::make_pair(SGV, DGV));
509
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000510 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000511 return Error(Err, "Global variables named '" + SGV->getName() +
512 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000513 } else if (SGV->hasExternalLinkage()) {
514 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000515 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000516 return Error(Err, "Global Variable Collision on '" +
517 SGV->getType()->getDescription() + " %" + SGV->getName() +
518 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000519
520 if (SGV->getInitializer() != DGV->getInitializer())
521 return Error(Err, "Global Variable Collision on '" +
522 SGV->getType()->getDescription() + " %" + SGV->getName() +
523 "' - External linkage globals have different initializers");
524
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000525 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000526 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000527 // No linking is performed yet. Just insert a new copy of the global, and
528 // keep track of the fact that it is an appending variable in the
529 // AppendingVars map. The name is cleared out so that no linkage is
530 // performed.
531 GlobalVariable *NewDGV =
532 new GlobalVariable(SGV->getType()->getElementType(),
533 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
534 "", Dest);
535
536 // Make sure to remember this mapping...
537 ValueMap.insert(std::make_pair(SGV, NewDGV));
538
539 // Keep track that this is an appending variable...
540 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000541 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000542 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000543 }
544 }
545 return false;
546}
547
548
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000549// LinkGlobalInits - Update the initializers in the Dest module now that all
550// globals that may be referenced are in Dest.
551//
552static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000553 std::map<const Value*, Value*> &ValueMap,
554 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000555
556 // Loop over all of the globals in the src module, mapping them over as we go
557 //
558 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000559 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000560
561 if (SGV->hasInitializer()) { // Only process initialized GV's
562 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000563 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000564 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000565
566 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000567 if (DGV->hasInitializer()) {
568 assert(SGV->getLinkage() == DGV->getLinkage());
569 if (SGV->hasExternalLinkage()) {
570 if (DGV->getInitializer() != SInit)
571 return Error(Err, "Global Variable Collision on '" +
572 SGV->getType()->getDescription() +"':%"+SGV->getName()+
573 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000574 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000575 // Nothing is required, mapped values will take the new global
576 // automatically.
577 } else if (DGV->hasAppendingLinkage()) {
578 assert(0 && "Appending linkage unimplemented!");
579 } else {
580 assert(0 && "Unknown linkage!");
581 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000582 } else {
583 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000584 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000585 }
586 }
587 }
588 return false;
589}
Chris Lattner5c377c52001-10-14 23:29:15 +0000590
Chris Lattner79df7c02002-03-26 18:01:55 +0000591// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000592// without doing function bodies... this just adds external function prototypes
593// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000594//
Chris Lattner79df7c02002-03-26 18:01:55 +0000595static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000596 std::map<const Value*, Value*> &ValueMap,
597 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000598 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000599
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000600 // Loop over all of the functions in the src module, mapping them over as we
601 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000602 //
603 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000604 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000605 Function *DF = 0;
606 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000607 // The same named thing is a Function, because the only two things
608 // that may be in a module level symbol table are Global Vars and
609 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000610 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000611 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
612 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000613
Chris Lattner4ad02e72003-04-16 20:28:45 +0000614 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000615 // Function does not already exist, simply insert an function signature
616 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000617 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
618 SF->getName(), Dest);
619
620 // If the LLVM runtime renamed the function, but it is an externally
621 // visible symbol, DF must be an existing function with internal linkage.
622 // Rename it.
623 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
624 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
625 DF->setName("");
626 NewDF->setName(SF->getName()); // Force the name back
627 DF->setName(SF->getName()); // This will cause a renaming
628 assert(NewDF->getName() == SF->getName() &&
629 DF->getName() != SF->getName());
630 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000631
632 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000633 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000634 } else if (SF->isExternal()) {
635 // If SF is external or if both SF & DF are external.. Just link the
636 // external functions, we aren't adding anything.
637 ValueMap.insert(std::make_pair(SF, DF));
638 } else if (DF->isExternal()) { // If DF is external but SF is not...
639 // Link the external functions, update linkage qualifiers
640 ValueMap.insert(std::make_pair(SF, DF));
641 DF->setLinkage(SF->getLinkage());
642
Chris Lattner35956552003-10-27 16:39:39 +0000643 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000644 // At this point we know that DF has LinkOnce, Weak, or External linkage.
645 ValueMap.insert(std::make_pair(SF, DF));
646
Chris Lattner35956552003-10-27 16:39:39 +0000647 // Linkonce+Weak = Weak
648 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
649 DF->setLinkage(SF->getLinkage());
650
651 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000652 // At this point we know that SF has LinkOnce or External linkage.
653 ValueMap.insert(std::make_pair(SF, DF));
654 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
655 DF->setLinkage(SF->getLinkage());
656
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000657 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000658 return Error(Err, "Functions named '" + SF->getName() +
659 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000660 } else if (SF->hasExternalLinkage()) {
661 // The function is defined in both modules!!
662 return Error(Err, "Function '" +
663 SF->getFunctionType()->getDescription() + "':\"" +
664 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000665 } else {
666 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000667 }
668 }
669 return false;
670}
671
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000672// LinkFunctionBody - Copy the source function over into the dest function and
673// fix up references to values. At this point we know that Dest is an external
674// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000675//
Chris Lattner79df7c02002-03-26 18:01:55 +0000676static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000677 std::map<const Value*, Value*> &GlobalMap,
678 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000679 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000680 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000681
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000682 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000683 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000684 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000685 I != E; ++I, ++DI) {
686 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000687
688 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000689 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000690 }
691
692 // Loop over all of the basic blocks, copying the instructions over...
693 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000694 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000695 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000696 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
697 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000698
699 // Loop over all of the instructions in the src basic block, copying them
700 // over. Note that this is broken in a strict sense because the cloned
701 // instructions will still be referencing values in the Src module, not
702 // the remapped values. In our case, however, we will not get caught and
703 // so we can delay patching the values up until later...
704 //
Chris Lattner18961502002-06-25 16:12:52 +0000705 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000706 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000707 Instruction *DI = II->clone();
708 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000709 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000710 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000711 }
712 }
713
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000714 // At this point, all of the instructions and values of the function are now
715 // copied over. The only problem is that they are still referencing values in
716 // the Source function as operands. Loop through all of the operands of the
717 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000718 //
Chris Lattner18961502002-06-25 16:12:52 +0000719 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
720 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
721 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000722 OI != OE; ++OI)
723 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000724
725 return false;
726}
727
728
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000729// LinkFunctionBodies - Link in the function bodies that are defined in the
730// source module into the DestModule. This consists basically of copying the
731// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000732//
Chris Lattner79df7c02002-03-26 18:01:55 +0000733static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000734 std::map<const Value*, Value*> &ValueMap,
735 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000736
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000737 // Loop over all of the functions in the src module, mapping them over as we
738 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000739 //
Chris Lattner18961502002-06-25 16:12:52 +0000740 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
741 if (!SF->isExternal()) { // No body if function is external
742 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000743
Chris Lattner18961502002-06-25 16:12:52 +0000744 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000745 if (DF->isExternal()) {
746 // Only provide the function body if there isn't one already.
747 if (LinkFunctionBody(DF, SF, ValueMap, Err))
748 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000749 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000750 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000751 }
752 return false;
753}
754
Chris Lattner8166e6e2003-05-13 21:33:43 +0000755// LinkAppendingVars - If there were any appending global variables, link them
756// together now. Return true on error.
757//
758static bool LinkAppendingVars(Module *M,
759 std::multimap<std::string, GlobalVariable *> &AppendingVars,
760 std::string *ErrorMsg) {
761 if (AppendingVars.empty()) return false; // Nothing to do.
762
763 // Loop over the multimap of appending vars, processing any variables with the
764 // same name, forming a new appending global variable with both of the
765 // initializers merged together, then rewrite references to the old variables
766 // and delete them.
767 //
768 std::vector<Constant*> Inits;
769 while (AppendingVars.size() > 1) {
770 // Get the first two elements in the map...
771 std::multimap<std::string,
772 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
773
774 // If the first two elements are for different names, there is no pair...
775 // Otherwise there is a pair, so link them together...
776 if (First->first == Second->first) {
777 GlobalVariable *G1 = First->second, *G2 = Second->second;
778 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
779 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
780
781 // Check to see that they two arrays agree on type...
782 if (T1->getElementType() != T2->getElementType())
783 return Error(ErrorMsg,
784 "Appending variables with different element types need to be linked!");
785 if (G1->isConstant() != G2->isConstant())
786 return Error(ErrorMsg,
787 "Appending variables linked with different const'ness!");
788
789 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
790 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
791
792 // Create the new global variable...
793 GlobalVariable *NG =
794 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
795 /*init*/0, First->first, M);
796
797 // Merge the initializer...
798 Inits.reserve(NewSize);
799 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
800 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
801 Inits.push_back(cast<Constant>(I->getValues()[i]));
802 I = cast<ConstantArray>(G2->getInitializer());
803 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
804 Inits.push_back(cast<Constant>(I->getValues()[i]));
805 NG->setInitializer(ConstantArray::get(NewType, Inits));
806 Inits.clear();
807
808 // Replace any uses of the two global variables with uses of the new
809 // global...
810
811 // FIXME: This should rewrite simple/straight-forward uses such as
812 // getelementptr instructions to not use the Cast!
813 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
814 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
815 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
816
817 // Remove the two globals from the module now...
818 M->getGlobalList().erase(G1);
819 M->getGlobalList().erase(G2);
820
821 // Put the new global into the AppendingVars map so that we can handle
822 // linking of more than two vars...
823 Second->second = NG;
824 }
825 AppendingVars.erase(First);
826 }
827
828 return false;
829}
Chris Lattner52f7e902001-10-13 07:03:50 +0000830
831
832// LinkModules - This function links two modules together, with the resulting
833// left module modified to be the composite of the two input modules. If an
834// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000835// the problem. Upon failure, the Dest module could be in a modified state, and
836// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000837//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000838bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000839 if (Dest->getEndianness() == Module::AnyEndianness)
840 Dest->setEndianness(Src->getEndianness());
841 if (Dest->getPointerSize() == Module::AnyPointerSize)
842 Dest->setPointerSize(Src->getPointerSize());
843
844 if (Src->getEndianness() != Module::AnyEndianness &&
845 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000846 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000847 if (Src->getPointerSize() != Module::AnyPointerSize &&
848 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000849 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000850
851 // LinkTypes - Go through the symbol table of the Src module and see if any
852 // types are named in the src module that are not named in the Dst module.
853 // Make sure there are no type name conflicts.
854 //
855 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
856
Chris Lattner5c377c52001-10-14 23:29:15 +0000857 // ValueMap - Mapping of values from what they used to be in Src, to what they
858 // are now in Dest.
859 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000860 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000861
Chris Lattner8166e6e2003-05-13 21:33:43 +0000862 // AppendingVars - Keep track of global variables in the destination module
863 // with appending linkage. After the module is linked together, they are
864 // appended and the module is rewritten.
865 //
866 std::multimap<std::string, GlobalVariable *> AppendingVars;
867
868 // Add all of the appending globals already in the Dest module to
869 // AppendingVars.
870 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000871 if (I->hasAppendingLinkage())
872 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000873
874 // Insert all of the globals in src into the Dest module... without linking
875 // initializers (which could refer to functions not yet mapped over).
876 //
877 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000878
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000879 // Link the functions together between the two modules, without doing function
880 // bodies... this just adds external function prototypes to the Dest
881 // function... We do this so that when we begin processing function bodies,
882 // all of the global values that may be referenced are available in our
883 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000884 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000885 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000886
Chris Lattner6cdf1972002-07-18 00:13:08 +0000887 // Update the initializers in the Dest module now that all globals that may
888 // be referenced are in Dest.
889 //
890 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
891
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000892 // Link in the function bodies that are defined in the source module into the
893 // DestModule. This consists basically of copying the function over and
894 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000895 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000896 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000897
Chris Lattner8166e6e2003-05-13 21:33:43 +0000898 // If there were any appending global variables, link them together now.
899 //
900 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
901
Chris Lattner52f7e902001-10-13 07:03:50 +0000902 return false;
903}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000904