blob: 71239f74392f08993da2dc6b9f7b7b6ca05ea6f3 [file] [log] [blame]
Reid Spencer361e5132004-11-12 20:37:43 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// 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.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
13// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15// * Merges functions between two modules
16//
17//===----------------------------------------------------------------------===//
18
Reid Spencer9b0ddbb2004-11-14 23:27:04 +000019#include "llvm/Linker.h"
Reid Spencer361e5132004-11-12 20:37:43 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/SymbolTable.h"
24#include "llvm/Instructions.h"
25#include "llvm/Assembly/Writer.h"
Bill Wendling7339b8d2006-11-27 10:09:12 +000026#include "llvm/Support/Streams.h"
Reid Spencer361e5132004-11-12 20:37:43 +000027#include "llvm/System/Path.h"
Reid Spencer361e5132004-11-12 20:37:43 +000028using namespace llvm;
29
30// Error - Simple wrapper function to conditionally assign to E and return true.
31// This just makes error return conditions a little bit simpler...
Reid Spencer361e5132004-11-12 20:37:43 +000032static inline bool Error(std::string *E, const std::string &Message) {
33 if (E) *E = Message;
34 return true;
35}
36
Reid Spencer2c4f9a42004-11-25 09:29:44 +000037// ToStr - Simple wrapper function to convert a type to a string.
Reid Spencer361e5132004-11-12 20:37:43 +000038static std::string ToStr(const Type *Ty, const Module *M) {
39 std::ostringstream OS;
40 WriteTypeSymbolic(OS, Ty, M);
41 return OS.str();
42}
43
44//
45// Function: ResolveTypes()
46//
47// Description:
48// Attempt to link the two specified types together.
49//
50// Inputs:
51// DestTy - The type to which we wish to resolve.
52// SrcTy - The original type which we want to resolve.
53// Name - The name of the type.
54//
55// Outputs:
56// DestST - The symbol table in which the new type should be placed.
57//
58// Return value:
59// true - There is an error and the types cannot yet be linked.
60// false - No errors.
61//
62static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
63 SymbolTable *DestST, const std::string &Name) {
64 if (DestTy == SrcTy) return false; // If already equal, noop
65
66 // Does the type already exist in the module?
67 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
68 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
69 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
70 } else {
71 return true; // Cannot link types... neither is opaque and not-equal
72 }
73 } else { // Type not in dest module. Add it now.
74 if (DestTy) // Type _is_ in module, just opaque...
75 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
76 ->refineAbstractTypeTo(SrcTy);
77 else if (!Name.empty())
78 DestST->insert(Name, const_cast<Type*>(SrcTy));
79 }
80 return false;
81}
82
83static const FunctionType *getFT(const PATypeHolder &TH) {
84 return cast<FunctionType>(TH.get());
85}
86static const StructType *getST(const PATypeHolder &TH) {
87 return cast<StructType>(TH.get());
88}
89
90// RecursiveResolveTypes - This is just like ResolveTypes, except that it
91// recurses down into derived types, merging the used types if the parent types
92// are compatible.
Reid Spencer361e5132004-11-12 20:37:43 +000093static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
94 const PATypeHolder &SrcTy,
95 SymbolTable *DestST, const std::string &Name,
96 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
97 const Type *SrcTyT = SrcTy.get();
98 const Type *DestTyT = DestTy.get();
99 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukman10468d82005-04-21 22:55:34 +0000100
Reid Spencer361e5132004-11-12 20:37:43 +0000101 // If we found our opaque type, resolve it now!
102 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
103 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Misha Brukman10468d82005-04-21 22:55:34 +0000104
Reid Spencer361e5132004-11-12 20:37:43 +0000105 // Two types cannot be resolved together if they are of different primitive
106 // type. For example, we cannot resolve an int to a float.
107 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
108
109 // Otherwise, resolve the used type used by this derived type...
110 switch (DestTyT->getTypeID()) {
111 case Type::FunctionTyID: {
112 if (cast<FunctionType>(DestTyT)->isVarArg() !=
113 cast<FunctionType>(SrcTyT)->isVarArg() ||
114 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
115 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
116 return true;
117 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
118 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
119 getFT(SrcTy)->getContainedType(i), DestST, "",
120 Pointers))
121 return true;
122 return false;
123 }
124 case Type::StructTyID: {
Misha Brukman10468d82005-04-21 22:55:34 +0000125 if (getST(DestTy)->getNumContainedTypes() !=
Reid Spencer361e5132004-11-12 20:37:43 +0000126 getST(SrcTy)->getNumContainedTypes()) return 1;
127 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
128 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
129 getST(SrcTy)->getContainedType(i), DestST, "",
130 Pointers))
131 return true;
132 return false;
133 }
134 case Type::ArrayTyID: {
135 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
136 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
137 if (DAT->getNumElements() != SAT->getNumElements()) return true;
138 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
139 DestST, "", Pointers);
140 }
141 case Type::PointerTyID: {
142 // If this is a pointer type, check to see if we have already seen it. If
143 // so, we are in a recursive branch. Cut off the search now. We cannot use
144 // an associative container for this search, because the type pointers (keys
145 // in the container) change whenever types get resolved...
Reid Spencer361e5132004-11-12 20:37:43 +0000146 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
147 if (Pointers[i].first == DestTy)
148 return Pointers[i].second != SrcTy;
149
150 // Otherwise, add the current pointers to the vector to stop recursion on
151 // this pair.
152 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
153 bool Result =
154 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
155 cast<PointerType>(SrcTy.get())->getElementType(),
156 DestST, "", Pointers);
157 Pointers.pop_back();
158 return Result;
159 }
160 default: assert(0 && "Unexpected type!"); return true;
Misha Brukman10468d82005-04-21 22:55:34 +0000161 }
Reid Spencer361e5132004-11-12 20:37:43 +0000162}
163
164static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
165 const PATypeHolder &SrcTy,
166 SymbolTable *DestST, const std::string &Name){
167 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
168 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
169}
170
171
172// LinkTypes - Go through the symbol table of the Src module and see if any
173// types are named in the src module that are not named in the Dst module.
174// Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000175static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
176 SymbolTable *DestST = &Dest->getSymbolTable();
177 const SymbolTable *SrcST = &Src->getSymbolTable();
178
179 // Look for a type plane for Type's...
180 SymbolTable::type_const_iterator TI = SrcST->type_begin();
181 SymbolTable::type_const_iterator TE = SrcST->type_end();
182 if (TI == TE) return false; // No named types, do nothing.
183
184 // Some types cannot be resolved immediately because they depend on other
185 // types being resolved to each other first. This contains a list of types we
186 // are waiting to recheck.
187 std::vector<std::string> DelayedTypesToResolve;
188
189 for ( ; TI != TE; ++TI ) {
190 const std::string &Name = TI->first;
191 const Type *RHS = TI->second;
192
193 // Check to see if this type name is already in the dest module...
194 Type *Entry = DestST->lookupType(Name);
195
196 if (ResolveTypes(Entry, RHS, DestST, Name)) {
197 // They look different, save the types 'till later to resolve.
198 DelayedTypesToResolve.push_back(Name);
199 }
200 }
201
202 // Iteratively resolve types while we can...
203 while (!DelayedTypesToResolve.empty()) {
204 // Loop over all of the types, attempting to resolve them if possible...
205 unsigned OldSize = DelayedTypesToResolve.size();
206
207 // Try direct resolution by name...
208 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
209 const std::string &Name = DelayedTypesToResolve[i];
210 Type *T1 = SrcST->lookupType(Name);
211 Type *T2 = DestST->lookupType(Name);
212 if (!ResolveTypes(T2, T1, DestST, Name)) {
213 // We are making progress!
214 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
215 --i;
216 }
217 }
218
219 // Did we not eliminate any types?
220 if (DelayedTypesToResolve.size() == OldSize) {
221 // Attempt to resolve subelements of types. This allows us to merge these
222 // two types: { int* } and { opaque* }
223 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
224 const std::string &Name = DelayedTypesToResolve[i];
225 PATypeHolder T1(SrcST->lookupType(Name));
226 PATypeHolder T2(DestST->lookupType(Name));
227
228 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
229 // We are making progress!
230 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukman10468d82005-04-21 22:55:34 +0000231
Reid Spencer361e5132004-11-12 20:37:43 +0000232 // Go back to the main loop, perhaps we can resolve directly by name
233 // now...
234 break;
235 }
236 }
237
238 // If we STILL cannot resolve the types, then there is something wrong.
Reid Spencer361e5132004-11-12 20:37:43 +0000239 if (DelayedTypesToResolve.size() == OldSize) {
Reid Spencer361e5132004-11-12 20:37:43 +0000240 // Remove the symbol name from the destination.
241 DelayedTypesToResolve.pop_back();
242 }
243 }
244 }
245
246
247 return false;
248}
249
250static void PrintMap(const std::map<const Value*, Value*> &M) {
251 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
252 I != E; ++I) {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000253 cerr << " Fr: " << (void*)I->first << " ";
Reid Spencer361e5132004-11-12 20:37:43 +0000254 I->first->dump();
Bill Wendlingf3baad32006-12-07 01:30:32 +0000255 cerr << " To: " << (void*)I->second << " ";
Reid Spencer361e5132004-11-12 20:37:43 +0000256 I->second->dump();
Bill Wendlingf3baad32006-12-07 01:30:32 +0000257 cerr << "\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000258 }
259}
260
261
Chris Lattner7391dde2004-11-16 17:12:38 +0000262// RemapOperand - Use ValueMap to convert references from one module to another.
263// This is somewhat sophisticated in that it can automatically handle constant
Chris Lattnerc7745922006-06-01 19:14:22 +0000264// references correctly as well.
Reid Spencer361e5132004-11-12 20:37:43 +0000265static Value *RemapOperand(const Value *In,
Chris Lattner7391dde2004-11-16 17:12:38 +0000266 std::map<const Value*, Value*> &ValueMap) {
267 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
268 if (I != ValueMap.end()) return I->second;
Reid Spencer361e5132004-11-12 20:37:43 +0000269
Chris Lattner7391dde2004-11-16 17:12:38 +0000270 // Check to see if it's a constant that we are interesting in transforming.
Chris Lattnerc7745922006-06-01 19:14:22 +0000271 Value *Result = 0;
Reid Spencer361e5132004-11-12 20:37:43 +0000272 if (const Constant *CPV = dyn_cast<Constant>(In)) {
273 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
274 isa<ConstantAggregateZero>(CPV))
Chris Lattner7391dde2004-11-16 17:12:38 +0000275 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Reid Spencer361e5132004-11-12 20:37:43 +0000276
Reid Spencer361e5132004-11-12 20:37:43 +0000277 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
278 std::vector<Constant*> Operands(CPA->getNumOperands());
279 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000280 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000281 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
282 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
283 std::vector<Constant*> Operands(CPS->getNumOperands());
284 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000285 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000286 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
287 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
288 Result = const_cast<Constant*>(CPV);
289 } else if (isa<GlobalValue>(CPV)) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000290 Result = cast<Constant>(RemapOperand(CPV, ValueMap));
Chris Lattner93bde9c2006-01-19 23:15:58 +0000291 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CPV)) {
292 std::vector<Constant*> Operands(CP->getNumOperands());
293 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
294 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
295 Result = ConstantPacked::get(Operands);
Reid Spencer361e5132004-11-12 20:37:43 +0000296 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner19247f32006-07-14 22:21:31 +0000297 std::vector<Constant*> Ops;
298 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
299 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
300 Result = CE->getWithOperands(Ops);
Reid Spencer361e5132004-11-12 20:37:43 +0000301 } else {
302 assert(0 && "Unknown type of derived type constant value!");
303 }
Chris Lattnerc7745922006-06-01 19:14:22 +0000304 } else if (isa<InlineAsm>(In)) {
305 Result = const_cast<Value*>(In);
306 }
307
308 // Cache the mapping in our local map structure...
309 if (Result) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000310 ValueMap.insert(std::make_pair(In, Result));
Reid Spencer361e5132004-11-12 20:37:43 +0000311 return Result;
312 }
Chris Lattnerc7745922006-06-01 19:14:22 +0000313
Reid Spencer361e5132004-11-12 20:37:43 +0000314
Bill Wendlingf3baad32006-12-07 01:30:32 +0000315 cerr << "LinkModules ValueMap: \n";
Chris Lattner7391dde2004-11-16 17:12:38 +0000316 PrintMap(ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000317
Bill Wendlingf3baad32006-12-07 01:30:32 +0000318 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000319 assert(0 && "Couldn't remap value!");
320 return 0;
321}
322
323/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
324/// in the symbol table. This is good for all clients except for us. Go
325/// through the trouble to force this back.
326static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
327 assert(GV->getName() != Name && "Can't force rename to self");
328 SymbolTable &ST = GV->getParent()->getSymbolTable();
329
330 // If there is a conflict, rename the conflict.
331 Value *ConflictVal = ST.lookup(GV->getType(), Name);
332 assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
333 GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
334 assert(ConflictGV->hasInternalLinkage() &&
335 "Not conflicting with a static global, should link instead!");
336
337 ConflictGV->setName(""); // Eliminate the conflict
338 GV->setName(Name); // Force the name back
339 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
340 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
341 "ForceRenaming didn't work");
342}
343
Chris Lattnerfc61de32004-12-03 22:18:41 +0000344/// GetLinkageResult - This analyzes the two global values and determines what
345/// the result will look like in the destination module. In particular, it
346/// computes the resultant linkage type, computes whether the global in the
347/// source should be copied over to the destination (replacing the existing
348/// one), and computes whether this linkage is an error or not.
349static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
350 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
351 std::string *Err) {
352 assert((!Dest || !Src->hasInternalLinkage()) &&
353 "If Src has internal linkage, Dest shouldn't be set!");
354 if (!Dest) {
355 // Linking something to nothing.
356 LinkFromSrc = true;
357 LT = Src->getLinkage();
358 } else if (Src->isExternal()) {
359 // If Src is external or if both Src & Drc are external.. Just link the
360 // external globals, we aren't adding anything.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000361 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000362 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000363 if (Dest->isExternal()) {
364 LinkFromSrc = true;
365 LT = Src->getLinkage();
366 }
367 } else {
368 LinkFromSrc = false;
369 LT = Dest->getLinkage();
370 }
371 } else if (Dest->isExternal() && !Dest->hasDLLImportLinkage()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000372 // If Dest is external but Src is not:
373 LinkFromSrc = true;
374 LT = Src->getLinkage();
375 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
376 if (Src->getLinkage() != Dest->getLinkage())
377 return Error(Err, "Linking globals named '" + Src->getName() +
378 "': can only link appending global with another appending global!");
379 LinkFromSrc = true; // Special cased.
380 LT = Src->getLinkage();
381 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000382 // At this point we know that Dest has LinkOnce, External*, Weak, DLL* linkage.
383 if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
384 Dest->hasExternalWeakLinkage()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000385 LinkFromSrc = true;
386 LT = Src->getLinkage();
387 } else {
388 LinkFromSrc = false;
389 LT = Dest->getLinkage();
390 }
391 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000392 // At this point we know that Src has External* or DLL* linkage.
393 if (Src->hasExternalWeakLinkage()) {
394 LinkFromSrc = false;
395 LT = Dest->getLinkage();
396 } else {
397 LinkFromSrc = true;
398 LT = GlobalValue::ExternalLinkage;
399 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000400 } else {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000401 assert((Dest->hasExternalLinkage() ||
402 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000403 Dest->hasDLLExportLinkage() ||
404 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000405 (Src->hasExternalLinkage() ||
406 Src->hasDLLImportLinkage() ||
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000407 Src->hasDLLExportLinkage() ||
408 Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000409 "Unexpected linkage type!");
Misha Brukman10468d82005-04-21 22:55:34 +0000410 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000411 "': symbol multiply defined!");
412 }
413 return false;
414}
Reid Spencer361e5132004-11-12 20:37:43 +0000415
416// LinkGlobals - Loop through the global variables in the src module and merge
417// them into the dest module.
Chris Lattnerfc61de32004-12-03 22:18:41 +0000418static bool LinkGlobals(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000419 std::map<const Value*, Value*> &ValueMap,
420 std::multimap<std::string, GlobalVariable *> &AppendingVars,
421 std::map<std::string, GlobalValue*> &GlobalsByName,
422 std::string *Err) {
423 // We will need a module level symbol table if the src module has a module
424 // level symbol table...
425 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000426
Reid Spencer361e5132004-11-12 20:37:43 +0000427 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000428 for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
429 I != E; ++I) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000430 GlobalVariable *SGV = I;
Reid Spencer361e5132004-11-12 20:37:43 +0000431 GlobalVariable *DGV = 0;
432 // Check to see if may have to link the global.
433 if (SGV->hasName() && !SGV->hasInternalLinkage())
434 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
435 SGV->getType()->getElementType()))) {
436 std::map<std::string, GlobalValue*>::iterator EGV =
437 GlobalsByName.find(SGV->getName());
438 if (EGV != GlobalsByName.end())
439 DGV = dyn_cast<GlobalVariable>(EGV->second);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000440 if (DGV)
441 // If types don't agree due to opaque types, try to resolve them.
442 RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
Reid Spencer361e5132004-11-12 20:37:43 +0000443 }
444
Chris Lattnerfc61de32004-12-03 22:18:41 +0000445 if (DGV && DGV->hasInternalLinkage())
446 DGV = 0;
447
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000448 assert(SGV->hasInitializer() ||
449 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
Reid Spencer361e5132004-11-12 20:37:43 +0000450 "Global must either be external or have an initializer!");
451
Chris Lattner1b9633d2006-11-09 05:18:12 +0000452 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
453 bool LinkFromSrc = false;
Chris Lattnerfc61de32004-12-03 22:18:41 +0000454 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
455 return true;
Reid Spencer361e5132004-11-12 20:37:43 +0000456
Chris Lattnerfc61de32004-12-03 22:18:41 +0000457 if (!DGV) {
Reid Spencer361e5132004-11-12 20:37:43 +0000458 // No linking to be performed, simply create an identical version of the
459 // symbol over in the dest module... the initializer will be filled in
460 // later by LinkGlobalInits...
Reid Spencer361e5132004-11-12 20:37:43 +0000461 GlobalVariable *NewDGV =
462 new GlobalVariable(SGV->getType()->getElementType(),
463 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
464 SGV->getName(), Dest);
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000465 // Propagate alignment info.
466 NewDGV->setAlignment(SGV->getAlignment());
467
Reid Spencer361e5132004-11-12 20:37:43 +0000468 // If the LLVM runtime renamed the global, but it is an externally visible
469 // symbol, DGV must be an existing global with internal linkage. Rename
470 // it.
471 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
472 ForceRenaming(NewDGV, SGV->getName());
473
474 // Make sure to remember this mapping...
475 ValueMap.insert(std::make_pair(SGV, NewDGV));
476 if (SGV->hasAppendingLinkage())
477 // Keep track that this is an appending variable...
478 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattnerfc61de32004-12-03 22:18:41 +0000479 } else if (DGV->hasAppendingLinkage()) {
Reid Spencer361e5132004-11-12 20:37:43 +0000480 // No linking is performed yet. Just insert a new copy of the global, and
481 // keep track of the fact that it is an appending variable in the
482 // AppendingVars map. The name is cleared out so that no linkage is
483 // performed.
484 GlobalVariable *NewDGV =
485 new GlobalVariable(SGV->getType()->getElementType(),
486 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
487 "", Dest);
488
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000489 // Propagate alignment info.
490 NewDGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
491
Reid Spencer361e5132004-11-12 20:37:43 +0000492 // Make sure to remember this mapping...
493 ValueMap.insert(std::make_pair(SGV, NewDGV));
494
495 // Keep track that this is an appending variable...
496 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
497 } else {
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000498 // Propagate alignment info.
499 DGV->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
500
Chris Lattnerfc61de32004-12-03 22:18:41 +0000501 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
502 // the types don't match, and if we are to link from the source, nuke DGV
503 // and create a new one of the appropriate type.
504 if (SGV->getType() != DGV->getType() && LinkFromSrc) {
505 GlobalVariable *NewDGV =
506 new GlobalVariable(SGV->getType()->getElementType(),
507 DGV->isConstant(), DGV->getLinkage());
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000508 NewDGV->setAlignment(DGV->getAlignment());
Chris Lattnerfc61de32004-12-03 22:18:41 +0000509 Dest->getGlobalList().insert(DGV, NewDGV);
510 DGV->replaceAllUsesWith(ConstantExpr::getCast(NewDGV, DGV->getType()));
511 DGV->eraseFromParent();
512 NewDGV->setName(SGV->getName());
513 DGV = NewDGV;
514 }
515
516 DGV->setLinkage(NewLinkage);
517
518 if (LinkFromSrc) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000519 // Inherit const as appropriate
Chris Lattner16277c12005-02-12 19:20:28 +0000520 DGV->setConstant(SGV->isConstant());
Chris Lattnerfc61de32004-12-03 22:18:41 +0000521 DGV->setInitializer(0);
522 } else {
523 if (SGV->isConstant() && !DGV->isConstant()) {
Chris Lattner16277c12005-02-12 19:20:28 +0000524 if (DGV->isExternal())
Chris Lattnerfc61de32004-12-03 22:18:41 +0000525 DGV->setConstant(true);
526 }
Chris Lattnera57c1052004-12-04 18:54:48 +0000527 SGV->setLinkage(GlobalValue::ExternalLinkage);
528 SGV->setInitializer(0);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000529 }
530
531 ValueMap.insert(std::make_pair(SGV,
532 ConstantExpr::getCast(DGV,
533 SGV->getType())));
Reid Spencer361e5132004-11-12 20:37:43 +0000534 }
535 }
536 return false;
537}
538
539
540// LinkGlobalInits - Update the initializers in the Dest module now that all
541// globals that may be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000542static bool LinkGlobalInits(Module *Dest, const Module *Src,
543 std::map<const Value*, Value*> &ValueMap,
544 std::string *Err) {
545
546 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000547 for (Module::const_global_iterator I = Src->global_begin(),
548 E = Src->global_end(); I != E; ++I) {
Reid Spencer361e5132004-11-12 20:37:43 +0000549 const GlobalVariable *SGV = I;
550
551 if (SGV->hasInitializer()) { // Only process initialized GV's
552 // Figure out what the initializer looks like in the dest module...
553 Constant *SInit =
Chris Lattner7391dde2004-11-16 17:12:38 +0000554 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000555
Misha Brukman10468d82005-04-21 22:55:34 +0000556 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Reid Spencer361e5132004-11-12 20:37:43 +0000557 if (DGV->hasInitializer()) {
558 if (SGV->hasExternalLinkage()) {
559 if (DGV->getInitializer() != SInit)
Misha Brukman10468d82005-04-21 22:55:34 +0000560 return Error(Err, "Global Variable Collision on '" +
Reid Spencer361e5132004-11-12 20:37:43 +0000561 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
562 " - Global variables have different initializers");
563 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
564 // Nothing is required, mapped values will take the new global
565 // automatically.
566 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
567 // Nothing is required, mapped values will take the new global
568 // automatically.
569 } else if (DGV->hasAppendingLinkage()) {
570 assert(0 && "Appending linkage unimplemented!");
571 } else {
572 assert(0 && "Unknown linkage!");
573 }
574 } else {
575 // Copy the initializer over now...
576 DGV->setInitializer(SInit);
577 }
578 }
579 }
580 return false;
581}
582
583// LinkFunctionProtos - Link the functions together between the two modules,
584// without doing function bodies... this just adds external function prototypes
585// to the Dest function...
586//
587static bool LinkFunctionProtos(Module *Dest, const Module *Src,
588 std::map<const Value*, Value*> &ValueMap,
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000589 std::map<std::string, GlobalValue*> &GlobalsByName,
Reid Spencer361e5132004-11-12 20:37:43 +0000590 std::string *Err) {
591 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000592
Reid Spencer361e5132004-11-12 20:37:43 +0000593 // Loop over all of the functions in the src module, mapping them over as we
594 // go
Reid Spencer361e5132004-11-12 20:37:43 +0000595 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
596 const Function *SF = I; // SrcFunction
597 Function *DF = 0;
598 if (SF->hasName() && !SF->hasInternalLinkage()) {
599 // Check to see if may have to link the function.
600 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
601 std::map<std::string, GlobalValue*>::iterator EF =
602 GlobalsByName.find(SF->getName());
603 if (EF != GlobalsByName.end())
604 DF = dyn_cast<Function>(EF->second);
605 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
606 DF = 0; // FIXME: gross.
607 }
608 }
609
610 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
611 // Function does not already exist, simply insert an function signature
612 // identical to SF into the dest module...
613 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
614 SF->getName(), Dest);
Chris Lattnere251b5c2005-05-09 01:09:39 +0000615 NewDF->setCallingConv(SF->getCallingConv());
Reid Spencer361e5132004-11-12 20:37:43 +0000616
617 // If the LLVM runtime renamed the function, but it is an externally
618 // visible symbol, DF must be an existing function with internal linkage.
619 // Rename it.
620 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
621 ForceRenaming(NewDF, SF->getName());
622
623 // ... and remember this mapping...
624 ValueMap.insert(std::make_pair(SF, NewDF));
625 } else if (SF->isExternal()) {
626 // If SF is external or if both SF & DF are external.. Just link the
627 // external functions, we aren't adding anything.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000628 if (SF->hasDLLImportLinkage()) {
629 if (DF->isExternal()) {
630 ValueMap.insert(std::make_pair(SF, DF));
631 DF->setLinkage(SF->getLinkage());
632 }
633 } else {
634 ValueMap.insert(std::make_pair(SF, DF));
635 }
636 } else if (DF->isExternal() && !DF->hasDLLImportLinkage()) {
637 // If DF is external but SF is not...
Reid Spencer361e5132004-11-12 20:37:43 +0000638 // Link the external functions, update linkage qualifiers
639 ValueMap.insert(std::make_pair(SF, DF));
640 DF->setLinkage(SF->getLinkage());
Reid Spencer361e5132004-11-12 20:37:43 +0000641 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000642 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
Reid Spencer361e5132004-11-12 20:37:43 +0000643 ValueMap.insert(std::make_pair(SF, DF));
644
645 // Linkonce+Weak = Weak
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000646 // *+External Weak = *
647 if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
648 DF->hasExternalWeakLinkage())
Reid Spencer361e5132004-11-12 20:37:43 +0000649 DF->setLinkage(SF->getLinkage());
650
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000651
Reid Spencer361e5132004-11-12 20:37:43 +0000652 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000653 // At this point we know that SF has LinkOnce or External* linkage.
Reid Spencer361e5132004-11-12 20:37:43 +0000654 ValueMap.insert(std::make_pair(SF, DF));
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000655 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
656 // Don't inherit linkonce & external weak linkage
Reid Spencer361e5132004-11-12 20:37:43 +0000657 DF->setLinkage(SF->getLinkage());
Reid Spencer361e5132004-11-12 20:37:43 +0000658 } else if (SF->getLinkage() != DF->getLinkage()) {
659 return Error(Err, "Functions named '" + SF->getName() +
660 "' have different linkage specifiers!");
661 } else if (SF->hasExternalLinkage()) {
662 // The function is defined in both modules!!
Misha Brukman10468d82005-04-21 22:55:34 +0000663 return Error(Err, "Function '" +
664 ToStr(SF->getFunctionType(), Src) + "':\"" +
Reid Spencer361e5132004-11-12 20:37:43 +0000665 SF->getName() + "\" - Function is already defined!");
666 } else {
667 assert(0 && "Unknown linkage configuration found!");
668 }
669 }
670 return false;
671}
672
673// LinkFunctionBody - Copy the source function over into the dest function and
674// fix up references to values. At this point we know that Dest is an external
675// function, and that Src is not.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000676static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000677 std::map<const Value*, Value*> &GlobalMap,
678 std::string *Err) {
679 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Reid Spencer361e5132004-11-12 20:37:43 +0000680
Chris Lattner7391dde2004-11-16 17:12:38 +0000681 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner531f9e92005-03-15 04:54:21 +0000682 Function::arg_iterator DI = Dest->arg_begin();
683 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000684 I != E; ++I, ++DI) {
685 DI->setName(I->getName()); // Copy the name information over...
686
687 // Add a mapping to our local map
Chris Lattner7391dde2004-11-16 17:12:38 +0000688 GlobalMap.insert(std::make_pair(I, DI));
Reid Spencer361e5132004-11-12 20:37:43 +0000689 }
690
Chris Lattner2f0557d2004-11-16 07:31:51 +0000691 // Splice the body of the source function into the dest function.
692 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Reid Spencer361e5132004-11-12 20:37:43 +0000693
694 // At this point, all of the instructions and values of the function are now
695 // copied over. The only problem is that they are still referencing values in
696 // the Source function as operands. Loop through all of the operands of the
697 // functions and patch them up to point to the local versions...
698 //
699 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
700 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
701 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
702 OI != OE; ++OI)
Chris Lattner2f0557d2004-11-16 07:31:51 +0000703 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner7391dde2004-11-16 17:12:38 +0000704 *OI = RemapOperand(*OI, GlobalMap);
705
706 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000707 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
708 I != E; ++I)
Chris Lattner7391dde2004-11-16 17:12:38 +0000709 GlobalMap.erase(I);
Reid Spencer361e5132004-11-12 20:37:43 +0000710
711 return false;
712}
713
714
715// LinkFunctionBodies - Link in the function bodies that are defined in the
716// source module into the DestModule. This consists basically of copying the
717// function over and fixing up references to values.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000718static bool LinkFunctionBodies(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000719 std::map<const Value*, Value*> &ValueMap,
720 std::string *Err) {
721
722 // Loop over all of the functions in the src module, mapping them over as we
723 // go
Chris Lattner2f0557d2004-11-16 07:31:51 +0000724 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer361e5132004-11-12 20:37:43 +0000725 if (!SF->isExternal()) { // No body if function is external
726 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
727
728 // DF not external SF external?
729 if (DF->isExternal()) {
730 // Only provide the function body if there isn't one already.
731 if (LinkFunctionBody(DF, SF, ValueMap, Err))
732 return true;
733 }
734 }
735 }
736 return false;
737}
738
739// LinkAppendingVars - If there were any appending global variables, link them
740// together now. Return true on error.
Reid Spencer361e5132004-11-12 20:37:43 +0000741static bool LinkAppendingVars(Module *M,
742 std::multimap<std::string, GlobalVariable *> &AppendingVars,
743 std::string *ErrorMsg) {
744 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukman10468d82005-04-21 22:55:34 +0000745
Reid Spencer361e5132004-11-12 20:37:43 +0000746 // Loop over the multimap of appending vars, processing any variables with the
747 // same name, forming a new appending global variable with both of the
748 // initializers merged together, then rewrite references to the old variables
749 // and delete them.
Reid Spencer361e5132004-11-12 20:37:43 +0000750 std::vector<Constant*> Inits;
751 while (AppendingVars.size() > 1) {
752 // Get the first two elements in the map...
753 std::multimap<std::string,
754 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
755
756 // If the first two elements are for different names, there is no pair...
757 // Otherwise there is a pair, so link them together...
758 if (First->first == Second->first) {
759 GlobalVariable *G1 = First->second, *G2 = Second->second;
760 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
761 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukman10468d82005-04-21 22:55:34 +0000762
Reid Spencer361e5132004-11-12 20:37:43 +0000763 // Check to see that they two arrays agree on type...
764 if (T1->getElementType() != T2->getElementType())
765 return Error(ErrorMsg,
766 "Appending variables with different element types need to be linked!");
767 if (G1->isConstant() != G2->isConstant())
768 return Error(ErrorMsg,
769 "Appending variables linked with different const'ness!");
770
771 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
772 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
773
Chris Lattnerd490d4f2005-12-06 17:30:58 +0000774 G1->setName(""); // Clear G1's name in case of a conflict!
775
Reid Spencer361e5132004-11-12 20:37:43 +0000776 // Create the new global variable...
777 GlobalVariable *NG =
778 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
779 /*init*/0, First->first, M);
780
781 // Merge the initializer...
782 Inits.reserve(NewSize);
783 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
784 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
785 Inits.push_back(I->getOperand(i));
786 } else {
787 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
788 Constant *CV = Constant::getNullValue(T1->getElementType());
789 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
790 Inits.push_back(CV);
791 }
792 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
793 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
794 Inits.push_back(I->getOperand(i));
795 } else {
796 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
797 Constant *CV = Constant::getNullValue(T2->getElementType());
798 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
799 Inits.push_back(CV);
800 }
801 NG->setInitializer(ConstantArray::get(NewType, Inits));
802 Inits.clear();
803
804 // Replace any uses of the two global variables with uses of the new
805 // global...
806
807 // FIXME: This should rewrite simple/straight-forward uses such as
808 // getelementptr instructions to not use the Cast!
809 G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
810 G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
811
812 // Remove the two globals from the module now...
813 M->getGlobalList().erase(G1);
814 M->getGlobalList().erase(G2);
815
816 // Put the new global into the AppendingVars map so that we can handle
817 // linking of more than two vars...
818 Second->second = NG;
819 }
820 AppendingVars.erase(First);
821 }
822
823 return false;
824}
825
826
827// LinkModules - This function links two modules together, with the resulting
828// left module modified to be the composite of the two input modules. If an
829// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
830// the problem. Upon failure, the Dest module could be in a modified state, and
831// shouldn't be relied on to be consistent.
Misha Brukman10468d82005-04-21 22:55:34 +0000832bool
Reid Spencerc4e31532004-12-13 03:00:16 +0000833Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer361e5132004-11-12 20:37:43 +0000834 assert(Dest != 0 && "Invalid Destination module");
835 assert(Src != 0 && "Invalid Source Module");
836
837 if (Dest->getEndianness() == Module::AnyEndianness)
838 Dest->setEndianness(Src->getEndianness());
839 if (Dest->getPointerSize() == Module::AnyPointerSize)
840 Dest->setPointerSize(Src->getPointerSize());
Chris Lattnerb7f59162004-12-10 20:26:15 +0000841 if (Dest->getTargetTriple().empty())
842 Dest->setTargetTriple(Src->getTargetTriple());
Reid Spencer361e5132004-11-12 20:37:43 +0000843
844 if (Src->getEndianness() != Module::AnyEndianness &&
845 Dest->getEndianness() != Src->getEndianness())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000846 cerr << "WARNING: Linking two modules of different endianness!\n";
Reid Spencer361e5132004-11-12 20:37:43 +0000847 if (Src->getPointerSize() != Module::AnyPointerSize &&
848 Dest->getPointerSize() != Src->getPointerSize())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000849 cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattnerb7f59162004-12-10 20:26:15 +0000850 if (!Src->getTargetTriple().empty() &&
851 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlingf3baad32006-12-07 01:30:32 +0000852 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukman10468d82005-04-21 22:55:34 +0000853
Chris Lattner8ebd2162006-01-24 04:14:29 +0000854 if (!Src->getModuleInlineAsm().empty()) {
855 if (Dest->getModuleInlineAsm().empty())
856 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000857 else
Chris Lattner8ebd2162006-01-24 04:14:29 +0000858 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
859 Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000860 }
861
Reid Spencer2c4f9a42004-11-25 09:29:44 +0000862 // Update the destination module's dependent libraries list with the libraries
Reid Spencer361e5132004-11-12 20:37:43 +0000863 // from the source module. There's no opportunity for duplicates here as the
864 // Module ensures that duplicate insertions are discarded.
865 Module::lib_iterator SI = Src->lib_begin();
866 Module::lib_iterator SE = Src->lib_end();
867 while ( SI != SE ) {
868 Dest->addLibrary(*SI);
869 ++SI;
870 }
871
872 // LinkTypes - Go through the symbol table of the Src module and see if any
873 // types are named in the src module that are not named in the Dst module.
874 // Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000875 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
876
877 // ValueMap - Mapping of values from what they used to be in Src, to what they
878 // are now in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000879 std::map<const Value*, Value*> ValueMap;
880
881 // AppendingVars - Keep track of global variables in the destination module
882 // with appending linkage. After the module is linked together, they are
883 // appended and the module is rewritten.
Reid Spencer361e5132004-11-12 20:37:43 +0000884 std::multimap<std::string, GlobalVariable *> AppendingVars;
885
886 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
887 // linking by separating globals by type. Until PR411 is fixed, we replicate
888 // it's functionality here.
889 std::map<std::string, GlobalValue*> GlobalsByName;
890
Chris Lattner44ab8ae2006-06-16 01:24:04 +0000891 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
892 I != E; ++I) {
Reid Spencer361e5132004-11-12 20:37:43 +0000893 // Add all of the appending globals already in the Dest module to
894 // AppendingVars.
895 if (I->hasAppendingLinkage())
896 AppendingVars.insert(std::make_pair(I->getName(), I));
897
898 // Keep track of all globals by name.
899 if (!I->hasInternalLinkage() && I->hasName())
900 GlobalsByName[I->getName()] = I;
901 }
902
903 // Keep track of all globals by name.
904 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
905 if (!I->hasInternalLinkage() && I->hasName())
906 GlobalsByName[I->getName()] = I;
907
908 // Insert all of the globals in src into the Dest module... without linking
909 // initializers (which could refer to functions not yet mapped over).
Reid Spencer361e5132004-11-12 20:37:43 +0000910 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
911 return true;
912
913 // Link the functions together between the two modules, without doing function
914 // bodies... this just adds external function prototypes to the Dest
915 // function... We do this so that when we begin processing function bodies,
916 // all of the global values that may be referenced are available in our
917 // ValueMap.
Reid Spencer361e5132004-11-12 20:37:43 +0000918 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
919 return true;
920
921 // Update the initializers in the Dest module now that all globals that may
922 // be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000923 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
924
925 // Link in the function bodies that are defined in the source module into the
926 // DestModule. This consists basically of copying the function over and
927 // fixing up references to values.
Reid Spencer361e5132004-11-12 20:37:43 +0000928 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
929
930 // If there were any appending global variables, link them together now.
Reid Spencer361e5132004-11-12 20:37:43 +0000931 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
932
933 // If the source library's module id is in the dependent library list of the
934 // destination library, remove it since that module is now linked in.
935 sys::Path modId;
Reid Spencerc9c04732005-07-07 23:21:43 +0000936 modId.set(Src->getModuleIdentifier());
Reid Spencer361e5132004-11-12 20:37:43 +0000937 if (!modId.isEmpty())
938 Dest->removeLibrary(modId.getBasename());
939
940 return false;
941}
942
943// vim: sw=2