blob: f75729b51940115707ea8f050e0844938af3094b [file] [log] [blame]
Chris Lattner52f7e902001-10-13 07:03:50 +00001//===- Linker.cpp - Module Linker Implementation --------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +000013// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000015// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +000016//
17//===----------------------------------------------------------------------===//
18
Misha Brukmanc837dd92004-06-23 17:24:31 +000019#include "llvm/Support/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000022#include "llvm/Module.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000023#include "llvm/SymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000024#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000025#include "llvm/Assembly/Writer.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000026#include "llvm/System/Path.h"
Reid Spencerc28a2242004-07-04 11:52:49 +000027#include <iostream>
Chris Lattner72cf7df2004-08-21 00:50:59 +000028#include <sstream>
Chris Lattnerf7703df2004-01-09 06:12:26 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner5c377c52001-10-14 23:29:15 +000031// Error - Simple wrapper function to conditionally assign to E and return true.
32// This just makes error return conditions a little bit simpler...
33//
Chris Lattner8166e6e2003-05-13 21:33:43 +000034static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000035 if (E) *E = Message;
36 return true;
37}
38
Chris Lattner72cf7df2004-08-21 00:50:59 +000039static std::string ToStr(const Type *Ty, const Module *M) {
40 std::ostringstream OS;
41 WriteTypeSymbolic(OS, Ty, M);
42 return OS.str();
43}
44
John Criswell700867b2003-11-04 15:22:26 +000045//
46// Function: ResolveTypes()
47//
48// Description:
49// Attempt to link the two specified types together.
50//
51// Inputs:
52// DestTy - The type to which we wish to resolve.
53// SrcTy - The original type which we want to resolve.
54// Name - The name of the type.
55//
56// Outputs:
57// DestST - The symbol table in which the new type should be placed.
58//
59// Return value:
60// true - There is an error and the types cannot yet be linked.
61// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000062//
Chris Lattnere76c57a2003-08-22 06:07:12 +000063static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
64 SymbolTable *DestST, const std::string &Name) {
65 if (DestTy == SrcTy) return false; // If already equal, noop
66
Chris Lattner4c00e532003-05-15 16:30:55 +000067 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
Chris Lattnere76c57a2003-08-22 06:07:12 +000069 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
Chris Lattner4c00e532003-05-15 16:30:55 +000071 } else {
72 return true; // Cannot link types... neither is opaque and not-equal
73 }
74 } else { // Type not in dest module. Add it now.
75 if (DestTy) // Type _is_ in module, just opaque...
Chris Lattnere76c57a2003-08-22 06:07:12 +000076 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
Chris Lattnerfcd02342003-08-23 20:31:10 +000078 else if (!Name.empty())
Chris Lattnere76c57a2003-08-22 06:07:12 +000079 DestST->insert(Name, const_cast<Type*>(SrcTy));
Chris Lattner4c00e532003-05-15 16:30:55 +000080 }
81 return false;
82}
83
Chris Lattner43f4ba82003-08-22 19:12:55 +000084static const FunctionType *getFT(const PATypeHolder &TH) {
85 return cast<FunctionType>(TH.get());
86}
Chris Lattner9732be72003-08-22 20:16:48 +000087static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000088 return cast<StructType>(TH.get());
89}
Chris Lattnere76c57a2003-08-22 06:07:12 +000090
91// RecursiveResolveTypes - This is just like ResolveTypes, except that it
92// recurses down into derived types, merging the used types if the parent types
93// are compatible.
94//
Chris Lattnere3092c92003-08-23 21:25:54 +000095static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
96 const PATypeHolder &SrcTy,
97 SymbolTable *DestST, const std::string &Name,
98 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000099 const Type *SrcTyT = SrcTy.get();
100 const Type *DestTyT = DestTy.get();
101 if (DestTyT == SrcTyT) return false; // If already equal, noop
Chris Lattnere76c57a2003-08-22 06:07:12 +0000102
103 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +0000104 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
105 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000106
107 // Two types cannot be resolved together if they are of different primitive
108 // type. For example, we cannot resolve an int to a float.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000109 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000110
111 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000112 switch (DestTyT->getTypeID()) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000113 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000114 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000115 cast<FunctionType>(SrcTyT)->isVarArg() ||
116 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
117 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000118 return true;
119 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000120 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
121 getFT(SrcTy)->getContainedType(i), DestST, "",
122 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000123 return true;
124 return false;
125 }
126 case Type::StructTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000127 if (getST(DestTy)->getNumContainedTypes() !=
128 getST(SrcTy)->getNumContainedTypes()) return 1;
129 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000130 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
131 getST(SrcTy)->getContainedType(i), DestST, "",
132 Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000133 return true;
134 return false;
135 }
136 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000137 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
138 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000139 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000140 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
141 DestST, "", Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000142 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000143 case Type::PointerTyID: {
144 // If this is a pointer type, check to see if we have already seen it. If
145 // so, we are in a recursive branch. Cut off the search now. We cannot use
146 // an associative container for this search, because the type pointers (keys
147 // in the container) change whenever types get resolved...
148 //
149 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
150 if (Pointers[i].first == DestTy)
151 return Pointers[i].second != SrcTy;
152
153 // Otherwise, add the current pointers to the vector to stop recursion on
154 // this pair.
155 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
156 bool Result =
157 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
158 cast<PointerType>(SrcTy.get())->getElementType(),
159 DestST, "", Pointers);
160 Pointers.pop_back();
161 return Result;
162 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000163 default: assert(0 && "Unexpected type!"); return true;
164 }
165}
166
Chris Lattnere3092c92003-08-23 21:25:54 +0000167static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
168 const PATypeHolder &SrcTy,
169 SymbolTable *DestST, const std::string &Name){
170 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
171 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
172}
173
Chris Lattnere76c57a2003-08-22 06:07:12 +0000174
Chris Lattner2c236f32001-11-03 05:18:24 +0000175// LinkTypes - Go through the symbol table of the Src module and see if any
176// types are named in the src module that are not named in the Dst module.
177// Make sure there are no type name conflicts.
178//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000179static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000180 SymbolTable *DestST = &Dest->getSymbolTable();
181 const SymbolTable *SrcST = &Src->getSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000182
183 // Look for a type plane for Type's...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000184 SymbolTable::type_const_iterator TI = SrcST->type_begin();
185 SymbolTable::type_const_iterator TE = SrcST->type_end();
186 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000187
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000188 // Some types cannot be resolved immediately because they depend on other
189 // types being resolved to each other first. This contains a list of types we
190 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000191 std::vector<std::string> DelayedTypesToResolve;
192
Reid Spencer567bc2c2004-05-25 08:52:20 +0000193 for ( ; TI != TE; ++TI ) {
194 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000195 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000196
197 // Check to see if this type name is already in the dest module...
Reid Spencer567bc2c2004-05-25 08:52:20 +0000198 Type *Entry = DestST->lookupType(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000199
Chris Lattner4c00e532003-05-15 16:30:55 +0000200 if (ResolveTypes(Entry, RHS, DestST, Name)) {
201 // They look different, save the types 'till later to resolve.
202 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000203 }
204 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000205
206 // Iteratively resolve types while we can...
207 while (!DelayedTypesToResolve.empty()) {
208 // Loop over all of the types, attempting to resolve them if possible...
209 unsigned OldSize = DelayedTypesToResolve.size();
210
Chris Lattnere76c57a2003-08-22 06:07:12 +0000211 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000212 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
213 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000214 Type *T1 = SrcST->lookupType(Name);
215 Type *T2 = DestST->lookupType(Name);
Chris Lattner4c00e532003-05-15 16:30:55 +0000216 if (!ResolveTypes(T2, T1, DestST, Name)) {
217 // We are making progress!
218 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
219 --i;
220 }
221 }
222
223 // Did we not eliminate any types?
224 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000225 // Attempt to resolve subelements of types. This allows us to merge these
226 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000227 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
228 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer567bc2c2004-05-25 08:52:20 +0000229 PATypeHolder T1(SrcST->lookupType(Name));
230 PATypeHolder T2(DestST->lookupType(Name));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000231
232 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
233 // We are making progress!
234 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
235
236 // Go back to the main loop, perhaps we can resolve directly by name
237 // now...
238 break;
239 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000240 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000241
242 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000243 // Report the warning and delete one of the names.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000244 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000245 const std::string &Name = DelayedTypesToResolve.back();
246
Reid Spencer567bc2c2004-05-25 08:52:20 +0000247 const Type *T1 = SrcST->lookupType(Name);
248 const Type *T2 = DestST->lookupType(Name);
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000249 std::cerr << "WARNING: Type conflict between types named '" << Name
Chris Lattneradbc0b52003-11-20 18:23:14 +0000250 << "'.\n Src='";
251 WriteTypeSymbolic(std::cerr, T1, Src);
252 std::cerr << "'.\n Dest='";
253 WriteTypeSymbolic(std::cerr, T2, Dest);
254 std::cerr << "'\n";
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000255
256 // Remove the symbol name from the destination.
257 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000258 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000259 }
260 }
261
262
Chris Lattner2c236f32001-11-03 05:18:24 +0000263 return false;
264}
265
Chris Lattner5c2d3352003-01-30 19:53:34 +0000266static void PrintMap(const std::map<const Value*, Value*> &M) {
267 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000268 I != E; ++I) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000269 std::cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000270 I->first->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000271 std::cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000272 I->second->dump();
Chris Lattner5c2d3352003-01-30 19:53:34 +0000273 std::cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000274 }
275}
276
277
Chris Lattner5c377c52001-10-14 23:29:15 +0000278// RemapOperand - Use LocalMap and GlobalMap to convert references from one
279// module to another. This is somewhat sophisticated in that it can
280// automatically handle constant references correctly as well...
281//
Chris Lattner5c2d3352003-01-30 19:53:34 +0000282static Value *RemapOperand(const Value *In,
283 std::map<const Value*, Value*> &LocalMap,
284 std::map<const Value*, Value*> *GlobalMap) {
285 std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
Chris Lattner5c377c52001-10-14 23:29:15 +0000286 if (I != LocalMap.end()) return I->second;
287
288 if (GlobalMap) {
289 I = GlobalMap->find(In);
290 if (I != GlobalMap->end()) return I->second;
291 }
292
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000293 // Check to see if it's a constant that we are interesting in transforming...
Chris Lattner18961502002-06-25 16:12:52 +0000294 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000295 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
296 isa<ConstantAggregateZero>(CPV))
Chris Lattner18961502002-06-25 16:12:52 +0000297 return const_cast<Constant*>(CPV); // Simple constants stay identical...
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000298
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000299 Constant *Result = 0;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000300
Chris Lattner18961502002-06-25 16:12:52 +0000301 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000302 std::vector<Constant*> Operands(CPA->getNumOperands());
303 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
304 Operands[i] =
305 cast<Constant>(RemapOperand(CPA->getOperand(i), LocalMap, GlobalMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000306 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000307 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000308 std::vector<Constant*> Operands(CPS->getNumOperands());
309 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
310 Operands[i] =
311 cast<Constant>(RemapOperand(CPS->getOperand(i), LocalMap, GlobalMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000312 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
313 } else if (isa<ConstantPointerNull>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000314 Result = const_cast<Constant*>(CPV);
Reid Spencer00dc4792004-07-17 23:50:57 +0000315 } else if (isa<GlobalValue>(CPV)) {
316 Result = cast<Constant>(RemapOperand(CPV, LocalMap, GlobalMap));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000317 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000318 if (CE->getOpcode() == Instruction::GetElementPtr) {
319 Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
320 std::vector<Constant*> Indices;
321 Indices.reserve(CE->getNumOperands()-1);
322 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
323 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
324 LocalMap, GlobalMap)));
325
326 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
327 } else if (CE->getNumOperands() == 1) {
Chris Lattnerad333482002-08-14 18:24:09 +0000328 // Cast instruction
329 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000330 Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
Chris Lattnerad333482002-08-14 18:24:09 +0000331 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
Chris Lattner14381022004-03-31 02:58:28 +0000332 } else if (CE->getNumOperands() == 3) {
333 // Select instruction
334 assert(CE->getOpcode() == Instruction::Select);
335 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
336 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
337 Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
338 Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
339 cast<Constant>(V3));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000340 } else if (CE->getNumOperands() == 2) {
341 // Binary operator...
342 Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
343 Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
344
345 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
Chris Lattnerd981f8a2003-11-05 20:37:01 +0000346 cast<Constant>(V2));
Chris Lattner6cdf1972002-07-18 00:13:08 +0000347 } else {
Chris Lattnerb319faf2002-08-20 19:35:11 +0000348 assert(0 && "Unknown constant expr type!");
Chris Lattner6cdf1972002-07-18 00:13:08 +0000349 }
350
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000351 } else {
352 assert(0 && "Unknown type of derived type constant value!");
353 }
354
355 // Cache the mapping in our local map structure...
Chris Lattnerd149c052002-09-23 18:14:15 +0000356 if (GlobalMap)
357 GlobalMap->insert(std::make_pair(In, Result));
358 else
359 LocalMap.insert(std::make_pair(In, Result));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000360 return Result;
361 }
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000362
Chris Lattner5c2d3352003-01-30 19:53:34 +0000363 std::cerr << "XXX LocalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000364 PrintMap(LocalMap);
365
366 if (GlobalMap) {
Chris Lattner5c2d3352003-01-30 19:53:34 +0000367 std::cerr << "XXX GlobalMap: \n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000368 PrintMap(*GlobalMap);
369 }
370
Chris Lattner5c2d3352003-01-30 19:53:34 +0000371 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000372 assert(0 && "Couldn't remap value!");
373 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000374}
375
Chris Lattnerc0036282004-08-04 07:05:54 +0000376/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
377/// in the symbol table. This is good for all clients except for us. Go
378/// through the trouble to force this back.
379static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
380 assert(GV->getName() != Name && "Can't force rename to self");
381 SymbolTable &ST = GV->getParent()->getSymbolTable();
382
383 // If there is a conflict, rename the conflict.
384 Value *ConflictVal = ST.lookup(GV->getType(), Name);
385 assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
386 GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
387 assert(ConflictGV->hasInternalLinkage() &&
388 "Not conflicting with a static global, should link instead!");
389
390 ConflictGV->setName(""); // Eliminate the conflict
391 GV->setName(Name); // Force the name back
392 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner7b0c84d2004-08-04 07:28:06 +0000393 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
Chris Lattnerc0036282004-08-04 07:05:54 +0000394 "ForceRenaming didn't work");
395}
396
Chris Lattner5c377c52001-10-14 23:29:15 +0000397
398// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000399// them into the dest module.
Chris Lattner5c377c52001-10-14 23:29:15 +0000400//
401static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000402 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000403 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5a837de2004-08-04 07:44:58 +0000404 std::map<std::string, GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000405 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000406 // We will need a module level symbol table if the src module has a module
407 // level symbol table...
Chris Lattnerb91b6572002-12-03 18:32:30 +0000408 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000409
410 // Loop over all of the globals in the src module, mapping them over as we go
411 //
412 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000413 const GlobalVariable *SGV = I;
Chris Lattner4ad02e72003-04-16 20:28:45 +0000414 GlobalVariable *DGV = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000415 // Check to see if may have to link the global.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000416 if (SGV->hasName() && !SGV->hasInternalLinkage())
417 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
418 SGV->getType()->getElementType()))) {
419 std::map<std::string, GlobalValue*>::iterator EGV =
420 GlobalsByName.find(SGV->getName());
421 if (EGV != GlobalsByName.end())
422 DGV = dyn_cast<GlobalVariable>(EGV->second);
423 if (DGV && RecursiveResolveTypes(SGV->getType(), DGV->getType(), ST, ""))
424 DGV = 0; // FIXME: gross.
425 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000426
Chris Lattner4ad02e72003-04-16 20:28:45 +0000427 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
428 "Global must either be external or have an initializer!");
429
Chris Lattner0fec08e2003-04-21 21:07:05 +0000430 bool SGExtern = SGV->isExternal();
431 bool DGExtern = DGV ? DGV->isExternal() : false;
432
Chris Lattner4ad02e72003-04-16 20:28:45 +0000433 if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
434 // No linking to be performed, simply create an identical version of the
435 // symbol over in the dest module... the initializer will be filled in
436 // later by LinkGlobalInits...
437 //
Chris Lattner2719bac2003-04-21 21:15:04 +0000438 GlobalVariable *NewDGV =
439 new GlobalVariable(SGV->getType()->getElementType(),
440 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
441 SGV->getName(), Dest);
442
443 // If the LLVM runtime renamed the global, but it is an externally visible
444 // symbol, DGV must be an existing global with internal linkage. Rename
445 // it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000446 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
447 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000448
449 // Make sure to remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000450 ValueMap.insert(std::make_pair(SGV, NewDGV));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000451 if (SGV->hasAppendingLinkage())
452 // Keep track that this is an appending variable...
453 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
454
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000455 } else if (SGV->isExternal()) {
456 // If SGV is external or if both SGV & DGV are external.. Just link the
457 // external globals, we aren't adding anything.
458 ValueMap.insert(std::make_pair(SGV, DGV));
459
460 } else if (DGV->isExternal()) { // If DGV is external but SGV is not...
461 ValueMap.insert(std::make_pair(SGV, DGV));
462 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
Chris Lattner35956552003-10-27 16:39:39 +0000463 } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000464 // At this point we know that DGV has LinkOnce, Appending, Weak, or
465 // External linkage. If DGV is Appending, this is an error.
466 if (DGV->hasAppendingLinkage())
467 return Error(Err, "Linking globals named '" + SGV->getName() +
468 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000469
470 if (SGV->isConstant() != DGV->isConstant())
471 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000472 ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
Chris Lattner35956552003-10-27 16:39:39 +0000473 "' - Global variables differ in const'ness");
474
Chris Lattner72ac148d2003-10-16 18:29:00 +0000475 // Otherwise, just perform the link.
476 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattner35956552003-10-27 16:39:39 +0000477
478 // Linkonce+Weak = Weak
479 if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
480 DGV->setLinkage(SGV->getLinkage());
481
482 } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000483 // At this point we know that SGV has LinkOnce, Appending, or External
484 // linkage. If SGV is Appending, this is an error.
485 if (SGV->hasAppendingLinkage())
486 return Error(Err, "Linking globals named '" + SGV->getName() +
487 " ' with 'weak' and 'appending' linkage is not allowed!");
Chris Lattner35956552003-10-27 16:39:39 +0000488
489 if (SGV->isConstant() != DGV->isConstant())
490 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000491 ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
Chris Lattner35956552003-10-27 16:39:39 +0000492 "' - Global variables differ in const'ness");
493
Chris Lattner72ac148d2003-10-16 18:29:00 +0000494 if (!SGV->hasLinkOnceLinkage())
495 DGV->setLinkage(SGV->getLinkage()); // Inherit linkage!
496 ValueMap.insert(std::make_pair(SGV, DGV));
497
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000498 } else if (SGV->getLinkage() != DGV->getLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000499 return Error(Err, "Global variables named '" + SGV->getName() +
500 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000501 } else if (SGV->hasExternalLinkage()) {
502 // Allow linking two exactly identical external global variables...
Chris Lattnerf85770c2003-10-21 21:52:20 +0000503 if (SGV->isConstant() != DGV->isConstant())
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000504 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000505 ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000506 "' - Global variables differ in const'ness");
Chris Lattnerf85770c2003-10-21 21:52:20 +0000507
508 if (SGV->getInitializer() != DGV->getInitializer())
509 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000510 ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
Chris Lattnerf85770c2003-10-21 21:52:20 +0000511 "' - External linkage globals have different initializers");
512
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000513 ValueMap.insert(std::make_pair(SGV, DGV));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000514 } else if (SGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000515 // No linking is performed yet. Just insert a new copy of the global, and
516 // keep track of the fact that it is an appending variable in the
517 // AppendingVars map. The name is cleared out so that no linkage is
518 // performed.
519 GlobalVariable *NewDGV =
520 new GlobalVariable(SGV->getType()->getElementType(),
521 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
522 "", Dest);
523
524 // Make sure to remember this mapping...
525 ValueMap.insert(std::make_pair(SGV, NewDGV));
526
527 // Keep track that this is an appending variable...
528 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner5c377c52001-10-14 23:29:15 +0000529 } else {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000530 assert(0 && "Unknown linkage!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000531 }
532 }
533 return false;
534}
535
536
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000537// LinkGlobalInits - Update the initializers in the Dest module now that all
538// globals that may be referenced are in Dest.
539//
540static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000541 std::map<const Value*, Value*> &ValueMap,
542 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000543
544 // Loop over all of the globals in the src module, mapping them over as we go
545 //
546 for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
Chris Lattner18961502002-06-25 16:12:52 +0000547 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000548
549 if (SGV->hasInitializer()) { // Only process initialized GV's
550 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000551 Constant *SInit =
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000552 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000553
554 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000555 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000556 if (SGV->hasExternalLinkage()) {
557 if (DGV->getInitializer() != SInit)
558 return Error(Err, "Global Variable Collision on '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000559 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
Chris Lattner4ad02e72003-04-16 20:28:45 +0000560 " - Global variables have different initializers");
Chris Lattner72ac148d2003-10-16 18:29:00 +0000561 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000562 // Nothing is required, mapped values will take the new global
563 // automatically.
Chris Lattner57cb9882004-02-17 21:56:04 +0000564 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
565 // Nothing is required, mapped values will take the new global
566 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000567 } else if (DGV->hasAppendingLinkage()) {
568 assert(0 && "Appending linkage unimplemented!");
569 } else {
570 assert(0 && "Unknown linkage!");
571 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000572 } else {
573 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000574 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000575 }
576 }
577 }
578 return false;
579}
Chris Lattner5c377c52001-10-14 23:29:15 +0000580
Chris Lattner79df7c02002-03-26 18:01:55 +0000581// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000582// without doing function bodies... this just adds external function prototypes
583// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000584//
Chris Lattner79df7c02002-03-26 18:01:55 +0000585static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000586 std::map<const Value*, Value*> &ValueMap,
Chris Lattner5a837de2004-08-04 07:44:58 +0000587 std::map<std::string, GlobalValue*> &GlobalsByName,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000588 std::string *Err) {
Chris Lattnerb91b6572002-12-03 18:32:30 +0000589 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Chris Lattner5c377c52001-10-14 23:29:15 +0000590
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000591 // Loop over all of the functions in the src module, mapping them over as we
592 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000593 //
594 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000595 const Function *SF = I; // SrcFunction
Chris Lattner4ad02e72003-04-16 20:28:45 +0000596 Function *DF = 0;
Chris Lattner5a837de2004-08-04 07:44:58 +0000597 if (SF->hasName() && !SF->hasInternalLinkage()) {
598 // Check to see if may have to link the function.
Chris Lattneraad2deb2004-08-04 22:39:54 +0000599 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
600 std::map<std::string, GlobalValue*>::iterator EF =
601 GlobalsByName.find(SF->getName());
602 if (EF != GlobalsByName.end())
603 DF = dyn_cast<Function>(EF->second);
604 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
605 DF = 0; // FIXME: gross.
606 }
Chris Lattner5a837de2004-08-04 07:44:58 +0000607 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000608
Chris Lattner4ad02e72003-04-16 20:28:45 +0000609 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000610 // Function does not already exist, simply insert an function signature
611 // identical to SF into the dest module...
Chris Lattner2719bac2003-04-21 21:15:04 +0000612 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
613 SF->getName(), Dest);
614
615 // If the LLVM runtime renamed the function, but it is an externally
616 // visible symbol, DF must be an existing function with internal linkage.
617 // Rename it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000618 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
Chris Lattner82b5b212004-08-04 22:29:05 +0000619 ForceRenaming(NewDF, SF->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000620
621 // ... and remember this mapping...
Chris Lattner2719bac2003-04-21 21:15:04 +0000622 ValueMap.insert(std::make_pair(SF, NewDF));
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000623 } else if (SF->isExternal()) {
624 // If SF is external or if both SF & DF are external.. Just link the
625 // external functions, we aren't adding anything.
626 ValueMap.insert(std::make_pair(SF, DF));
627 } else if (DF->isExternal()) { // If DF is external but SF is not...
628 // Link the external functions, update linkage qualifiers
629 ValueMap.insert(std::make_pair(SF, DF));
630 DF->setLinkage(SF->getLinkage());
631
Chris Lattner35956552003-10-27 16:39:39 +0000632 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000633 // At this point we know that DF has LinkOnce, Weak, or External linkage.
634 ValueMap.insert(std::make_pair(SF, DF));
635
Chris Lattner35956552003-10-27 16:39:39 +0000636 // Linkonce+Weak = Weak
637 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
638 DF->setLinkage(SF->getLinkage());
639
640 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Chris Lattner72ac148d2003-10-16 18:29:00 +0000641 // At this point we know that SF has LinkOnce or External linkage.
642 ValueMap.insert(std::make_pair(SF, DF));
643 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
644 DF->setLinkage(SF->getLinkage());
645
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000646 } else if (SF->getLinkage() != DF->getLinkage()) {
Chris Lattner0fec08e2003-04-21 21:07:05 +0000647 return Error(Err, "Functions named '" + SF->getName() +
648 "' have different linkage specifiers!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000649 } else if (SF->hasExternalLinkage()) {
650 // The function is defined in both modules!!
651 return Error(Err, "Function '" +
Chris Lattner72cf7df2004-08-21 00:50:59 +0000652 ToStr(SF->getFunctionType(), Src) + "':\"" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000653 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000654 } else {
655 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000656 }
657 }
658 return false;
659}
660
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000661// LinkFunctionBody - Copy the source function over into the dest function and
662// fix up references to values. At this point we know that Dest is an external
663// function, and that Src is not.
Chris Lattner5c377c52001-10-14 23:29:15 +0000664//
Chris Lattner79df7c02002-03-26 18:01:55 +0000665static bool LinkFunctionBody(Function *Dest, const Function *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000666 std::map<const Value*, Value*> &GlobalMap,
667 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000668 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Chris Lattner5c2d3352003-01-30 19:53:34 +0000669 std::map<const Value*, Value*> LocalMap; // Map for function local values
Chris Lattner5c377c52001-10-14 23:29:15 +0000670
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000671 // Go through and convert function arguments over...
Chris Lattner69da5cf2002-10-13 20:57:00 +0000672 Function::aiterator DI = Dest->abegin();
Chris Lattner18961502002-06-25 16:12:52 +0000673 for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000674 I != E; ++I, ++DI) {
675 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000676
677 // Add a mapping to our local map
Chris Lattner69da5cf2002-10-13 20:57:00 +0000678 LocalMap.insert(std::make_pair(I, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000679 }
680
681 // Loop over all of the basic blocks, copying the instructions over...
682 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000683 for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000684 // Create new basic block and add to mapping and the Dest function...
Chris Lattner18961502002-06-25 16:12:52 +0000685 BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
686 LocalMap.insert(std::make_pair(I, DBB));
Chris Lattner5c377c52001-10-14 23:29:15 +0000687
688 // Loop over all of the instructions in the src basic block, copying them
689 // over. Note that this is broken in a strict sense because the cloned
690 // instructions will still be referencing values in the Src module, not
691 // the remapped values. In our case, however, we will not get caught and
692 // so we can delay patching the values up until later...
693 //
Chris Lattner18961502002-06-25 16:12:52 +0000694 for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
Chris Lattner5c377c52001-10-14 23:29:15 +0000695 II != IE; ++II) {
Chris Lattner18961502002-06-25 16:12:52 +0000696 Instruction *DI = II->clone();
697 DI->setName(II->getName());
Chris Lattner5c377c52001-10-14 23:29:15 +0000698 DBB->getInstList().push_back(DI);
Chris Lattner18961502002-06-25 16:12:52 +0000699 LocalMap.insert(std::make_pair(II, DI));
Chris Lattner5c377c52001-10-14 23:29:15 +0000700 }
701 }
702
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000703 // At this point, all of the instructions and values of the function are now
704 // copied over. The only problem is that they are still referencing values in
705 // the Source function as operands. Loop through all of the operands of the
706 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000707 //
Chris Lattner18961502002-06-25 16:12:52 +0000708 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
709 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
710 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000711 OI != OE; ++OI)
712 *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
Chris Lattner5c377c52001-10-14 23:29:15 +0000713
714 return false;
715}
716
717
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000718// LinkFunctionBodies - Link in the function bodies that are defined in the
719// source module into the DestModule. This consists basically of copying the
720// function over and fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000721//
Chris Lattner79df7c02002-03-26 18:01:55 +0000722static bool LinkFunctionBodies(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000723 std::map<const Value*, Value*> &ValueMap,
724 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000725
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000726 // Loop over all of the functions in the src module, mapping them over as we
727 // go
Chris Lattner5c377c52001-10-14 23:29:15 +0000728 //
Chris Lattner18961502002-06-25 16:12:52 +0000729 for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
730 if (!SF->isExternal()) { // No body if function is external
731 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +0000732
Chris Lattner18961502002-06-25 16:12:52 +0000733 // DF not external SF external?
Chris Lattner35956552003-10-27 16:39:39 +0000734 if (DF->isExternal()) {
735 // Only provide the function body if there isn't one already.
736 if (LinkFunctionBody(DF, SF, ValueMap, Err))
737 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000738 }
Chris Lattnerc2d774b2001-10-23 20:43:42 +0000739 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000740 }
741 return false;
742}
743
Chris Lattner8166e6e2003-05-13 21:33:43 +0000744// LinkAppendingVars - If there were any appending global variables, link them
745// together now. Return true on error.
746//
747static bool LinkAppendingVars(Module *M,
748 std::multimap<std::string, GlobalVariable *> &AppendingVars,
749 std::string *ErrorMsg) {
750 if (AppendingVars.empty()) return false; // Nothing to do.
751
752 // Loop over the multimap of appending vars, processing any variables with the
753 // same name, forming a new appending global variable with both of the
754 // initializers merged together, then rewrite references to the old variables
755 // and delete them.
756 //
757 std::vector<Constant*> Inits;
758 while (AppendingVars.size() > 1) {
759 // Get the first two elements in the map...
760 std::multimap<std::string,
761 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
762
763 // If the first two elements are for different names, there is no pair...
764 // Otherwise there is a pair, so link them together...
765 if (First->first == Second->first) {
766 GlobalVariable *G1 = First->second, *G2 = Second->second;
767 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
768 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
769
770 // Check to see that they two arrays agree on type...
771 if (T1->getElementType() != T2->getElementType())
772 return Error(ErrorMsg,
773 "Appending variables with different element types need to be linked!");
774 if (G1->isConstant() != G2->isConstant())
775 return Error(ErrorMsg,
776 "Appending variables linked with different const'ness!");
777
778 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
779 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
780
781 // Create the new global variable...
782 GlobalVariable *NG =
783 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
784 /*init*/0, First->first, M);
785
786 // Merge the initializer...
787 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +0000788 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
789 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000790 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000791 } else {
792 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
793 Constant *CV = Constant::getNullValue(T1->getElementType());
794 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
795 Inits.push_back(CV);
796 }
797 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
798 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000799 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +0000800 } else {
801 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
802 Constant *CV = Constant::getNullValue(T2->getElementType());
803 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
804 Inits.push_back(CV);
805 }
Chris Lattner8166e6e2003-05-13 21:33:43 +0000806 NG->setInitializer(ConstantArray::get(NewType, Inits));
807 Inits.clear();
808
809 // Replace any uses of the two global variables with uses of the new
810 // global...
811
812 // FIXME: This should rewrite simple/straight-forward uses such as
813 // getelementptr instructions to not use the Cast!
Reid Spencer00dc4792004-07-17 23:50:57 +0000814 G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
815 G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000816
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 Lattnerf7703df2004-01-09 06:12:26 +0000838bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +0000839 assert(Dest != 0 && "Invalid Destination module");
840 assert(Src != 0 && "Invalid Source Module");
841
Chris Lattner873c5e72003-08-24 19:26:42 +0000842 if (Dest->getEndianness() == Module::AnyEndianness)
843 Dest->setEndianness(Src->getEndianness());
844 if (Dest->getPointerSize() == Module::AnyPointerSize)
845 Dest->setPointerSize(Src->getPointerSize());
846
847 if (Src->getEndianness() != Module::AnyEndianness &&
848 Dest->getEndianness() != Src->getEndianness())
Chris Lattner43a99942003-04-22 19:13:20 +0000849 std::cerr << "WARNING: Linking two modules of different endianness!\n";
Chris Lattner873c5e72003-08-24 19:26:42 +0000850 if (Src->getPointerSize() != Module::AnyPointerSize &&
851 Dest->getPointerSize() != Src->getPointerSize())
Chris Lattner43a99942003-04-22 19:13:20 +0000852 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattner2c236f32001-11-03 05:18:24 +0000853
Reid Spencer57a0efa2004-09-11 04:25:17 +0000854 // Update the destination module's dependent libraries list with the libraries
855 // from the source module. There's no opportunity for duplicates here as the
856 // Module ensures that duplicate insertions are discarded.
857 Module::lib_iterator SI = Src->lib_begin();
858 Module::lib_iterator SE = Src->lib_end();
859 while ( SI != SE ) {
860 Dest->addLibrary(*SI);
861 ++SI;
862 }
863
Chris Lattner2c236f32001-11-03 05:18:24 +0000864 // LinkTypes - Go through the symbol table of the Src module and see if any
865 // types are named in the src module that are not named in the Dst module.
866 // Make sure there are no type name conflicts.
867 //
868 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
869
Chris Lattner5c377c52001-10-14 23:29:15 +0000870 // ValueMap - Mapping of values from what they used to be in Src, to what they
871 // are now in Dest.
872 //
Chris Lattner5c2d3352003-01-30 19:53:34 +0000873 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +0000874
Chris Lattner8166e6e2003-05-13 21:33:43 +0000875 // AppendingVars - Keep track of global variables in the destination module
876 // with appending linkage. After the module is linked together, they are
877 // appended and the module is rewritten.
878 //
879 std::multimap<std::string, GlobalVariable *> AppendingVars;
880
Chris Lattner5a837de2004-08-04 07:44:58 +0000881 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
882 // linking by separating globals by type. Until PR411 is fixed, we replicate
883 // it's functionality here.
884 std::map<std::string, GlobalValue*> GlobalsByName;
885
886 for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I) {
887 // Add all of the appending globals already in the Dest module to
888 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +0000889 if (I->hasAppendingLinkage())
890 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner8166e6e2003-05-13 21:33:43 +0000891
Chris Lattner5a837de2004-08-04 07:44:58 +0000892 // Keep track of all globals by name.
893 if (!I->hasInternalLinkage() && I->hasName())
894 GlobalsByName[I->getName()] = I;
895 }
896
897 // Keep track of all globals by name.
898 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
899 if (!I->hasInternalLinkage() && I->hasName())
900 GlobalsByName[I->getName()] = I;
901
Chris Lattner8166e6e2003-05-13 21:33:43 +0000902 // Insert all of the globals in src into the Dest module... without linking
903 // initializers (which could refer to functions not yet mapped over).
904 //
Chris Lattner5a837de2004-08-04 07:44:58 +0000905 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
906 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000907
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000908 // Link the functions together between the two modules, without doing function
909 // bodies... this just adds external function prototypes to the Dest
910 // function... We do this so that when we begin processing function bodies,
911 // all of the global values that may be referenced are available in our
912 // ValueMap.
Chris Lattner5c377c52001-10-14 23:29:15 +0000913 //
Chris Lattner5a837de2004-08-04 07:44:58 +0000914 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
915 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +0000916
Chris Lattner6cdf1972002-07-18 00:13:08 +0000917 // Update the initializers in the Dest module now that all globals that may
918 // be referenced are in Dest.
919 //
920 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
921
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000922 // Link in the function bodies that are defined in the source module into the
923 // DestModule. This consists basically of copying the function over and
924 // fixing up references to values.
Chris Lattner5c377c52001-10-14 23:29:15 +0000925 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000926 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +0000927
Chris Lattner8166e6e2003-05-13 21:33:43 +0000928 // If there were any appending global variables, link them together now.
929 //
930 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
931
Reid Spencer57a0efa2004-09-11 04:25:17 +0000932 // If the source library's module id is in the dependent library list of the
933 // destination library, remove it since that module is now linked in.
934 sys::Path modId;
935 modId.set_file(Src->getModuleIdentifier());
936 if (!modId.is_empty())
937 Dest->removeLibrary(modId.get_basename());
938
Chris Lattner52f7e902001-10-13 07:03:50 +0000939 return false;
940}
Vikram S. Adve9466f512001-10-28 21:38:02 +0000941
Reid Spencer567bc2c2004-05-25 08:52:20 +0000942// vim: sw=2