blob: 1d002c5821be688e732e3f60389eaa5a64e0bae1 [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
Chris Lattner4c00e532003-05-15 16:30:55 +000034// ResolveTypes - Attempt to link the two specified types together. Return true
35// if there is an error and they cannot yet be linked.
36//
Chris Lattnere76c57a2003-08-22 06:07:12 +000037static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
38 SymbolTable *DestST, const std::string &Name) {
39 if (DestTy == SrcTy) return false; // If already equal, noop
40
Chris Lattner4c00e532003-05-15 16:30:55 +000041 // Does the type already exist in the module?
42 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000043 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
44 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000045 } else {
46 return true; // Cannot link types... neither is opaque and not-equal
47 }
48 } else { // Type not in dest module. Add it now.
49 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000050 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
51 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000052 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000053 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000054 }
55 return false;
56}
57
Chris Lattner43f4ba82003-08-22 19:12:55 +000058static const FunctionType *getFT(const PATypeHolder &TH) {
59 return cast<FunctionType>(TH.get());
60}
Chris Lattner9732be72003-08-22 20:16:48 +000061static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000062 return cast<StructType>(TH.get());
63}
Chris Lattnere76c57a2003-08-22 06:07:12 +000064
65// RecursiveResolveTypes - This is just like ResolveTypes, except that it
66// recurses down into derived types, merging the used types if the parent types
67// are compatible.
68//
Chris Lattnere3092c92003-08-23 21:25:54 +000069static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
70 const PATypeHolder &SrcTy,
71 SymbolTable *DestST, const std::string &Name,
72 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000073 const Type *SrcTyT = SrcTy.get();
74 const Type *DestTyT = DestTy.get();
75 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +000076
77 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000078 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
79 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +000080
81 // Two types cannot be resolved together if they are of different primitive
82 // type. For example, we cannot resolve an int to a float.
Chris Lattner43f4ba82003-08-22 19:12:55 +000083 if (DestTyT->getPrimitiveID() != SrcTyT->getPrimitiveID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +000084
85 // Otherwise, resolve the used type used by this derived type...
Chris Lattner43f4ba82003-08-22 19:12:55 +000086 switch (DestTyT->getPrimitiveID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000087 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +000088 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +000089 cast<FunctionType>(SrcTyT)->isVarArg() ||
90 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
91 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +000092 return true;
93 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +000094 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
95 getFT(SrcTy)->getContainedType(i), DestST, "",
96 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +000097 return true;
98 return false;
99 }
100 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000101 if (getST(DestTy)->getNumContainedTypes() !=
102 getST(SrcTy)->getNumContainedTypes()) return 1;
103 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000104 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
105 getST(SrcTy)->getContainedType(i), DestST, "",
106 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000107 return true;
108 return false;
109 }
110 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000111 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
112 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000113 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000114 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
115 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000116 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000117 case Type::PointerTyID: {
118 // If this is a pointer type, check to see if we have already seen it. If
119 // so, we are in a recursive branch. Cut off the search now. We cannot use
120 // an associative container for this search, because the type pointers (keys
121 // in the container) change whenever types get resolved...
122 //
123 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
124 if (Pointers[i].first == DestTy)
125 return Pointers[i].second != SrcTy;
126
127 // Otherwise, add the current pointers to the vector to stop recursion on
128 // this pair.
129 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
130 bool Result =
131 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
132 cast<PointerType>(SrcTy.get())->getElementType(),
133 DestST, "", Pointers);
134 Pointers.pop_back();
135 return Result;
136 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000137 default: assert(0 && "Unexpected type!"); return true;
138 }
139}
140
Chris Lattnere3092c92003-08-23 21:25:54 +0000141static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
142 const PATypeHolder &SrcTy,
143 SymbolTable *DestST, const std::string &Name){
144 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
145 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
146}
147
Chris Lattnere76c57a2003-08-22 06:07:12 +0000148
Chris Lattner2c236f32001-11-03 05:18:24 +0000149// LinkTypes - Go through the symbol table of the Src module and see if any
150// types are named in the src module that are not named in the Dst module.
151// Make sure there are no type name conflicts.
152//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000153static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000154 SymbolTable *DestST = &Dest->getSymbolTable();
155 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000156
157 // Look for a type plane for Type's...
158 SymbolTable::const_iterator PI = SrcST->find(Type::TypeTy);
159 if (PI == SrcST->end()) return false; // No named types, do nothing.
160
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000161 // Some types cannot be resolved immediately because they depend on other
162 // types being resolved to each other first. This contains a list of types we
163 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000164 std::vector<std::string> DelayedTypesToResolve;
165
Chris Lattner2c236f32001-11-03 05:18:24 +0000166 const SymbolTable::VarMap &VM = PI->second;
167 for (SymbolTable::type_const_iterator I = VM.begin(), E = VM.end();
168 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000169 const std::string &Name = I->first;
Chris Lattner4c00e532003-05-15 16:30:55 +0000170 Type *RHS = cast<Type>(I->second);
Chris Lattner2c236f32001-11-03 05:18:24 +0000171
172 // Check to see if this type name is already in the dest module...
Chris Lattner4c00e532003-05-15 16:30:55 +0000173 Type *Entry = cast_or_null<Type>(DestST->lookup(Type::TypeTy, Name));
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000174
Chris Lattner4c00e532003-05-15 16:30:55 +0000175 if (ResolveTypes(Entry, RHS, DestST, Name)) {
176 // They look different, save the types 'till later to resolve.
177 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000178 }
179 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000180
181 // Iteratively resolve types while we can...
182 while (!DelayedTypesToResolve.empty()) {
183 // Loop over all of the types, attempting to resolve them if possible...
184 unsigned OldSize = DelayedTypesToResolve.size();
185
Chris Lattnere76c57a2003-08-22 06:07:12 +0000186 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000187 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
188 const std::string &Name = DelayedTypesToResolve[i];
189 Type *T1 = cast<Type>(VM.find(Name)->second);
190 Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
191 if (!ResolveTypes(T2, T1, DestST, Name)) {
192 // We are making progress!
193 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
194 --i;
195 }
196 }
197
198 // Did we not eliminate any types?
199 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000200 // Attempt to resolve subelements of types. This allows us to merge these
201 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000202 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
203 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattner43f4ba82003-08-22 19:12:55 +0000204 PATypeHolder T1(cast<Type>(VM.find(Name)->second));
205 PATypeHolder T2(cast<Type>(DestST->lookup(Type::TypeTy, Name)));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000206
207 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
208 // We are making progress!
209 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
210
211 // Go back to the main loop, perhaps we can resolve directly by name
212 // now...
213 break;
214 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000215 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000216
217 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000218 // Report the warning and delete one of the names.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000219 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000220 const std::string &Name = DelayedTypesToResolve.back();
221
222 const Type *T1 = cast<Type>(VM.find(Name)->second);
223 const Type *T2 = cast<Type>(DestST->lookup(Type::TypeTy, Name));
224 std::cerr << "WARNING: Type conflict between types named '" << Name
225 << "'.\n Src='" << *T1 << "'.\n Dest='" << *T2 << "'\n";
226
227 // Remove the symbol name from the destination.
228 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000229 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000230 }
231 }
232
233
Chris Lattner2c236f32001-11-03 05:18:24 +0000234 return false;
235}
236
Chris Lattner5c2d3352003-01-30 19:53:34 +0000237static void PrintMap(const std::map<const Value*, Value*> &M) {
238 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000239 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000240 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000241 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000242 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000243 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000244 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000245 }
246}
247
248
Chris Lattner5c377c52001-10-14 23:29:15 +0000249// RemapOperand - Use LocalMap and GlobalMap to convert references from one
250// module to another. This is somewhat sophisticated in that it can
251// automatically handle constant references correctly as well...
252//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000253static Value *RemapOperand(const Value *In,
254 std::map<const Value*, Value*> &LocalMap,
255 std::map<const Value*, Value*> *GlobalMap) {
256 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000257 if (I != LocalMap.end()) return I->second;
258
259 if (GlobalMap) {
260 I = GlobalMap->find(In);
261 if (I != GlobalMap->end()) return I->second;
262 }
263
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000264 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000265 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattner6cdf1972002-07-18 00:13:08 +0000266 if (!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000267 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000268
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000269 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000270
Chris Lattner18961502002-06-25 16:12:52 +0000271 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000272 const std::vector<Use> &Ops = CPA->getValues();
273 std::vector<Constant*> Operands(Ops.size());
Chris Lattnere306d942002-07-18 02:31:03 +0000274 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000275 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000276 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
277 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000278 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Chris Lattner697954c2002-01-20 22:54:45 +0000279 const std::vector<Use> &Ops = CPS->getValues();
280 std::vector<Constant*> Operands(Ops.size());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000281 for (unsigned i = 0; i < Ops.size(); ++i)
282 Operands[i] =
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000283 cast<Constant>(RemapOperand(Ops[i], LocalMap, GlobalMap));
284 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
285 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000286 Result = const_cast<Constant*>(CPV);
287 } else if (const ConstantPointerRef *CPR =
288 dyn_cast<ConstantPointerRef>(CPV)) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000289 Value *V = RemapOperand(CPR->getValue(), LocalMap, GlobalMap);
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000290 Result = ConstantPointerRef::get(cast<GlobalValue>(V));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000291 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000292 if (CE->getOpcode() == Instruction::GetElementPtr) {
293 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
294 std::vector<Constant*> Indices;
295 Indices.reserve(CE->getNumOperands()-1);
296 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
297 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
298 LocalMap, GlobalMap)));
299
300 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
301 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000302 // Cast instruction
303 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000304 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000305 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattner6cdf1972002-07-18 00:13:08 +0000306 } else if (CE->getNumOperands() == 2) {
307 // Binary operator...
308 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
309 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
310
311 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnere8e46052002-07-30 18:54:22 +0000312 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000313 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000314 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000315 }
316
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000317 } else {
318 assert(0 && "Unknown type of derived type constant value!");
319 }
320
321 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000322 if (GlobalMap)
323 GlobalMap->insert(std::make_pair(In, Result));
324 else
325 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000326 return Result;
327 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000328
Chris Lattner5c2d3352003-01-30 19:53:34 +0000329 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000330 PrintMap(LocalMap);
331
332 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000333 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000334 PrintMap(*GlobalMap);
335 }
336
Chris Lattner5c2d3352003-01-30 19:53:34 +0000337 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000338 assert(0 && "Couldn't remap value!");
339 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000340}
341
Chris Lattnerfcd02342003-08-23 20:31:10 +0000342/// FindGlobalNamed - Look in the specified symbol table for a global with the
343/// specified name and type. If an exactly matching global does not exist, see
344/// if there is a global which is "type compatible" with the specified
345/// name/type. This allows us to resolve things like '%x = global int*' with
346/// '%x = global opaque*'.
347///
348static GlobalValue *FindGlobalNamed(const std::string &Name, const Type *Ty,
349 SymbolTable *ST) {
350 // See if an exact match exists in the symbol table...
351 if (Value *V = ST->lookup(Ty, Name)) return cast<GlobalValue>(V);
352
353 // It doesn't exist exactly, scan through all of the type planes in the symbol
354 // table, checking each of them for a type-compatible version.
355 //
Chris Lattnerf44c6052003-08-23 21:32:24 +0000356 for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
Chris Lattner77c5f732003-08-24 19:30:20 +0000357 if (I->first != Type::TypeTy) {
Chris Lattnerf44c6052003-08-23 21:32:24 +0000358 SymbolTable::VarMap &VM = I->second;
359 // Does this type plane contain an entry with the specified name?
360 SymbolTable::type_iterator TI = VM.find(Name);
361 if (TI != VM.end()) {
362 // Determine whether we can fold the two types together, resolving them.
363 // If so, we can use this value.
364 if (!RecursiveResolveTypes(Ty, I->first, ST, ""))
365 return cast<GlobalValue>(TI->second);
366 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000367 }
Chris Lattnerfcd02342003-08-23 20:31:10 +0000368 return 0; // Otherwise, nothing could be found.
369}
370
Chris Lattner5c377c52001-10-14 23:29:15 +0000371
372// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000373// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000374//
375static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000376 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000377 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000378 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000379 // We will need a module level symbol table if the src module has a module
380 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000381 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000382
383 // Loop over all of the globals in the src module, mapping them over as we go
384 //
385 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000386 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000387 GlobalVariable *DGV = 0;
388 if (SGV->hasName()) {
389 // A same named thing is a global variable, because the only two things
Chris Lattner79df7c02002-03-26 18:01:55 +0000390 // that may be in a module level symbol table are Global Vars and
391 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000392 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000393 DGV = cast_or_null<GlobalVariable>(FindGlobalNamed(SGV->getName(),
394 SGV->getType(), ST));
Chris Lattner4ad02e72003-04-16 20:28:45 +0000395 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000396
Chris Lattner4ad02e72003-04-16 20:28:45 +0000397 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
398 "Global must either be external or have an initializer!");
399
Chris Lattner0fec08e2003-04-21 21:07:05 +0000400 bool SGExtern = SGV->isExternal();
401 bool DGExtern = DGV ? DGV->isExternal() : false;
402
Chris Lattner4ad02e72003-04-16 20:28:45 +0000403 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
404 // No linking to be performed, simply create an identical version of the
405 // symbol over in the dest module... the initializer will be filled in
406 // later by LinkGlobalInits...
407 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000408 GlobalVariable *NewDGV =
409 new GlobalVariable(SGV->getType()->getElementType(),
410 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
411 SGV->getName(), Dest);
412
413 // If the LLVM runtime renamed the global, but it is an externally visible
414 // symbol, DGV must be an existing global with internal linkage. Rename
415 // it.
416 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage()){
417 assert(DGV && DGV->getName() == SGV->getName() &&
418 DGV->hasInternalLinkage());
419 DGV->setName("");
420 NewDGV->setName(SGV->getName()); // Force the name back
421 DGV->setName(SGV->getName()); // This will cause a renaming
422 assert(NewDGV->getName() == SGV->getName() &&
423 DGV->getName() != SGV->getName());
424 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000425
426 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000427 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000428 if (SGV->hasAppendingLinkage())
429 // Keep track that this is an appending variable...
430 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
431
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000432 } else if (SGV->isExternal()) {
433 // If SGV is external or if both SGV & DGV are external.. Just link the
434 // external globals, we aren't adding anything.
435 ValueMap.insert(std::make_pair(SGV, DGV));
436
437 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
438 ValueMap.insert(std::make_pair(SGV, DGV));
439 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner72ac148d2003-10-16 18:29:00 +0000440 } else if (SGV->hasWeakLinkage()) {
441 // At this point we know that DGV has LinkOnce, Appending, Weak, or
442 // External linkage. If DGV is Appending, this is an error.
443 if (DGV->hasAppendingLinkage())
444 return Error(Err, "Linking globals named '" + SGV->getName() +
445 " ' with 'weak' and 'appending' linkage is not allowed!");
446 // Otherwise, just perform the link.
447 ValueMap.insert(std::make_pair(SGV, DGV));
448 } else if (DGV->hasWeakLinkage()) {
449 // At this point we know that SGV has LinkOnce, Appending, or External
450 // linkage. If SGV is Appending, this is an error.
451 if (SGV->hasAppendingLinkage())
452 return Error(Err, "Linking globals named '" + SGV->getName() +
453 " ' with 'weak' and 'appending' linkage is not allowed!");
454 if (!SGV->hasLinkOnceLinkage())
455 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
456 ValueMap.insert(std::make_pair(SGV, DGV));
457
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000458 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000459 return Error(Err, "Global variables named '" + SGV->getName() +
460 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000461 } else if (SGV->hasExternalLinkage()) {
462 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000463 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000464 return Error(Err, "Global Variable Collision on '" +
465 SGV->getType()->getDescription() + " %" + SGV->getName() +
466 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000467
468 if (SGV->getInitializer() != DGV->getInitializer())
469 return Error(Err, "Global Variable Collision on '" +
470 SGV->getType()->getDescription() + " %" + SGV->getName() +
471 "' - External linkage globals have different initializers");
472
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000473 ValueMap.insert(std::make_pair(SGV, DGV));
474 } else if (SGV->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000475 // If the global variable has a name, and that name is already in use in
476 // the Dest module, make sure that the name is a compatible global
477 // variable...
478 //
Chris Lattner5c377c52001-10-14 23:29:15 +0000479 // Check to see if the two GV's have the same Const'ness...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000480 if (SGV->isConstant() != DGV->isConstant())
Chris Lattner5c377c52001-10-14 23:29:15 +0000481 return Error(Err, "Global Variable Collision on '" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000482 SGV->getType()->getDescription() + " %" + SGV->getName() +
483 "' - Global variables differ in const'ness");
Chris Lattner0fec08e2003-04-21 21:07:05 +0000484
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000485 // Okay, everything is cool, remember the mapping...
Chris Lattner697954c2002-01-20 22:54:45 +0000486 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000487 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000488 // No linking is performed yet. Just insert a new copy of the global, and
489 // keep track of the fact that it is an appending variable in the
490 // AppendingVars map. The name is cleared out so that no linkage is
491 // performed.
492 GlobalVariable *NewDGV =
493 new GlobalVariable(SGV->getType()->getElementType(),
494 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
495 "", Dest);
496
497 // Make sure to remember this mapping...
498 ValueMap.insert(std::make_pair(SGV, NewDGV));
499
500 // Keep track that this is an appending variable...
501 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000502 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000503 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000504 }
505 }
506 return false;
507}
508
509
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000510// LinkGlobalInits - Update the initializers in the Dest module now that all
511// globals that may be referenced are in Dest.
512//
513static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000514 std::map<const Value*, Value*> &ValueMap,
515 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000516
517 // Loop over all of the globals in the src module, mapping them over as we go
518 //
519 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000520 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000521
522 if (SGV->hasInitializer()) { // Only process initialized GV's
523 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000524 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000525 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000526
527 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000528 if (DGV->hasInitializer()) {
529 assert(SGV->getLinkage() == DGV->getLinkage());
530 if (SGV->hasExternalLinkage()) {
531 if (DGV->getInitializer() != SInit)
532 return Error(Err, "Global Variable Collision on '" +
533 SGV->getType()->getDescription() +"':%"+SGV->getName()+
534 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000535 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000536 // Nothing is required, mapped values will take the new global
537 // automatically.
538 } else if (DGV->hasAppendingLinkage()) {
539 assert(0 && "Appending linkage unimplemented!");
540 } else {
541 assert(0 && "Unknown linkage!");
542 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000543 } else {
544 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000545 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000546 }
547 }
548 }
549 return false;
550}
Chris Lattner5c377c52001-10-14 23:29:15 +0000551
Chris Lattner79df7c02002-03-26 18:01:55 +0000552// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000553// without doing function bodies... this just adds external function prototypes
554// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000555//
Chris Lattner79df7c02002-03-26 18:01:55 +0000556static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000557 std::map<const Value*, Value*> &ValueMap,
558 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000559 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000560
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000561 // Loop over all of the functions in the src module, mapping them over as we
562 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000563 //
564 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000565 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000566 Function *DF = 0;
567 if (SF->hasName())
Chris Lattner79df7c02002-03-26 18:01:55 +0000568 // The same named thing is a Function, because the only two things
569 // that may be in a module level symbol table are Global Vars and
570 // Functions, and they both have distinct, nonoverlapping, possible types.
Chris Lattner5c377c52001-10-14 23:29:15 +0000571 //
Chris Lattnerfcd02342003-08-23 20:31:10 +0000572 DF = cast_or_null<Function>(FindGlobalNamed(SF->getName(), SF->getType(),
573 ST));
Chris Lattner5c377c52001-10-14 23:29:15 +0000574
Chris Lattner4ad02e72003-04-16 20:28:45 +0000575 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000576 // Function does not already exist, simply insert an function signature
577 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000578 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
579 SF->getName(), Dest);
580
581 // If the LLVM runtime renamed the function, but it is an externally
582 // visible symbol, DF must be an existing function with internal linkage.
583 // Rename it.
584 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage()) {
585 assert(DF && DF->getName() == SF->getName() &&DF->hasInternalLinkage());
586 DF->setName("");
587 NewDF->setName(SF->getName()); // Force the name back
588 DF->setName(SF->getName()); // This will cause a renaming
589 assert(NewDF->getName() == SF->getName() &&
590 DF->getName() != SF->getName());
591 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000592
593 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000594 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000595 } else if (SF->isExternal()) {
596 // If SF is external or if both SF & DF are external.. Just link the
597 // external functions, we aren't adding anything.
598 ValueMap.insert(std::make_pair(SF, DF));
599 } else if (DF->isExternal()) { // If DF is external but SF is not...
600 // Link the external functions, update linkage qualifiers
601 ValueMap.insert(std::make_pair(SF, DF));
602 DF->setLinkage(SF->getLinkage());
603
Chris Lattner72ac148d2003-10-16 18:29:00 +0000604 } else if (SF->hasWeakLinkage()) {
605 // At this point we know that DF has LinkOnce, Weak, or External linkage.
606 ValueMap.insert(std::make_pair(SF, DF));
607
608 } else if (DF->hasWeakLinkage()) {
609 // At this point we know that SF has LinkOnce or External linkage.
610 ValueMap.insert(std::make_pair(SF, DF));
611 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
612 DF->setLinkage(SF->getLinkage());
613
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000614 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000615 return Error(Err, "Functions named '" + SF->getName() +
616 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000617 } else if (SF->hasExternalLinkage()) {
618 // The function is defined in both modules!!
619 return Error(Err, "Function '" +
620 SF->getFunctionType()->getDescription() + "':\"" +
621 SF->getName() + "\" - Function is already defined!");
622 } else if (SF->hasLinkOnceLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000623 // Completely ignore the source function.
Chris Lattner18961502002-06-25 16:12:52 +0000624 ValueMap.insert(std::make_pair(SF, DF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000625 } else {
626 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000627 }
628 }
629 return false;
630}
631
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000632// LinkFunctionBody - Copy the source function over into the dest function and
633// fix up references to values. At this point we know that Dest is an external
634// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000635//
Chris Lattner79df7c02002-03-26 18:01:55 +0000636static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000637 std::map<const Value*, Value*> &GlobalMap,
638 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000639 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000640 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000641
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000642 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000643 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000644 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000645 I != E; ++I, ++DI) {
646 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000647
648 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000649 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000650 }
651
652 // Loop over all of the basic blocks, copying the instructions over...
653 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000654 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000655 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000656 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
657 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000658
659 // Loop over all of the instructions in the src basic block, copying them
660 // over. Note that this is broken in a strict sense because the cloned
661 // instructions will still be referencing values in the Src module, not
662 // the remapped values. In our case, however, we will not get caught and
663 // so we can delay patching the values up until later...
664 //
Chris Lattner18961502002-06-25 16:12:52 +0000665 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000666 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000667 Instruction *DI = II->clone();
668 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000669 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000670 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000671 }
672 }
673
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000674 // At this point, all of the instructions and values of the function are now
675 // copied over. The only problem is that they are still referencing values in
676 // the Source function as operands. Loop through all of the operands of the
677 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000678 //
Chris Lattner18961502002-06-25 16:12:52 +0000679 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
680 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
681 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000682 OI != OE; ++OI)
683 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000684
685 return false;
686}
687
688
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000689// LinkFunctionBodies - Link in the function bodies that are defined in the
690// source module into the DestModule. This consists basically of copying the
691// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000692//
Chris Lattner79df7c02002-03-26 18:01:55 +0000693static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000694 std::map<const Value*, Value*> &ValueMap,
695 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000696
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000697 // Loop over all of the functions in the src module, mapping them over as we
698 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000699 //
Chris Lattner18961502002-06-25 16:12:52 +0000700 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
701 if (!SF->isExternal()) { // No body if function is external
702 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000703
Chris Lattner18961502002-06-25 16:12:52 +0000704 // DF not external SF external?
705 if (!DF->isExternal()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000706 if (DF->hasLinkOnceLinkage()) continue; // No relinkage for link-once!
Chris Lattner72ac148d2003-10-16 18:29:00 +0000707 if (SF->hasWeakLinkage()) continue;
708 return Error(Err, "Function '" + SF->getName() +
709 "' body multiply defined!");
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000710 }
711
Chris Lattner18961502002-06-25 16:12:52 +0000712 if (LinkFunctionBody(DF, SF, ValueMap, Err)) return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000713 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000714 }
715 return false;
716}
717
Chris Lattner8166e6e2003-05-13 21:33:43 +0000718// LinkAppendingVars - If there were any appending global variables, link them
719// together now. Return true on error.
720//
721static bool LinkAppendingVars(Module *M,
722 std::multimap<std::string, GlobalVariable *> &AppendingVars,
723 std::string *ErrorMsg) {
724 if (AppendingVars.empty()) return false; // Nothing to do.
725
726 // Loop over the multimap of appending vars, processing any variables with the
727 // same name, forming a new appending global variable with both of the
728 // initializers merged together, then rewrite references to the old variables
729 // and delete them.
730 //
731 std::vector<Constant*> Inits;
732 while (AppendingVars.size() > 1) {
733 // Get the first two elements in the map...
734 std::multimap<std::string,
735 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
736
737 // If the first two elements are for different names, there is no pair...
738 // Otherwise there is a pair, so link them together...
739 if (First->first == Second->first) {
740 GlobalVariable *G1 = First->second, *G2 = Second->second;
741 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
742 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
743
744 // Check to see that they two arrays agree on type...
745 if (T1->getElementType() != T2->getElementType())
746 return Error(ErrorMsg,
747 "Appending variables with different element types need to be linked!");
748 if (G1->isConstant() != G2->isConstant())
749 return Error(ErrorMsg,
750 "Appending variables linked with different const'ness!");
751
752 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
753 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
754
755 // Create the new global variable...
756 GlobalVariable *NG =
757 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
758 /*init*/0, First->first, M);
759
760 // Merge the initializer...
761 Inits.reserve(NewSize);
762 ConstantArray *I = cast<ConstantArray>(G1->getInitializer());
763 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
764 Inits.push_back(cast<Constant>(I->getValues()[i]));
765 I = cast<ConstantArray>(G2->getInitializer());
766 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
767 Inits.push_back(cast<Constant>(I->getValues()[i]));
768 NG->setInitializer(ConstantArray::get(NewType, Inits));
769 Inits.clear();
770
771 // Replace any uses of the two global variables with uses of the new
772 // global...
773
774 // FIXME: This should rewrite simple/straight-forward uses such as
775 // getelementptr instructions to not use the Cast!
776 ConstantPointerRef *NGCP = ConstantPointerRef::get(NG);
777 G1->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G1->getType()));
778 G2->replaceAllUsesWith(ConstantExpr::getCast(NGCP, G2->getType()));
779
780 // Remove the two globals from the module now...
781 M->getGlobalList().erase(G1);
782 M->getGlobalList().erase(G2);
783
784 // Put the new global into the AppendingVars map so that we can handle
785 // linking of more than two vars...
786 Second->second = NG;
787 }
788 AppendingVars.erase(First);
789 }
790
791 return false;
792}
Chris Lattner52f7e902001-10-13 07:03:50 +0000793
794
795// LinkModules - This function links two modules together, with the resulting
796// left module modified to be the composite of the two input modules. If an
797// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +0000798// the problem. Upon failure, the Dest module could be in a modified state, and
799// shouldn't be relied on to be consistent.
Chris Lattner52f7e902001-10-13 07:03:50 +0000800//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000801bool LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Chris Lattner873c5e72003-08-24 19:26:42 +0000802 if (Dest->getEndianness() == Module::AnyEndianness)
803 Dest->setEndianness(Src->getEndianness());
804 if (Dest->getPointerSize() == Module::AnyPointerSize)
805 Dest->setPointerSize(Src->getPointerSize());
806
807 if (Src->getEndianness() != Module::AnyEndianness &&
808 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000809 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000810 if (Src->getPointerSize() != Module::AnyPointerSize &&
811 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000812 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000813
814 // LinkTypes - Go through the symbol table of the Src module and see if any
815 // types are named in the src module that are not named in the Dst module.
816 // Make sure there are no type name conflicts.
817 //
818 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
819
Chris Lattner5c377c52001-10-14 23:29:15 +0000820 // ValueMap - Mapping of values from what they used to be in Src, to what they
821 // are now in Dest.
822 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000823 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000824
Chris Lattner8166e6e2003-05-13 21:33:43 +0000825 // AppendingVars - Keep track of global variables in the destination module
826 // with appending linkage. After the module is linked together, they are
827 // appended and the module is rewritten.
828 //
829 std::multimap<std::string, GlobalVariable *> AppendingVars;
830
831 // Add all of the appending globals already in the Dest module to
832 // AppendingVars.
833 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I)
Chris Lattnerf4146462003-05-14 12:11:51 +0000834 if (I->hasAppendingLinkage())
835 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000836
837 // Insert all of the globals in src into the Dest module... without linking
838 // initializers (which could refer to functions not yet mapped over).
839 //
840 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000841
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000842 // Link the functions together between the two modules, without doing function
843 // bodies... this just adds external function prototypes to the Dest
844 // function... We do this so that when we begin processing function bodies,
845 // all of the global values that may be referenced are available in our
846 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000847 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000848 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000849
Chris Lattner6cdf1972002-07-18 00:13:08 +0000850 // Update the initializers in the Dest module now that all globals that may
851 // be referenced are in Dest.
852 //
853 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
854
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000855 // Link in the function bodies that are defined in the source module into the
856 // DestModule. This consists basically of copying the function over and
857 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000858 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000859 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000860
Chris Lattner8166e6e2003-05-13 21:33:43 +0000861 // If there were any appending global variables, link them together now.
862 //
863 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
864
Chris Lattner52f7e902001-10-13 07:03:50 +0000865 return false;
866}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000867