blob: c8ea03898e348a0568b93d9811377a57f3e0a4de [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"
26#include "llvm/System/Path.h"
27#include <iostream>
28#include <sstream>
29using namespace llvm;
30
31// Error - Simple wrapper function to conditionally assign to E and return true.
32// This just makes error return conditions a little bit simpler...
Reid Spencer361e5132004-11-12 20:37:43 +000033static inline bool Error(std::string *E, const std::string &Message) {
34 if (E) *E = Message;
35 return true;
36}
37
Reid Spencer2c4f9a42004-11-25 09:29:44 +000038// ToStr - Simple wrapper function to convert a type to a string.
Reid Spencer361e5132004-11-12 20:37:43 +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
45//
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.
62//
63static 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
67 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
69 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
71 } 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...
76 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
78 else if (!Name.empty())
79 DestST->insert(Name, const_cast<Type*>(SrcTy));
80 }
81 return false;
82}
83
84static const FunctionType *getFT(const PATypeHolder &TH) {
85 return cast<FunctionType>(TH.get());
86}
87static const StructType *getST(const PATypeHolder &TH) {
88 return cast<StructType>(TH.get());
89}
90
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.
Reid Spencer361e5132004-11-12 20:37:43 +000094static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
95 const PATypeHolder &SrcTy,
96 SymbolTable *DestST, const std::string &Name,
97 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
98 const Type *SrcTyT = SrcTy.get();
99 const Type *DestTyT = DestTy.get();
100 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukman10468d82005-04-21 22:55:34 +0000101
Reid Spencer361e5132004-11-12 20:37:43 +0000102 // If we found our opaque type, resolve it now!
103 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
104 return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
Misha Brukman10468d82005-04-21 22:55:34 +0000105
Reid Spencer361e5132004-11-12 20:37:43 +0000106 // Two types cannot be resolved together if they are of different primitive
107 // type. For example, we cannot resolve an int to a float.
108 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
109
110 // Otherwise, resolve the used type used by this derived type...
111 switch (DestTyT->getTypeID()) {
112 case Type::FunctionTyID: {
113 if (cast<FunctionType>(DestTyT)->isVarArg() !=
114 cast<FunctionType>(SrcTyT)->isVarArg() ||
115 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
116 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
117 return true;
118 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
119 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
120 getFT(SrcTy)->getContainedType(i), DestST, "",
121 Pointers))
122 return true;
123 return false;
124 }
125 case Type::StructTyID: {
Misha Brukman10468d82005-04-21 22:55:34 +0000126 if (getST(DestTy)->getNumContainedTypes() !=
Reid Spencer361e5132004-11-12 20:37:43 +0000127 getST(SrcTy)->getNumContainedTypes()) return 1;
128 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
129 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
130 getST(SrcTy)->getContainedType(i), DestST, "",
131 Pointers))
132 return true;
133 return false;
134 }
135 case Type::ArrayTyID: {
136 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
137 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
138 if (DAT->getNumElements() != SAT->getNumElements()) return true;
139 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
140 DestST, "", Pointers);
141 }
142 case Type::PointerTyID: {
143 // If this is a pointer type, check to see if we have already seen it. If
144 // so, we are in a recursive branch. Cut off the search now. We cannot use
145 // an associative container for this search, because the type pointers (keys
146 // in the container) change whenever types get resolved...
Reid Spencer361e5132004-11-12 20:37:43 +0000147 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
148 if (Pointers[i].first == DestTy)
149 return Pointers[i].second != SrcTy;
150
151 // Otherwise, add the current pointers to the vector to stop recursion on
152 // this pair.
153 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
154 bool Result =
155 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
156 cast<PointerType>(SrcTy.get())->getElementType(),
157 DestST, "", Pointers);
158 Pointers.pop_back();
159 return Result;
160 }
161 default: assert(0 && "Unexpected type!"); return true;
Misha Brukman10468d82005-04-21 22:55:34 +0000162 }
Reid Spencer361e5132004-11-12 20:37:43 +0000163}
164
165static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
166 const PATypeHolder &SrcTy,
167 SymbolTable *DestST, const std::string &Name){
168 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
169 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
170}
171
172
173// LinkTypes - Go through the symbol table of the Src module and see if any
174// types are named in the src module that are not named in the Dst module.
175// Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000176static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
177 SymbolTable *DestST = &Dest->getSymbolTable();
178 const SymbolTable *SrcST = &Src->getSymbolTable();
179
180 // Look for a type plane for Type's...
181 SymbolTable::type_const_iterator TI = SrcST->type_begin();
182 SymbolTable::type_const_iterator TE = SrcST->type_end();
183 if (TI == TE) return false; // No named types, do nothing.
184
185 // Some types cannot be resolved immediately because they depend on other
186 // types being resolved to each other first. This contains a list of types we
187 // are waiting to recheck.
188 std::vector<std::string> DelayedTypesToResolve;
189
190 for ( ; TI != TE; ++TI ) {
191 const std::string &Name = TI->first;
192 const Type *RHS = TI->second;
193
194 // Check to see if this type name is already in the dest module...
195 Type *Entry = DestST->lookupType(Name);
196
197 if (ResolveTypes(Entry, RHS, DestST, Name)) {
198 // They look different, save the types 'till later to resolve.
199 DelayedTypesToResolve.push_back(Name);
200 }
201 }
202
203 // Iteratively resolve types while we can...
204 while (!DelayedTypesToResolve.empty()) {
205 // Loop over all of the types, attempting to resolve them if possible...
206 unsigned OldSize = DelayedTypesToResolve.size();
207
208 // Try direct resolution by name...
209 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
210 const std::string &Name = DelayedTypesToResolve[i];
211 Type *T1 = SrcST->lookupType(Name);
212 Type *T2 = DestST->lookupType(Name);
213 if (!ResolveTypes(T2, T1, DestST, Name)) {
214 // We are making progress!
215 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
216 --i;
217 }
218 }
219
220 // Did we not eliminate any types?
221 if (DelayedTypesToResolve.size() == OldSize) {
222 // Attempt to resolve subelements of types. This allows us to merge these
223 // two types: { int* } and { opaque* }
224 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
225 const std::string &Name = DelayedTypesToResolve[i];
226 PATypeHolder T1(SrcST->lookupType(Name));
227 PATypeHolder T2(DestST->lookupType(Name));
228
229 if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
230 // We are making progress!
231 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukman10468d82005-04-21 22:55:34 +0000232
Reid Spencer361e5132004-11-12 20:37:43 +0000233 // Go back to the main loop, perhaps we can resolve directly by name
234 // now...
235 break;
236 }
237 }
238
239 // If we STILL cannot resolve the types, then there is something wrong.
Reid Spencer361e5132004-11-12 20:37:43 +0000240 if (DelayedTypesToResolve.size() == OldSize) {
Reid Spencer361e5132004-11-12 20:37:43 +0000241 // Remove the symbol name from the destination.
242 DelayedTypesToResolve.pop_back();
243 }
244 }
245 }
246
247
248 return false;
249}
250
251static void PrintMap(const std::map<const Value*, Value*> &M) {
252 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
253 I != E; ++I) {
254 std::cerr << " Fr: " << (void*)I->first << " ";
255 I->first->dump();
256 std::cerr << " To: " << (void*)I->second << " ";
257 I->second->dump();
258 std::cerr << "\n";
259 }
260}
261
262
Chris Lattner7391dde2004-11-16 17:12:38 +0000263// RemapOperand - Use ValueMap to convert references from one module to another.
264// This is somewhat sophisticated in that it can automatically handle constant
265// references correctly as well...
Reid Spencer361e5132004-11-12 20:37:43 +0000266static Value *RemapOperand(const Value *In,
Chris Lattner7391dde2004-11-16 17:12:38 +0000267 std::map<const Value*, Value*> &ValueMap) {
268 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
269 if (I != ValueMap.end()) return I->second;
Reid Spencer361e5132004-11-12 20:37:43 +0000270
Chris Lattner7391dde2004-11-16 17:12:38 +0000271 // Check to see if it's a constant that we are interesting in transforming.
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
277 Constant *Result = 0;
278
279 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
280 std::vector<Constant*> Operands(CPA->getNumOperands());
281 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000282 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000283 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
284 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
285 std::vector<Constant*> Operands(CPS->getNumOperands());
286 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner7391dde2004-11-16 17:12:38 +0000287 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000288 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
289 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
290 Result = const_cast<Constant*>(CPV);
291 } else if (isa<GlobalValue>(CPV)) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000292 Result = cast<Constant>(RemapOperand(CPV, ValueMap));
Chris Lattner93bde9c2006-01-19 23:15:58 +0000293 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CPV)) {
294 std::vector<Constant*> Operands(CP->getNumOperands());
295 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
296 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
297 Result = ConstantPacked::get(Operands);
Reid Spencer361e5132004-11-12 20:37:43 +0000298 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
299 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner7391dde2004-11-16 17:12:38 +0000300 Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000301 std::vector<Constant*> Indices;
302 Indices.reserve(CE->getNumOperands()-1);
303 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
304 Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
Chris Lattner7391dde2004-11-16 17:12:38 +0000305 ValueMap)));
Reid Spencer361e5132004-11-12 20:37:43 +0000306
307 Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
Evan Cheng5c349b82006-04-07 01:27:42 +0000308 } else if (CE->getOpcode() == Instruction::ExtractElement) {
309 Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
310 Value *Idx = RemapOperand(CE->getOperand(1), ValueMap);
311 Result = ConstantExpr::getExtractElement(cast<Constant>(Ptr),
312 cast<Constant>(Idx));
313 } else if (CE->getOpcode() == Instruction::InsertElement) {
314 Value *Ptr = RemapOperand(CE->getOperand(0), ValueMap);
315 Value *Elt = RemapOperand(CE->getOperand(1), ValueMap);
316 Value *Idx = RemapOperand(CE->getOperand(2), ValueMap);
317 Result = ConstantExpr::getInsertElement(cast<Constant>(Ptr),
318 cast<Constant>(Elt),
319 cast<Constant>(Idx));
Reid Spencer361e5132004-11-12 20:37:43 +0000320 } else if (CE->getNumOperands() == 1) {
321 // Cast instruction
322 assert(CE->getOpcode() == Instruction::Cast);
Chris Lattner7391dde2004-11-16 17:12:38 +0000323 Value *V = RemapOperand(CE->getOperand(0), ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000324 Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
325 } else if (CE->getNumOperands() == 3) {
326 // Select instruction
327 assert(CE->getOpcode() == Instruction::Select);
Chris Lattner7391dde2004-11-16 17:12:38 +0000328 Value *V1 = RemapOperand(CE->getOperand(0), ValueMap);
329 Value *V2 = RemapOperand(CE->getOperand(1), ValueMap);
330 Value *V3 = RemapOperand(CE->getOperand(2), ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000331 Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
332 cast<Constant>(V3));
333 } else if (CE->getNumOperands() == 2) {
334 // Binary operator...
Chris Lattner7391dde2004-11-16 17:12:38 +0000335 Value *V1 = RemapOperand(CE->getOperand(0), ValueMap);
336 Value *V2 = RemapOperand(CE->getOperand(1), ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000337
338 Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
339 cast<Constant>(V2));
340 } else {
341 assert(0 && "Unknown constant expr type!");
342 }
343
344 } else {
345 assert(0 && "Unknown type of derived type constant value!");
346 }
347
348 // Cache the mapping in our local map structure...
Chris Lattner7391dde2004-11-16 17:12:38 +0000349 ValueMap.insert(std::make_pair(In, Result));
Reid Spencer361e5132004-11-12 20:37:43 +0000350 return Result;
351 }
352
Chris Lattner7391dde2004-11-16 17:12:38 +0000353 std::cerr << "LinkModules ValueMap: \n";
354 PrintMap(ValueMap);
Reid Spencer361e5132004-11-12 20:37:43 +0000355
356 std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
357 assert(0 && "Couldn't remap value!");
358 return 0;
359}
360
361/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
362/// in the symbol table. This is good for all clients except for us. Go
363/// through the trouble to force this back.
364static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
365 assert(GV->getName() != Name && "Can't force rename to self");
366 SymbolTable &ST = GV->getParent()->getSymbolTable();
367
368 // If there is a conflict, rename the conflict.
369 Value *ConflictVal = ST.lookup(GV->getType(), Name);
370 assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
371 GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
372 assert(ConflictGV->hasInternalLinkage() &&
373 "Not conflicting with a static global, should link instead!");
374
375 ConflictGV->setName(""); // Eliminate the conflict
376 GV->setName(Name); // Force the name back
377 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
378 assert(GV->getName() == Name && ConflictGV->getName() != Name &&
379 "ForceRenaming didn't work");
380}
381
Chris Lattnerfc61de32004-12-03 22:18:41 +0000382/// GetLinkageResult - This analyzes the two global values and determines what
383/// the result will look like in the destination module. In particular, it
384/// computes the resultant linkage type, computes whether the global in the
385/// source should be copied over to the destination (replacing the existing
386/// one), and computes whether this linkage is an error or not.
387static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
388 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
389 std::string *Err) {
390 assert((!Dest || !Src->hasInternalLinkage()) &&
391 "If Src has internal linkage, Dest shouldn't be set!");
392 if (!Dest) {
393 // Linking something to nothing.
394 LinkFromSrc = true;
395 LT = Src->getLinkage();
396 } else if (Src->isExternal()) {
397 // If Src is external or if both Src & Drc are external.. Just link the
398 // external globals, we aren't adding anything.
399 LinkFromSrc = false;
400 LT = Dest->getLinkage();
401 } else if (Dest->isExternal()) {
402 // If Dest is external but Src is not:
403 LinkFromSrc = true;
404 LT = Src->getLinkage();
405 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
406 if (Src->getLinkage() != Dest->getLinkage())
407 return Error(Err, "Linking globals named '" + Src->getName() +
408 "': can only link appending global with another appending global!");
409 LinkFromSrc = true; // Special cased.
410 LT = Src->getLinkage();
411 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
412 // At this point we know that Dest has LinkOnce, External or Weak linkage.
413 if (Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) {
414 LinkFromSrc = true;
415 LT = Src->getLinkage();
416 } else {
417 LinkFromSrc = false;
418 LT = Dest->getLinkage();
419 }
420 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
421 // At this point we know that Src has External linkage.
422 LinkFromSrc = true;
423 LT = GlobalValue::ExternalLinkage;
424 } else {
425 assert(Dest->hasExternalLinkage() && Src->hasExternalLinkage() &&
426 "Unexpected linkage type!");
Misha Brukman10468d82005-04-21 22:55:34 +0000427 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000428 "': symbol multiply defined!");
429 }
430 return false;
431}
Reid Spencer361e5132004-11-12 20:37:43 +0000432
433// LinkGlobals - Loop through the global variables in the src module and merge
434// them into the dest module.
Chris Lattnerfc61de32004-12-03 22:18:41 +0000435static bool LinkGlobals(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000436 std::map<const Value*, Value*> &ValueMap,
437 std::multimap<std::string, GlobalVariable *> &AppendingVars,
438 std::map<std::string, GlobalValue*> &GlobalsByName,
439 std::string *Err) {
440 // We will need a module level symbol table if the src module has a module
441 // level symbol table...
442 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000443
Reid Spencer361e5132004-11-12 20:37:43 +0000444 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner531f9e92005-03-15 04:54:21 +0000445 for (Module::global_iterator I = Src->global_begin(), E = Src->global_end(); I != E; ++I) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000446 GlobalVariable *SGV = I;
Reid Spencer361e5132004-11-12 20:37:43 +0000447 GlobalVariable *DGV = 0;
448 // Check to see if may have to link the global.
449 if (SGV->hasName() && !SGV->hasInternalLinkage())
450 if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
451 SGV->getType()->getElementType()))) {
452 std::map<std::string, GlobalValue*>::iterator EGV =
453 GlobalsByName.find(SGV->getName());
454 if (EGV != GlobalsByName.end())
455 DGV = dyn_cast<GlobalVariable>(EGV->second);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000456 if (DGV)
457 // If types don't agree due to opaque types, try to resolve them.
458 RecursiveResolveTypes(SGV->getType(), DGV->getType(),ST, "");
Reid Spencer361e5132004-11-12 20:37:43 +0000459 }
460
Chris Lattnerfc61de32004-12-03 22:18:41 +0000461 if (DGV && DGV->hasInternalLinkage())
462 DGV = 0;
463
Reid Spencer361e5132004-11-12 20:37:43 +0000464 assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
465 "Global must either be external or have an initializer!");
466
Chris Lattnerfc61de32004-12-03 22:18:41 +0000467 GlobalValue::LinkageTypes NewLinkage;
468 bool LinkFromSrc;
469 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
470 return true;
Reid Spencer361e5132004-11-12 20:37:43 +0000471
Chris Lattnerfc61de32004-12-03 22:18:41 +0000472 if (!DGV) {
Reid Spencer361e5132004-11-12 20:37:43 +0000473 // No linking to be performed, simply create an identical version of the
474 // symbol over in the dest module... the initializer will be filled in
475 // later by LinkGlobalInits...
Reid Spencer361e5132004-11-12 20:37:43 +0000476 GlobalVariable *NewDGV =
477 new GlobalVariable(SGV->getType()->getElementType(),
478 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
479 SGV->getName(), Dest);
480
481 // If the LLVM runtime renamed the global, but it is an externally visible
482 // symbol, DGV must be an existing global with internal linkage. Rename
483 // it.
484 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
485 ForceRenaming(NewDGV, SGV->getName());
486
487 // Make sure to remember this mapping...
488 ValueMap.insert(std::make_pair(SGV, NewDGV));
489 if (SGV->hasAppendingLinkage())
490 // Keep track that this is an appending variable...
491 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattnerfc61de32004-12-03 22:18:41 +0000492 } else if (DGV->hasAppendingLinkage()) {
Reid Spencer361e5132004-11-12 20:37:43 +0000493 // No linking is performed yet. Just insert a new copy of the global, and
494 // keep track of the fact that it is an appending variable in the
495 // AppendingVars map. The name is cleared out so that no linkage is
496 // performed.
497 GlobalVariable *NewDGV =
498 new GlobalVariable(SGV->getType()->getElementType(),
499 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
500 "", Dest);
501
502 // Make sure to remember this mapping...
503 ValueMap.insert(std::make_pair(SGV, NewDGV));
504
505 // Keep track that this is an appending variable...
506 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
507 } else {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000508 // Otherwise, perform the mapping as instructed by GetLinkageResult. If
509 // the types don't match, and if we are to link from the source, nuke DGV
510 // and create a new one of the appropriate type.
511 if (SGV->getType() != DGV->getType() && LinkFromSrc) {
512 GlobalVariable *NewDGV =
513 new GlobalVariable(SGV->getType()->getElementType(),
514 DGV->isConstant(), DGV->getLinkage());
515 Dest->getGlobalList().insert(DGV, NewDGV);
516 DGV->replaceAllUsesWith(ConstantExpr::getCast(NewDGV, DGV->getType()));
517 DGV->eraseFromParent();
518 NewDGV->setName(SGV->getName());
519 DGV = NewDGV;
520 }
521
522 DGV->setLinkage(NewLinkage);
523
524 if (LinkFromSrc) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000525 // Inherit const as appropriate
Chris Lattner16277c12005-02-12 19:20:28 +0000526 DGV->setConstant(SGV->isConstant());
Chris Lattnerfc61de32004-12-03 22:18:41 +0000527 DGV->setInitializer(0);
528 } else {
529 if (SGV->isConstant() && !DGV->isConstant()) {
Chris Lattner16277c12005-02-12 19:20:28 +0000530 if (DGV->isExternal())
Chris Lattnerfc61de32004-12-03 22:18:41 +0000531 DGV->setConstant(true);
532 }
Chris Lattnera57c1052004-12-04 18:54:48 +0000533 SGV->setLinkage(GlobalValue::ExternalLinkage);
534 SGV->setInitializer(0);
Chris Lattnerfc61de32004-12-03 22:18:41 +0000535 }
536
537 ValueMap.insert(std::make_pair(SGV,
538 ConstantExpr::getCast(DGV,
539 SGV->getType())));
Reid Spencer361e5132004-11-12 20:37:43 +0000540 }
541 }
542 return false;
543}
544
545
546// LinkGlobalInits - Update the initializers in the Dest module now that all
547// globals that may be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000548static bool LinkGlobalInits(Module *Dest, const Module *Src,
549 std::map<const Value*, Value*> &ValueMap,
550 std::string *Err) {
551
552 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner531f9e92005-03-15 04:54:21 +0000553 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end(); I != E; ++I){
Reid Spencer361e5132004-11-12 20:37:43 +0000554 const GlobalVariable *SGV = I;
555
556 if (SGV->hasInitializer()) { // Only process initialized GV's
557 // Figure out what the initializer looks like in the dest module...
558 Constant *SInit =
Chris Lattner7391dde2004-11-16 17:12:38 +0000559 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Reid Spencer361e5132004-11-12 20:37:43 +0000560
Misha Brukman10468d82005-04-21 22:55:34 +0000561 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
Reid Spencer361e5132004-11-12 20:37:43 +0000562 if (DGV->hasInitializer()) {
563 if (SGV->hasExternalLinkage()) {
564 if (DGV->getInitializer() != SInit)
Misha Brukman10468d82005-04-21 22:55:34 +0000565 return Error(Err, "Global Variable Collision on '" +
Reid Spencer361e5132004-11-12 20:37:43 +0000566 ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
567 " - Global variables have different initializers");
568 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
569 // Nothing is required, mapped values will take the new global
570 // automatically.
571 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
572 // Nothing is required, mapped values will take the new global
573 // automatically.
574 } else if (DGV->hasAppendingLinkage()) {
575 assert(0 && "Appending linkage unimplemented!");
576 } else {
577 assert(0 && "Unknown linkage!");
578 }
579 } else {
580 // Copy the initializer over now...
581 DGV->setInitializer(SInit);
582 }
583 }
584 }
585 return false;
586}
587
588// LinkFunctionProtos - Link the functions together between the two modules,
589// without doing function bodies... this just adds external function prototypes
590// to the Dest function...
591//
592static bool LinkFunctionProtos(Module *Dest, const Module *Src,
593 std::map<const Value*, Value*> &ValueMap,
594 std::map<std::string, GlobalValue*> &GlobalsByName,
595 std::string *Err) {
596 SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
Misha Brukman10468d82005-04-21 22:55:34 +0000597
Reid Spencer361e5132004-11-12 20:37:43 +0000598 // Loop over all of the functions in the src module, mapping them over as we
599 // go
Reid Spencer361e5132004-11-12 20:37:43 +0000600 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
601 const Function *SF = I; // SrcFunction
602 Function *DF = 0;
603 if (SF->hasName() && !SF->hasInternalLinkage()) {
604 // Check to see if may have to link the function.
605 if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
606 std::map<std::string, GlobalValue*>::iterator EF =
607 GlobalsByName.find(SF->getName());
608 if (EF != GlobalsByName.end())
609 DF = dyn_cast<Function>(EF->second);
610 if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
611 DF = 0; // FIXME: gross.
612 }
613 }
614
615 if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
616 // Function does not already exist, simply insert an function signature
617 // identical to SF into the dest module...
618 Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
619 SF->getName(), Dest);
Chris Lattnere251b5c2005-05-09 01:09:39 +0000620 NewDF->setCallingConv(SF->getCallingConv());
Reid Spencer361e5132004-11-12 20:37:43 +0000621
622 // If the LLVM runtime renamed the function, but it is an externally
623 // visible symbol, DF must be an existing function with internal linkage.
624 // Rename it.
625 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
626 ForceRenaming(NewDF, SF->getName());
627
628 // ... and remember this mapping...
629 ValueMap.insert(std::make_pair(SF, NewDF));
630 } else if (SF->isExternal()) {
631 // If SF is external or if both SF & DF are external.. Just link the
632 // external functions, we aren't adding anything.
633 ValueMap.insert(std::make_pair(SF, DF));
634 } else if (DF->isExternal()) { // If DF is external but SF is not...
635 // Link the external functions, update linkage qualifiers
636 ValueMap.insert(std::make_pair(SF, DF));
637 DF->setLinkage(SF->getLinkage());
638
639 } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
640 // At this point we know that DF has LinkOnce, Weak, or External linkage.
641 ValueMap.insert(std::make_pair(SF, DF));
642
643 // Linkonce+Weak = Weak
644 if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
645 DF->setLinkage(SF->getLinkage());
646
647 } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
648 // At this point we know that SF has LinkOnce or External linkage.
649 ValueMap.insert(std::make_pair(SF, DF));
650 if (!SF->hasLinkOnceLinkage()) // Don't inherit linkonce linkage
651 DF->setLinkage(SF->getLinkage());
652
653 } else if (SF->getLinkage() != DF->getLinkage()) {
654 return Error(Err, "Functions named '" + SF->getName() +
655 "' have different linkage specifiers!");
656 } else if (SF->hasExternalLinkage()) {
657 // The function is defined in both modules!!
Misha Brukman10468d82005-04-21 22:55:34 +0000658 return Error(Err, "Function '" +
659 ToStr(SF->getFunctionType(), Src) + "':\"" +
Reid Spencer361e5132004-11-12 20:37:43 +0000660 SF->getName() + "\" - Function is already defined!");
661 } else {
662 assert(0 && "Unknown linkage configuration found!");
663 }
664 }
665 return false;
666}
667
668// LinkFunctionBody - Copy the source function over into the dest function and
669// fix up references to values. At this point we know that Dest is an external
670// function, and that Src is not.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000671static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000672 std::map<const Value*, Value*> &GlobalMap,
673 std::string *Err) {
674 assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
Reid Spencer361e5132004-11-12 20:37:43 +0000675
Chris Lattner7391dde2004-11-16 17:12:38 +0000676 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner531f9e92005-03-15 04:54:21 +0000677 Function::arg_iterator DI = Dest->arg_begin();
678 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000679 I != E; ++I, ++DI) {
680 DI->setName(I->getName()); // Copy the name information over...
681
682 // Add a mapping to our local map
Chris Lattner7391dde2004-11-16 17:12:38 +0000683 GlobalMap.insert(std::make_pair(I, DI));
Reid Spencer361e5132004-11-12 20:37:43 +0000684 }
685
Chris Lattner2f0557d2004-11-16 07:31:51 +0000686 // Splice the body of the source function into the dest function.
687 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Reid Spencer361e5132004-11-12 20:37:43 +0000688
689 // At this point, all of the instructions and values of the function are now
690 // copied over. The only problem is that they are still referencing values in
691 // the Source function as operands. Loop through all of the operands of the
692 // functions and patch them up to point to the local versions...
693 //
694 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
695 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
696 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
697 OI != OE; ++OI)
Chris Lattner2f0557d2004-11-16 07:31:51 +0000698 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner7391dde2004-11-16 17:12:38 +0000699 *OI = RemapOperand(*OI, GlobalMap);
700
701 // There is no need to map the arguments anymore.
Chris Lattner531f9e92005-03-15 04:54:21 +0000702 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); I != E; ++I)
Chris Lattner7391dde2004-11-16 17:12:38 +0000703 GlobalMap.erase(I);
Reid Spencer361e5132004-11-12 20:37:43 +0000704
705 return false;
706}
707
708
709// LinkFunctionBodies - Link in the function bodies that are defined in the
710// source module into the DestModule. This consists basically of copying the
711// function over and fixing up references to values.
Chris Lattner2f0557d2004-11-16 07:31:51 +0000712static bool LinkFunctionBodies(Module *Dest, Module *Src,
Reid Spencer361e5132004-11-12 20:37:43 +0000713 std::map<const Value*, Value*> &ValueMap,
714 std::string *Err) {
715
716 // Loop over all of the functions in the src module, mapping them over as we
717 // go
Chris Lattner2f0557d2004-11-16 07:31:51 +0000718 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer361e5132004-11-12 20:37:43 +0000719 if (!SF->isExternal()) { // No body if function is external
720 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
721
722 // DF not external SF external?
723 if (DF->isExternal()) {
724 // Only provide the function body if there isn't one already.
725 if (LinkFunctionBody(DF, SF, ValueMap, Err))
726 return true;
727 }
728 }
729 }
730 return false;
731}
732
733// LinkAppendingVars - If there were any appending global variables, link them
734// together now. Return true on error.
Reid Spencer361e5132004-11-12 20:37:43 +0000735static bool LinkAppendingVars(Module *M,
736 std::multimap<std::string, GlobalVariable *> &AppendingVars,
737 std::string *ErrorMsg) {
738 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukman10468d82005-04-21 22:55:34 +0000739
Reid Spencer361e5132004-11-12 20:37:43 +0000740 // Loop over the multimap of appending vars, processing any variables with the
741 // same name, forming a new appending global variable with both of the
742 // initializers merged together, then rewrite references to the old variables
743 // and delete them.
Reid Spencer361e5132004-11-12 20:37:43 +0000744 std::vector<Constant*> Inits;
745 while (AppendingVars.size() > 1) {
746 // Get the first two elements in the map...
747 std::multimap<std::string,
748 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
749
750 // If the first two elements are for different names, there is no pair...
751 // Otherwise there is a pair, so link them together...
752 if (First->first == Second->first) {
753 GlobalVariable *G1 = First->second, *G2 = Second->second;
754 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
755 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukman10468d82005-04-21 22:55:34 +0000756
Reid Spencer361e5132004-11-12 20:37:43 +0000757 // Check to see that they two arrays agree on type...
758 if (T1->getElementType() != T2->getElementType())
759 return Error(ErrorMsg,
760 "Appending variables with different element types need to be linked!");
761 if (G1->isConstant() != G2->isConstant())
762 return Error(ErrorMsg,
763 "Appending variables linked with different const'ness!");
764
765 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
766 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
767
Chris Lattnerd490d4f2005-12-06 17:30:58 +0000768 G1->setName(""); // Clear G1's name in case of a conflict!
769
Reid Spencer361e5132004-11-12 20:37:43 +0000770 // Create the new global variable...
771 GlobalVariable *NG =
772 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
773 /*init*/0, First->first, M);
774
775 // Merge the initializer...
776 Inits.reserve(NewSize);
777 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
778 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
779 Inits.push_back(I->getOperand(i));
780 } else {
781 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
782 Constant *CV = Constant::getNullValue(T1->getElementType());
783 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
784 Inits.push_back(CV);
785 }
786 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
787 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
788 Inits.push_back(I->getOperand(i));
789 } else {
790 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
791 Constant *CV = Constant::getNullValue(T2->getElementType());
792 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
793 Inits.push_back(CV);
794 }
795 NG->setInitializer(ConstantArray::get(NewType, Inits));
796 Inits.clear();
797
798 // Replace any uses of the two global variables with uses of the new
799 // global...
800
801 // FIXME: This should rewrite simple/straight-forward uses such as
802 // getelementptr instructions to not use the Cast!
803 G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
804 G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
805
806 // Remove the two globals from the module now...
807 M->getGlobalList().erase(G1);
808 M->getGlobalList().erase(G2);
809
810 // Put the new global into the AppendingVars map so that we can handle
811 // linking of more than two vars...
812 Second->second = NG;
813 }
814 AppendingVars.erase(First);
815 }
816
817 return false;
818}
819
820
821// LinkModules - This function links two modules together, with the resulting
822// left module modified to be the composite of the two input modules. If an
823// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
824// the problem. Upon failure, the Dest module could be in a modified state, and
825// shouldn't be relied on to be consistent.
Misha Brukman10468d82005-04-21 22:55:34 +0000826bool
Reid Spencerc4e31532004-12-13 03:00:16 +0000827Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer361e5132004-11-12 20:37:43 +0000828 assert(Dest != 0 && "Invalid Destination module");
829 assert(Src != 0 && "Invalid Source Module");
830
831 if (Dest->getEndianness() == Module::AnyEndianness)
832 Dest->setEndianness(Src->getEndianness());
833 if (Dest->getPointerSize() == Module::AnyPointerSize)
834 Dest->setPointerSize(Src->getPointerSize());
Chris Lattnerb7f59162004-12-10 20:26:15 +0000835 if (Dest->getTargetTriple().empty())
836 Dest->setTargetTriple(Src->getTargetTriple());
Reid Spencer361e5132004-11-12 20:37:43 +0000837
838 if (Src->getEndianness() != Module::AnyEndianness &&
839 Dest->getEndianness() != Src->getEndianness())
840 std::cerr << "WARNING: Linking two modules of different endianness!\n";
841 if (Src->getPointerSize() != Module::AnyPointerSize &&
842 Dest->getPointerSize() != Src->getPointerSize())
843 std::cerr << "WARNING: Linking two modules of different pointer size!\n";
Chris Lattnerb7f59162004-12-10 20:26:15 +0000844 if (!Src->getTargetTriple().empty() &&
845 Dest->getTargetTriple() != Src->getTargetTriple())
846 std::cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukman10468d82005-04-21 22:55:34 +0000847
Chris Lattner8ebd2162006-01-24 04:14:29 +0000848 if (!Src->getModuleInlineAsm().empty()) {
849 if (Dest->getModuleInlineAsm().empty())
850 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000851 else
Chris Lattner8ebd2162006-01-24 04:14:29 +0000852 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
853 Src->getModuleInlineAsm());
Chris Lattnerdd2d3fa2006-01-23 23:08:37 +0000854 }
855
Reid Spencer2c4f9a42004-11-25 09:29:44 +0000856 // Update the destination module's dependent libraries list with the libraries
Reid Spencer361e5132004-11-12 20:37:43 +0000857 // from the source module. There's no opportunity for duplicates here as the
858 // Module ensures that duplicate insertions are discarded.
859 Module::lib_iterator SI = Src->lib_begin();
860 Module::lib_iterator SE = Src->lib_end();
861 while ( SI != SE ) {
862 Dest->addLibrary(*SI);
863 ++SI;
864 }
865
866 // LinkTypes - Go through the symbol table of the Src module and see if any
867 // types are named in the src module that are not named in the Dst module.
868 // Make sure there are no type name conflicts.
Reid Spencer361e5132004-11-12 20:37:43 +0000869 if (LinkTypes(Dest, Src, ErrorMsg)) return true;
870
871 // ValueMap - Mapping of values from what they used to be in Src, to what they
872 // are now in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000873 std::map<const Value*, Value*> ValueMap;
874
875 // 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.
Reid Spencer361e5132004-11-12 20:37:43 +0000878 std::multimap<std::string, GlobalVariable *> AppendingVars;
879
880 // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
881 // linking by separating globals by type. Until PR411 is fixed, we replicate
882 // it's functionality here.
883 std::map<std::string, GlobalValue*> GlobalsByName;
884
Chris Lattner531f9e92005-03-15 04:54:21 +0000885 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end(); I != E; ++I) {
Reid Spencer361e5132004-11-12 20:37:43 +0000886 // Add all of the appending globals already in the Dest module to
887 // AppendingVars.
888 if (I->hasAppendingLinkage())
889 AppendingVars.insert(std::make_pair(I->getName(), I));
890
891 // Keep track of all globals by name.
892 if (!I->hasInternalLinkage() && I->hasName())
893 GlobalsByName[I->getName()] = I;
894 }
895
896 // Keep track of all globals by name.
897 for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
898 if (!I->hasInternalLinkage() && I->hasName())
899 GlobalsByName[I->getName()] = I;
900
901 // Insert all of the globals in src into the Dest module... without linking
902 // initializers (which could refer to functions not yet mapped over).
Reid Spencer361e5132004-11-12 20:37:43 +0000903 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
904 return true;
905
906 // Link the functions together between the two modules, without doing function
907 // bodies... this just adds external function prototypes to the Dest
908 // function... We do this so that when we begin processing function bodies,
909 // all of the global values that may be referenced are available in our
910 // ValueMap.
Reid Spencer361e5132004-11-12 20:37:43 +0000911 if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
912 return true;
913
914 // Update the initializers in the Dest module now that all globals that may
915 // be referenced are in Dest.
Reid Spencer361e5132004-11-12 20:37:43 +0000916 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
917
918 // Link in the function bodies that are defined in the source module into the
919 // DestModule. This consists basically of copying the function over and
920 // fixing up references to values.
Reid Spencer361e5132004-11-12 20:37:43 +0000921 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
922
923 // If there were any appending global variables, link them together now.
Reid Spencer361e5132004-11-12 20:37:43 +0000924 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
925
926 // If the source library's module id is in the dependent library list of the
927 // destination library, remove it since that module is now linked in.
928 sys::Path modId;
Reid Spencerc9c04732005-07-07 23:21:43 +0000929 modId.set(Src->getModuleIdentifier());
Reid Spencer361e5132004-11-12 20:37:43 +0000930 if (!modId.isEmpty())
931 Dest->removeLibrary(modId.getBasename());
932
933 return false;
934}
935
936// vim: sw=2