blob: 5979dc6fbc6f3a578829b0a4e44fc775649af041 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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
19#include "llvm/Linker.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/Instructions.h"
26#include "llvm/Assembly/Writer.h"
27#include "llvm/Support/Streams.h"
28#include "llvm/System/Path.h"
Chris Lattner0b228bf2008-06-16 21:00:18 +000029#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include <sstream>
31using namespace llvm;
32
33// Error - Simple wrapper function to conditionally assign to E and return true.
34// This just makes error return conditions a little bit simpler...
35static inline bool Error(std::string *E, const std::string &Message) {
36 if (E) *E = Message;
37 return true;
38}
39
40// ToStr - Simple wrapper function to convert a type to a string.
41static std::string ToStr(const Type *Ty, const Module *M) {
42 std::ostringstream OS;
43 WriteTypeSymbolic(OS, Ty, M);
44 return OS.str();
45}
46
47//
48// Function: ResolveTypes()
49//
50// Description:
51// Attempt to link the two specified types together.
52//
53// Inputs:
54// DestTy - The type to which we wish to resolve.
55// SrcTy - The original type which we want to resolve.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056//
57// Outputs:
58// DestST - The symbol table in which the new type should be placed.
59//
60// Return value:
61// true - There is an error and the types cannot yet be linked.
62// false - No errors.
63//
Chris Lattner06638ab2008-06-16 18:19:05 +000064static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattner06638ab2008-06-16 18:19:05 +000066 assert(DestTy && SrcTy && "Can't handle null types");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067
Chris Lattner06638ab2008-06-16 18:19:05 +000068 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
69 // Type _is_ in module, just opaque...
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
71 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
72 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
73 } else {
74 return true; // Cannot link types... not-equal and neither is opaque.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 }
76 return false;
77}
78
Chris Lattner0b228bf2008-06-16 21:00:18 +000079/// LinkerTypeMap - This implements a map of types that is stable
80/// even if types are resolved/refined to other types. This is not a general
81/// purpose map, it is specific to the linker's use.
82namespace {
83class LinkerTypeMap : public AbstractTypeUser {
84 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
85 TheMapTy TheMap;
Chris Lattner0b228bf2008-06-16 21:00:18 +000086
Chris Lattnera9326492008-06-16 23:06:51 +000087 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
88 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
89public:
90 LinkerTypeMap() {}
91 ~LinkerTypeMap() {
Chris Lattner0b228bf2008-06-16 21:00:18 +000092 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
93 E = TheMap.end(); I != E; ++I)
94 I->first->removeAbstractTypeUser(this);
95 }
96
97 /// lookup - Return the value for the specified type or null if it doesn't
98 /// exist.
99 const Type *lookup(const Type *Ty) const {
100 TheMapTy::const_iterator I = TheMap.find(Ty);
101 if (I != TheMap.end()) return I->second;
102 return 0;
103 }
104
105 /// erase - Remove the specified type, returning true if it was in the set.
106 bool erase(const Type *Ty) {
107 if (!TheMap.erase(Ty))
108 return false;
109 if (Ty->isAbstract())
110 Ty->removeAbstractTypeUser(this);
111 return true;
112 }
113
114 /// insert - This returns true if the pointer was new to the set, false if it
115 /// was already in the set.
116 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman55d19662008-07-07 17:46:23 +0000117 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner0b228bf2008-06-16 21:00:18 +0000118 return false; // Already in map.
119 if (Src->isAbstract())
120 Src->addAbstractTypeUser(this);
121 return true;
122 }
123
124protected:
125 /// refineAbstractType - The callback method invoked when an abstract type is
126 /// resolved to another type. An object must override this method to update
127 /// its internal state to reference NewType instead of OldType.
128 ///
129 virtual void refineAbstractType(const DerivedType *OldTy,
130 const Type *NewTy) {
131 TheMapTy::iterator I = TheMap.find(OldTy);
132 const Type *DstTy = I->second;
133
134 TheMap.erase(I);
135 if (OldTy->isAbstract())
136 OldTy->removeAbstractTypeUser(this);
137
138 // Don't reinsert into the map if the key is concrete now.
139 if (NewTy->isAbstract())
140 insert(NewTy, DstTy);
141 }
142
143 /// The other case which AbstractTypeUsers must be aware of is when a type
144 /// makes the transition from being abstract (where it has clients on it's
145 /// AbstractTypeUsers list) to concrete (where it does not). This method
146 /// notifies ATU's when this occurs for a type.
147 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
148 TheMap.erase(AbsTy);
149 AbsTy->removeAbstractTypeUser(this);
150 }
151
152 // for debugging...
153 virtual void dump() const {
154 cerr << "AbstractTypeSet!\n";
155 }
156};
157}
158
159
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160// RecursiveResolveTypes - This is just like ResolveTypes, except that it
161// recurses down into derived types, merging the used types if the parent types
162// are compatible.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000163static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner0b228bf2008-06-16 21:00:18 +0000164 LinkerTypeMap &Pointers) {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000165 if (DstTy == SrcTy) return false; // If already equal, noop
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
167 // If we found our opaque type, resolve it now!
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000168 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
169 return ResolveTypes(DstTy, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 // Two types cannot be resolved together if they are of different primitive
172 // type. For example, we cannot resolve an int to a float.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000173 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
Chris Lattnere174d322008-06-16 20:03:01 +0000175 // If neither type is abstract, then they really are just different types.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000176 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattnere174d322008-06-16 20:03:01 +0000177 return true;
178
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000180 switch (DstTy->getTypeID()) {
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000181 default:
182 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 case Type::FunctionTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000184 const FunctionType *DstFT = cast<FunctionType>(DstTy);
185 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000186 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
187 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000189
190 // Use TypeHolder's so recursive resolution won't break us.
191 PATypeHolder ST(SrcFT), DT(DstFT);
192 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
193 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
194 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000196 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 return false;
198 }
199 case Type::StructTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000200 const StructType *DstST = cast<StructType>(DstTy);
201 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000202 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000203 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000204
205 PATypeHolder ST(SrcST), DT(DstST);
206 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
207 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
208 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000210 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 return false;
212 }
213 case Type::ArrayTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000214 const ArrayType *DAT = cast<ArrayType>(DstTy);
215 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 if (DAT->getNumElements() != SAT->getNumElements()) return true;
217 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000218 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 }
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000220 case Type::VectorTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000221 const VectorType *DVT = cast<VectorType>(DstTy);
222 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000223 if (DVT->getNumElements() != SVT->getNumElements()) return true;
224 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
225 Pointers);
226 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 case Type::PointerTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000228 const PointerType *DstPT = cast<PointerType>(DstTy);
229 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000230
231 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
232 return true;
233
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 // If this is a pointer type, check to see if we have already seen it. If
235 // so, we are in a recursive branch. Cut off the search now. We cannot use
236 // an associative container for this search, because the type pointers (keys
Chris Lattner0b228bf2008-06-16 21:00:18 +0000237 // in the container) change whenever types get resolved.
238 if (SrcPT->isAbstract())
239 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
240 return ExistingDestTy != DstPT;
241
242 if (DstPT->isAbstract())
243 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
244 return ExistingSrcTy != SrcPT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 // Otherwise, add the current pointers to the vector to stop recursion on
246 // this pair.
Chris Lattner0b228bf2008-06-16 21:00:18 +0000247 if (DstPT->isAbstract())
248 Pointers.insert(DstPT, SrcPT);
249 if (SrcPT->isAbstract())
250 Pointers.insert(SrcPT, DstPT);
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000251
Chris Lattner41fed262008-06-16 19:55:40 +0000252 return RecursiveResolveTypesI(DstPT->getElementType(),
253 SrcPT->getElementType(), Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 }
256}
257
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000258static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner0b228bf2008-06-16 21:00:18 +0000259 LinkerTypeMap PointerTypes;
Chris Lattner06638ab2008-06-16 18:19:05 +0000260 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261}
262
263
264// LinkTypes - Go through the symbol table of the Src module and see if any
265// types are named in the src module that are not named in the Dst module.
266// Make sure there are no type name conflicts.
267static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
268 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
269 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
270
271 // Look for a type plane for Type's...
272 TypeSymbolTable::const_iterator TI = SrcST->begin();
273 TypeSymbolTable::const_iterator TE = SrcST->end();
274 if (TI == TE) return false; // No named types, do nothing.
275
276 // Some types cannot be resolved immediately because they depend on other
277 // types being resolved to each other first. This contains a list of types we
278 // are waiting to recheck.
279 std::vector<std::string> DelayedTypesToResolve;
280
281 for ( ; TI != TE; ++TI ) {
282 const std::string &Name = TI->first;
283 const Type *RHS = TI->second;
284
Chris Lattner06638ab2008-06-16 18:19:05 +0000285 // Check to see if this type name is already in the dest module.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 Type *Entry = DestST->lookup(Name);
287
Chris Lattner06638ab2008-06-16 18:19:05 +0000288 // If the name is just in the source module, bring it over to the dest.
289 if (Entry == 0) {
290 if (!Name.empty())
291 DestST->insert(Name, const_cast<Type*>(RHS));
292 } else if (ResolveTypes(Entry, RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 // They look different, save the types 'till later to resolve.
294 DelayedTypesToResolve.push_back(Name);
295 }
296 }
297
298 // Iteratively resolve types while we can...
299 while (!DelayedTypesToResolve.empty()) {
300 // Loop over all of the types, attempting to resolve them if possible...
301 unsigned OldSize = DelayedTypesToResolve.size();
302
303 // Try direct resolution by name...
304 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
305 const std::string &Name = DelayedTypesToResolve[i];
306 Type *T1 = SrcST->lookup(Name);
307 Type *T2 = DestST->lookup(Name);
Chris Lattner06638ab2008-06-16 18:19:05 +0000308 if (!ResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 // We are making progress!
310 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
311 --i;
312 }
313 }
314
315 // Did we not eliminate any types?
316 if (DelayedTypesToResolve.size() == OldSize) {
317 // Attempt to resolve subelements of types. This allows us to merge these
318 // two types: { int* } and { opaque* }
319 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
320 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000321 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 // We are making progress!
323 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
324
325 // Go back to the main loop, perhaps we can resolve directly by name
326 // now...
327 break;
328 }
329 }
330
331 // If we STILL cannot resolve the types, then there is something wrong.
332 if (DelayedTypesToResolve.size() == OldSize) {
333 // Remove the symbol name from the destination.
334 DelayedTypesToResolve.pop_back();
335 }
336 }
337 }
338
339
340 return false;
341}
342
Chris Lattnercb13a012008-07-14 05:52:33 +0000343#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344static void PrintMap(const std::map<const Value*, Value*> &M) {
345 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
346 I != E; ++I) {
347 cerr << " Fr: " << (void*)I->first << " ";
348 I->first->dump();
349 cerr << " To: " << (void*)I->second << " ";
350 I->second->dump();
351 cerr << "\n";
352 }
353}
Chris Lattnercb13a012008-07-14 05:52:33 +0000354#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355
356
357// RemapOperand - Use ValueMap to convert constants from one module to another.
358static Value *RemapOperand(const Value *In,
359 std::map<const Value*, Value*> &ValueMap) {
360 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
361 if (I != ValueMap.end())
362 return I->second;
363
364 // Check to see if it's a constant that we are interested in transforming.
365 Value *Result = 0;
366 if (const Constant *CPV = dyn_cast<Constant>(In)) {
367 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
368 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
369 return const_cast<Constant*>(CPV); // Simple constants stay identical.
370
371 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
372 std::vector<Constant*> Operands(CPA->getNumOperands());
373 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
374 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
375 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
376 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
377 std::vector<Constant*> Operands(CPS->getNumOperands());
378 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
379 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
380 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
381 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
382 Result = const_cast<Constant*>(CPV);
383 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
384 std::vector<Constant*> Operands(CP->getNumOperands());
385 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
386 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
387 Result = ConstantVector::get(Operands);
388 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
389 std::vector<Constant*> Ops;
390 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
391 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
392 Result = CE->getWithOperands(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 } else {
Chris Lattnercb13a012008-07-14 05:52:33 +0000394 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 assert(0 && "Unknown type of derived type constant value!");
396 }
397 } else if (isa<InlineAsm>(In)) {
398 Result = const_cast<Value*>(In);
399 }
400
401 // Cache the mapping in our local map structure
402 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000403 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 return Result;
405 }
406
Chris Lattnercb13a012008-07-14 05:52:33 +0000407#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 cerr << "LinkModules ValueMap: \n";
409 PrintMap(ValueMap);
410
411 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
412 assert(0 && "Couldn't remap value!");
Chris Lattnercb13a012008-07-14 05:52:33 +0000413#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return 0;
415}
416
417/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
418/// in the symbol table. This is good for all clients except for us. Go
419/// through the trouble to force this back.
420static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
421 assert(GV->getName() != Name && "Can't force rename to self");
422 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
423
424 // If there is a conflict, rename the conflict.
425 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
426 assert(ConflictGV->hasInternalLinkage() &&
427 "Not conflicting with a static global, should link instead!");
428 GV->takeName(ConflictGV);
429 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
430 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
431 } else {
432 GV->setName(Name); // Force the name back
433 }
434}
435
436/// CopyGVAttributes - copy additional attributes (those not needed to construct
437/// a GlobalValue) from the SrcGV to the DestGV.
438static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000439 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
440 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
441 DestGV->copyAttributesFrom(SrcGV);
442 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443}
444
445/// GetLinkageResult - This analyzes the two global values and determines what
446/// the result will look like in the destination module. In particular, it
447/// computes the resultant linkage type, computes whether the global in the
448/// source should be copied over to the destination (replacing the existing
449/// one), and computes whether this linkage is an error or not. It also performs
450/// visibility checks: we cannot link together two symbols with different
451/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000452static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
454 std::string *Err) {
455 assert((!Dest || !Src->hasInternalLinkage()) &&
456 "If Src has internal linkage, Dest shouldn't be set!");
457 if (!Dest) {
458 // Linking something to nothing.
459 LinkFromSrc = true;
460 LT = Src->getLinkage();
461 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000462 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 // external globals, we aren't adding anything.
464 if (Src->hasDLLImportLinkage()) {
465 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
466 if (Dest->isDeclaration()) {
467 LinkFromSrc = true;
468 LT = Src->getLinkage();
469 }
470 } else if (Dest->hasExternalWeakLinkage()) {
471 //If the Dest is weak, use the source linkage
472 LinkFromSrc = true;
473 LT = Src->getLinkage();
474 } else {
475 LinkFromSrc = false;
476 LT = Dest->getLinkage();
477 }
478 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
479 // If Dest is external but Src is not:
480 LinkFromSrc = true;
481 LT = Src->getLinkage();
482 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
483 if (Src->getLinkage() != Dest->getLinkage())
484 return Error(Err, "Linking globals named '" + Src->getName() +
485 "': can only link appending global with another appending global!");
486 LinkFromSrc = true; // Special cased.
487 LT = Src->getLinkage();
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000488 } else if (Src->isWeakForLinker()) {
Dale Johannesen49c44122008-05-14 20:12:51 +0000489 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
490 // or DLL* linkage.
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000491 if ((Dest->hasLinkOnceLinkage() &&
Dale Johannesen49c44122008-05-14 20:12:51 +0000492 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 Dest->hasExternalWeakLinkage()) {
494 LinkFromSrc = true;
495 LT = Src->getLinkage();
496 } else {
497 LinkFromSrc = false;
498 LT = Dest->getLinkage();
499 }
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000500 } else if (Dest->isWeakForLinker()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 // At this point we know that Src has External* or DLL* linkage.
502 if (Src->hasExternalWeakLinkage()) {
503 LinkFromSrc = false;
504 LT = Dest->getLinkage();
505 } else {
506 LinkFromSrc = true;
507 LT = GlobalValue::ExternalLinkage;
508 }
509 } else {
510 assert((Dest->hasExternalLinkage() ||
511 Dest->hasDLLImportLinkage() ||
512 Dest->hasDLLExportLinkage() ||
513 Dest->hasExternalWeakLinkage()) &&
514 (Src->hasExternalLinkage() ||
515 Src->hasDLLImportLinkage() ||
516 Src->hasDLLExportLinkage() ||
517 Src->hasExternalWeakLinkage()) &&
518 "Unexpected linkage type!");
519 return Error(Err, "Linking globals named '" + Src->getName() +
520 "': symbol multiply defined!");
521 }
522
523 // Check visibility
524 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000525 if (!Src->isDeclaration() && !Dest->isDeclaration())
526 return Error(Err, "Linking globals named '" + Src->getName() +
527 "': symbols have different visibilities!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 return false;
529}
530
531// LinkGlobals - Loop through the global variables in the src module and merge
532// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000533static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 std::map<const Value*, Value*> &ValueMap,
535 std::multimap<std::string, GlobalVariable *> &AppendingVars,
536 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000537 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
538
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnercb13a012008-07-14 05:52:33 +0000540 for (Module::const_global_iterator I = Src->global_begin(),
541 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000542 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000543 GlobalValue *DGV = 0;
544
Chris Lattner0763d412008-07-14 06:49:45 +0000545 // Check to see if may have to link the global with the global, alias or
546 // function.
547 if (SGV->hasName() && !SGV->hasInternalLinkage())
548 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
549 SGV->getNameEnd()));
550
551 // If types don't agree due to opaque types, try to resolve them.
552 if (DGV && DGV->getType() != SGV->getType())
553 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000554
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 if (DGV && DGV->hasInternalLinkage())
556 DGV = 0;
557
Dan Gohman930191f2007-10-08 15:13:30 +0000558 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
559 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000560 "Global must either be external or have an initializer!");
561
562 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
563 bool LinkFromSrc = false;
564 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
565 return true;
566
567 if (!DGV) {
568 // No linking to be performed, simply create an identical version of the
569 // symbol over in the dest module... the initializer will be filled in
Chris Lattner0763d412008-07-14 06:49:45 +0000570 // later by LinkGlobalInits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 GlobalVariable *NewDGV =
572 new GlobalVariable(SGV->getType()->getElementType(),
573 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000574 SGV->getName(), Dest, false,
575 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000576 // Propagate alignment, visibility and section info.
577 CopyGVAttributes(NewDGV, SGV);
578
579 // If the LLVM runtime renamed the global, but it is an externally visible
580 // symbol, DGV must be an existing global with internal linkage. Rename
581 // it.
582 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
583 ForceRenaming(NewDGV, SGV->getName());
584
585 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000586 ValueMap[SGV] = NewDGV;
587
Chris Lattner0763d412008-07-14 06:49:45 +0000588 // Keep track that this is an appending variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 if (SGV->hasAppendingLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
591 } else if (DGV->hasAppendingLinkage()) {
592 // No linking is performed yet. Just insert a new copy of the global, and
593 // keep track of the fact that it is an appending variable in the
594 // AppendingVars map. The name is cleared out so that no linkage is
595 // performed.
596 GlobalVariable *NewDGV =
597 new GlobalVariable(SGV->getType()->getElementType(),
598 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000599 "", Dest, false,
600 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000602 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000604 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 CopyGVAttributes(NewDGV, SGV);
606
607 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000608 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609
610 // Keep track that this is an appending variable...
611 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000612 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
613 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
614 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000615 // linkage calculation was correct.
Chris Lattner0763d412008-07-14 06:49:45 +0000616 if (!SGV->isDeclaration() || LinkFromSrc)
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000617 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
618 "': symbol multiple defined");
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000619
Chris Lattner0763d412008-07-14 06:49:45 +0000620 // Make sure to remember this mapping.
621 ValueMap[SGV] = DGA;
622 } else if (LinkFromSrc) {
623 // If the types don't match, and if we are to link from the source, nuke
624 // DGV and create a new one of the appropriate type. Note that the thing
625 // we are replacing may be a function (if a prototype, weak, etc) or a
626 // global variable.
627 GlobalVariable *NewDGV =
628 new GlobalVariable(SGV->getType()->getElementType(),
629 SGV->isConstant(), SGV->getLinkage(),
630 /*init*/0, DGV->getName(), Dest, false,
631 SGV->getType()->getAddressSpace());
632
633 // Propagate alignment, section, and visibility info.
634 CopyGVAttributes(NewDGV, SGV);
635 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
636
637 // DGV will conflict with NewDGV because they both had the same
638 // name. We must erase this now so ForceRenaming doesn't assert
639 // because DGV might not have internal linkage.
640 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
641 Var->eraseFromParent();
642 else
643 cast<Function>(DGV)->eraseFromParent();
644 DGV = NewDGV;
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000645
Chris Lattner0763d412008-07-14 06:49:45 +0000646 // If the symbol table renamed the global, but it is an externally visible
647 // symbol, DGV must be an existing global with internal linkage. Rename.
648 if (NewDGV->getValueName() != SGV->getValueName() &&
649 !NewDGV->hasInternalLinkage())
650 ForceRenaming(NewDGV, SGV->getName());
651
652 // Inherit const as appropriate
653 NewDGV->setConstant(SGV->isConstant());
654
655 // Set calculated linkage
656 NewDGV->setLinkage(NewLinkage);
657
658 // Make sure to remember this mapping...
659 ValueMap[SGV] = ConstantExpr::getBitCast(NewDGV, SGV->getType());
660 } else {
661 // Not "link from source", keep the one in the DestModule and remap the
662 // input onto it.
663
664 // Special case for const propagation.
665 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000666 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
667 DGVar->setConstant(true);
Chris Lattner0763d412008-07-14 06:49:45 +0000668
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000669 // Set calculated linkage
Chris Lattner0763d412008-07-14 06:49:45 +0000670 DGV->setLinkage(NewLinkage);
671
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000672 // Make sure to remember this mapping...
Chris Lattner0763d412008-07-14 06:49:45 +0000673 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 }
675 }
676 return false;
677}
678
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000679static GlobalValue::LinkageTypes
680CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
681 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
682 return GlobalValue::ExternalLinkage;
683 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
684 return GlobalValue::WeakLinkage;
685 else {
686 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
687 "Unexpected linkage type");
688 return GlobalValue::InternalLinkage;
689 }
690}
691
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000693// dest module. We're assuming, that all functions/global variables were already
694// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000695static bool LinkAlias(Module *Dest, const Module *Src,
696 std::map<const Value*, Value*> &ValueMap,
697 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 // Loop over all alias in the src module
699 for (Module::const_alias_iterator I = Src->alias_begin(),
700 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000701 const GlobalAlias *SGA = I;
702 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
703 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000705 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000706 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000707 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
708 assert(VMI != ValueMap.end() && "Aliasee not linked");
709 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000710 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000712 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000713 if (!DGV && !SGA->hasInternalLinkage()) {
714 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000715
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000716 // If types don't agree due to opaque types, try to resolve them.
717 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000718 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000719 }
720
721 if (!DGV && !SGA->hasInternalLinkage()) {
722 DGV = Dest->getGlobalVariable(SGA->getName());
723
724 // If types don't agree due to opaque types, try to resolve them.
725 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000726 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000727 }
728
729 if (!DGV && !SGA->hasInternalLinkage()) {
730 DGV = Dest->getFunction(SGA->getName());
731
732 // If types don't agree due to opaque types, try to resolve them.
733 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000734 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000735 }
736
737 // No linking to be performed on internal stuff.
738 if (DGV && DGV->hasInternalLinkage())
739 DGV = NULL;
740
741 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
742 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000743 // globals are already linked we just need query ValueMap to find the
744 // mapping.
745 if (DAliasee == DGA->getAliasedGlobal()) {
746 // This is just two copies of the same alias. Propagate linkage, if
747 // necessary.
748 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
749
750 NewGA = DGA;
751 // Proceed to 'common' steps
752 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000753 return Error(Err, "Alias Collision on '" + SGA->getName()+
754 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000755 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000756 // The only allowed way is to link alias with external declaration or weak
757 // symbol..
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000758 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000759 // But only if aliasee is global too...
760 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000761 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
762 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000763
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000764 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
765 SGA->getName(), DAliasee, Dest);
766 CopyGVAttributes(NewGA, SGA);
767
768 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000769 if (SGA->getType() != DGVar->getType())
770 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
771 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000772 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000773 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000774
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000775 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000776 // name. We must erase this now so ForceRenaming doesn't assert
777 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000778 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000779
780 // Proceed to 'common' steps
781 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000782 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
783 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000784 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000785 // The only allowed way is to link alias with external declaration or weak
786 // symbol...
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000787 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000788 // But only if aliasee is function too...
789 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000790 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
791 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000792
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000793 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
794 SGA->getName(), DAliasee, Dest);
795 CopyGVAttributes(NewGA, SGA);
796
797 // Any uses of DF need to change to NewGA, with cast, if needed.
798 if (SGA->getType() != DF->getType())
799 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
800 DF->getType()));
801 else
802 DF->replaceAllUsesWith(NewGA);
803
804 // DF will conflict with NewGA because they both had the same
805 // name. We must erase this now so ForceRenaming doesn't assert
806 // because DF might not have internal linkage.
807 DF->eraseFromParent();
808
809 // Proceed to 'common' steps
810 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000811 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
812 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000813 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000814 // No linking to be performed, simply create an identical version of the
815 // alias over in the dest module...
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000816
817 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
818 SGA->getName(), DAliasee, Dest);
819 CopyGVAttributes(NewGA, SGA);
820
821 // Proceed to 'common' steps
822 }
823
824 assert(NewGA && "No alias was created in destination module!");
825
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000826 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000827 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000828 if (NewGA->getName() != SGA->getName() &&
829 !NewGA->hasInternalLinkage())
830 ForceRenaming(NewGA, SGA->getName());
831
832 // Remember this mapping so uses in the source module get remapped
833 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000834 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000836
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 return false;
838}
839
840
841// LinkGlobalInits - Update the initializers in the Dest module now that all
842// globals that may be referenced are in Dest.
843static bool LinkGlobalInits(Module *Dest, const Module *Src,
844 std::map<const Value*, Value*> &ValueMap,
845 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 // Loop over all of the globals in the src module, mapping them over as we go
847 for (Module::const_global_iterator I = Src->global_begin(),
848 E = Src->global_end(); I != E; ++I) {
849 const GlobalVariable *SGV = I;
850
851 if (SGV->hasInitializer()) { // Only process initialized GV's
852 // Figure out what the initializer looks like in the dest module...
853 Constant *SInit =
854 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
855
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +0000856 GlobalVariable *DGV =
857 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 if (DGV->hasInitializer()) {
859 if (SGV->hasExternalLinkage()) {
860 if (DGV->getInitializer() != SInit)
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000861 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
862 "': global variables have different initializers");
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000863 } else if (DGV->isWeakForLinker()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 // Nothing is required, mapped values will take the new global
865 // automatically.
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000866 } else if (SGV->isWeakForLinker()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 // Nothing is required, mapped values will take the new global
868 // automatically.
869 } else if (DGV->hasAppendingLinkage()) {
870 assert(0 && "Appending linkage unimplemented!");
871 } else {
872 assert(0 && "Unknown linkage!");
873 }
874 } else {
875 // Copy the initializer over now...
876 DGV->setInitializer(SInit);
877 }
878 }
879 }
880 return false;
881}
882
883// LinkFunctionProtos - Link the functions together between the two modules,
884// without doing function bodies... this just adds external function prototypes
885// to the Dest function...
886//
887static bool LinkFunctionProtos(Module *Dest, const Module *Src,
888 std::map<const Value*, Value*> &ValueMap,
889 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000890 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
891
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 // Loop over all of the functions in the src module, mapping them over
893 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
894 const Function *SF = I; // SrcFunction
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000895 GlobalValue *DGV = 0;
Chris Lattnera518cc92008-06-20 05:29:39 +0000896 Value *MappedDF;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000897
Chris Lattner0763d412008-07-14 06:49:45 +0000898 // Check to see if may have to link the function with the global, alias or
899 // function.
900 if (SF->hasName() && !SF->hasInternalLinkage())
901 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
902 SF->getNameEnd()));
903
904 // If types don't agree due to opaque types, try to resolve them.
905 if (DGV && DGV->getType() != SF->getType())
906 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000907
908 if (DGV && DGV->hasInternalLinkage())
909 DGV = 0;
910
Chris Lattner1426bfa2008-06-09 07:36:11 +0000911 // If there is no linkage to be performed, just bring over SF without
912 // modifying it.
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000913 if (DGV == 0) {
Chris Lattner1426bfa2008-06-09 07:36:11 +0000914 // Function does not already exist, simply insert an function signature
915 // identical to SF into the dest module.
916 Function *NewDF = Function::Create(SF->getFunctionType(),
917 SF->getLinkage(),
918 SF->getName(), Dest);
919 CopyGVAttributes(NewDF, SF);
920
921 // If the LLVM runtime renamed the function, but it is an externally
922 // visible symbol, DF must be an existing function with internal linkage.
923 // Rename it.
924 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
925 ForceRenaming(NewDF, SF->getName());
926
927 // ... and remember this mapping...
928 ValueMap[SF] = NewDF;
929 continue;
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000930 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000931 // SF is function, but DF is alias.
932 // The only valid mappings are:
933 // - SF is external declaration, which is effectively a no-op.
934 // - SF is weak, when we just need to throw SF out.
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +0000935 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000936 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
937 "': symbol multiple defined");
938
939 // Make sure to remember this mapping...
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000940 ValueMap[SF] = ConstantExpr::getBitCast(DGA, SF->getType());
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000941 continue;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000942 }
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000943
944 Function* DF = cast<Function>(DGV);
Chris Lattner1426bfa2008-06-09 07:36:11 +0000945 // If types don't agree because of opaque, try to resolve them.
946 if (SF->getType() != DF->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000947 RecursiveResolveTypes(SF->getType(), DF->getType());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000948
949 // Check visibility, merging if a definition overrides a prototype.
950 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000951 // If one is a prototype, ignore its visibility. Prototypes are always
952 // overridden by the definition.
953 if (!SF->isDeclaration() && !DF->isDeclaration())
954 return Error(Err, "Linking functions named '" + SF->getName() +
955 "': symbols have different visibilities!");
Chris Lattnerf7e84192008-06-09 07:25:28 +0000956
957 // Otherwise, replace the visibility of DF if DF is a prototype.
958 if (DF->isDeclaration())
959 DF->setVisibility(SF->getVisibility());
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000960 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961
Chris Lattner1426bfa2008-06-09 07:36:11 +0000962 if (DF->getType() != SF->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 if (DF->isDeclaration() && !SF->isDeclaration()) {
964 // We have a definition of the same name but different type in the
965 // source module. Copy the prototype to the destination and replace
966 // uses of the destination's prototype with the new prototype.
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000967 Function *NewDF = Function::Create(SF->getFunctionType(),
968 SF->getLinkage(),
Gabor Greifd6da1d02008-04-06 20:25:17 +0000969 SF->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 CopyGVAttributes(NewDF, SF);
971
972 // Any uses of DF need to change to NewDF, with cast
973 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
974
975 // DF will conflict with NewDF because they both had the same. We must
976 // erase this now so ForceRenaming doesn't assert because DF might
977 // not have internal linkage.
978 DF->eraseFromParent();
979
980 // If the symbol table renamed the function, but it is an externally
981 // visible symbol, DF must be an existing function with internal
982 // linkage. Rename it.
983 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
984 ForceRenaming(NewDF, SF->getName());
985
986 // Remember this mapping so uses in the source module get remapped
987 // later by RemapOperand.
988 ValueMap[SF] = NewDF;
Chris Lattnera518cc92008-06-20 05:29:39 +0000989 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 } else {
Chris Lattnera518cc92008-06-20 05:29:39 +0000991 // We have two functions of the same name but different type. Any use
992 // of the source must be mapped to the destination, with a cast.
993 MappedDF = ConstantExpr::getBitCast(DF, SF->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 }
Chris Lattnera518cc92008-06-20 05:29:39 +0000995 } else {
996 MappedDF = DF;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000997 }
998
999 if (SF->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 // If SF is a declaration or if both SF & DF are declarations, just link
1001 // the declarations, we aren't adding anything.
1002 if (SF->hasDLLImportLinkage()) {
1003 if (DF->isDeclaration()) {
Chris Lattnera518cc92008-06-20 05:29:39 +00001004 ValueMap[SF] = MappedDF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001006 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 } else {
Chris Lattnera518cc92008-06-20 05:29:39 +00001008 ValueMap[SF] = MappedDF;
Chris Lattnerc082fd42008-06-09 07:47:34 +00001009 }
1010 continue;
1011 }
1012
1013 // If DF is external but SF is not, link the external functions, update
1014 // linkage qualifiers.
1015 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Chris Lattnera518cc92008-06-20 05:29:39 +00001016 ValueMap.insert(std::make_pair(SF, MappedDF));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001018 continue;
1019 }
1020
1021 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +00001022 if (SF->isWeakForLinker()) {
Chris Lattnera518cc92008-06-20 05:29:39 +00001023 ValueMap[SF] = MappedDF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024
1025 // Linkonce+Weak = Weak
1026 // *+External Weak = *
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +00001027 if ((DF->hasLinkOnceLinkage() &&
Dale Johannesen49c44122008-05-14 20:12:51 +00001028 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 DF->hasExternalWeakLinkage())
1030 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001031 continue;
1032 }
1033
Anton Korobeynikov46aa9c12008-07-05 23:48:30 +00001034 if (DF->isWeakForLinker()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035 // At this point we know that SF has LinkOnce or External* linkage.
Chris Lattnera518cc92008-06-20 05:29:39 +00001036 ValueMap[SF] = MappedDF;
Chris Lattnerc082fd42008-06-09 07:47:34 +00001037
1038 // If the source function has stronger linkage than the destination,
1039 // its body and linkage should override ours.
1040 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
1041 // Don't inherit linkonce & external weak linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +00001043 DF->deleteBody();
1044 }
1045 continue;
1046 }
1047
1048 if (SF->getLinkage() != DF->getLinkage())
1049 return Error(Err, "Functions named '" + SF->getName() +
1050 "' have different linkage specifiers!");
1051
1052 // The function is defined identically in both modules!
1053 if (SF->hasExternalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 return Error(Err, "Function '" +
1055 ToStr(SF->getFunctionType(), Src) + "':\"" +
1056 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc082fd42008-06-09 07:47:34 +00001057 assert(0 && "Unknown linkage configuration found!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059 return false;
1060}
1061
1062// LinkFunctionBody - Copy the source function over into the dest function and
1063// fix up references to values. At this point we know that Dest is an external
1064// function, and that Src is not.
1065static bool LinkFunctionBody(Function *Dest, Function *Src,
1066 std::map<const Value*, Value*> &ValueMap,
1067 std::string *Err) {
1068 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1069
1070 // Go through and convert function arguments over, remembering the mapping.
1071 Function::arg_iterator DI = Dest->arg_begin();
1072 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1073 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +00001074 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075
1076 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001077 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 }
1079
1080 // Splice the body of the source function into the dest function.
1081 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1082
1083 // At this point, all of the instructions and values of the function are now
1084 // copied over. The only problem is that they are still referencing values in
1085 // the Source function as operands. Loop through all of the operands of the
1086 // functions and patch them up to point to the local versions...
1087 //
1088 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1089 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1090 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1091 OI != OE; ++OI)
1092 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1093 *OI = RemapOperand(*OI, ValueMap);
1094
1095 // There is no need to map the arguments anymore.
1096 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1097 I != E; ++I)
1098 ValueMap.erase(I);
1099
1100 return false;
1101}
1102
1103
1104// LinkFunctionBodies - Link in the function bodies that are defined in the
1105// source module into the DestModule. This consists basically of copying the
1106// function over and fixing up references to values.
1107static bool LinkFunctionBodies(Module *Dest, Module *Src,
1108 std::map<const Value*, Value*> &ValueMap,
1109 std::string *Err) {
1110
1111 // Loop over all of the functions in the src module, mapping them over as we
1112 // go
1113 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1114 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnera518cc92008-06-20 05:29:39 +00001115 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
1117 // DF not external SF external?
Chris Lattnera518cc92008-06-20 05:29:39 +00001118 if (DF && DF->isDeclaration())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 // Only provide the function body if there isn't one already.
1120 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1121 return true;
1122 }
1123 }
1124 return false;
1125}
1126
1127// LinkAppendingVars - If there were any appending global variables, link them
1128// together now. Return true on error.
1129static bool LinkAppendingVars(Module *M,
1130 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1131 std::string *ErrorMsg) {
1132 if (AppendingVars.empty()) return false; // Nothing to do.
1133
1134 // Loop over the multimap of appending vars, processing any variables with the
1135 // same name, forming a new appending global variable with both of the
1136 // initializers merged together, then rewrite references to the old variables
1137 // and delete them.
1138 std::vector<Constant*> Inits;
1139 while (AppendingVars.size() > 1) {
1140 // Get the first two elements in the map...
1141 std::multimap<std::string,
1142 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1143
1144 // If the first two elements are for different names, there is no pair...
1145 // Otherwise there is a pair, so link them together...
1146 if (First->first == Second->first) {
1147 GlobalVariable *G1 = First->second, *G2 = Second->second;
1148 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1149 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1150
1151 // Check to see that they two arrays agree on type...
1152 if (T1->getElementType() != T2->getElementType())
1153 return Error(ErrorMsg,
1154 "Appending variables with different element types need to be linked!");
1155 if (G1->isConstant() != G2->isConstant())
1156 return Error(ErrorMsg,
1157 "Appending variables linked with different const'ness!");
1158
1159 if (G1->getAlignment() != G2->getAlignment())
1160 return Error(ErrorMsg,
1161 "Appending variables with different alignment need to be linked!");
1162
1163 if (G1->getVisibility() != G2->getVisibility())
1164 return Error(ErrorMsg,
1165 "Appending variables with different visibility need to be linked!");
1166
1167 if (G1->getSection() != G2->getSection())
1168 return Error(ErrorMsg,
1169 "Appending variables with different section name need to be linked!");
1170
1171 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1172 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1173
1174 G1->setName(""); // Clear G1's name in case of a conflict!
1175
1176 // Create the new global variable...
1177 GlobalVariable *NG =
1178 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
Chris Lattner29ae6c52008-06-27 03:10:24 +00001179 /*init*/0, First->first, M, G1->isThreadLocal(),
1180 G1->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181
1182 // Propagate alignment, visibility and section info.
1183 CopyGVAttributes(NG, G1);
1184
1185 // Merge the initializer...
1186 Inits.reserve(NewSize);
1187 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1188 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1189 Inits.push_back(I->getOperand(i));
1190 } else {
1191 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1192 Constant *CV = Constant::getNullValue(T1->getElementType());
1193 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1194 Inits.push_back(CV);
1195 }
1196 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1197 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1198 Inits.push_back(I->getOperand(i));
1199 } else {
1200 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1201 Constant *CV = Constant::getNullValue(T2->getElementType());
1202 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1203 Inits.push_back(CV);
1204 }
1205 NG->setInitializer(ConstantArray::get(NewType, Inits));
1206 Inits.clear();
1207
1208 // Replace any uses of the two global variables with uses of the new
1209 // global...
1210
1211 // FIXME: This should rewrite simple/straight-forward uses such as
1212 // getelementptr instructions to not use the Cast!
1213 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1214 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1215
1216 // Remove the two globals from the module now...
1217 M->getGlobalList().erase(G1);
1218 M->getGlobalList().erase(G2);
1219
1220 // Put the new global into the AppendingVars map so that we can handle
1221 // linking of more than two vars...
1222 Second->second = NG;
1223 }
1224 AppendingVars.erase(First);
1225 }
1226
1227 return false;
1228}
1229
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001230static bool ResolveAliases(Module *Dest) {
1231 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001232 I != E; ++I)
1233 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1234 if (!GV->isDeclaration())
1235 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001236
1237 return false;
1238}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239
1240// LinkModules - This function links two modules together, with the resulting
1241// left module modified to be the composite of the two input modules. If an
1242// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1243// the problem. Upon failure, the Dest module could be in a modified state, and
1244// shouldn't be relied on to be consistent.
1245bool
1246Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1247 assert(Dest != 0 && "Invalid Destination module");
1248 assert(Src != 0 && "Invalid Source Module");
1249
1250 if (Dest->getDataLayout().empty()) {
1251 if (!Src->getDataLayout().empty()) {
1252 Dest->setDataLayout(Src->getDataLayout());
1253 } else {
1254 std::string DataLayout;
1255
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001256 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 if (Src->getEndianness() == Module::BigEndian)
1258 DataLayout.append("E");
1259 else if (Src->getEndianness() == Module::LittleEndian)
1260 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001261 }
1262
1263 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 if (Src->getPointerSize() == Module::Pointer64)
1265 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1266 else if (Src->getPointerSize() == Module::Pointer32)
1267 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001268 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 Dest->setDataLayout(DataLayout);
1270 }
1271 }
1272
Chris Lattner85dd49c2008-02-19 18:49:08 +00001273 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1275 Dest->setTargetTriple(Src->getTargetTriple());
1276
1277 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1278 Src->getDataLayout() != Dest->getDataLayout())
1279 cerr << "WARNING: Linking two modules of different data layouts!\n";
1280 if (!Src->getTargetTriple().empty() &&
1281 Dest->getTargetTriple() != Src->getTargetTriple())
1282 cerr << "WARNING: Linking two modules of different target triples!\n";
1283
Chris Lattner85dd49c2008-02-19 18:49:08 +00001284 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 if (!Src->getModuleInlineAsm().empty()) {
1286 if (Dest->getModuleInlineAsm().empty())
1287 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1288 else
1289 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1290 Src->getModuleInlineAsm());
1291 }
1292
1293 // Update the destination module's dependent libraries list with the libraries
1294 // from the source module. There's no opportunity for duplicates here as the
1295 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001296 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1297 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299
1300 // LinkTypes - Go through the symbol table of the Src module and see if any
1301 // types are named in the src module that are not named in the Dst module.
1302 // Make sure there are no type name conflicts.
1303 if (LinkTypes(Dest, Src, ErrorMsg))
1304 return true;
1305
1306 // ValueMap - Mapping of values from what they used to be in Src, to what they
1307 // are now in Dest.
1308 std::map<const Value*, Value*> ValueMap;
1309
1310 // AppendingVars - Keep track of global variables in the destination module
1311 // with appending linkage. After the module is linked together, they are
1312 // appended and the module is rewritten.
1313 std::multimap<std::string, GlobalVariable *> AppendingVars;
1314 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1315 I != E; ++I) {
1316 // Add all of the appending globals already in the Dest module to
1317 // AppendingVars.
1318 if (I->hasAppendingLinkage())
1319 AppendingVars.insert(std::make_pair(I->getName(), I));
1320 }
1321
1322 // Insert all of the globals in src into the Dest module... without linking
1323 // initializers (which could refer to functions not yet mapped over).
1324 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1325 return true;
1326
1327 // Link the functions together between the two modules, without doing function
1328 // bodies... this just adds external function prototypes to the Dest
1329 // function... We do this so that when we begin processing function bodies,
1330 // all of the global values that may be referenced are available in our
1331 // ValueMap.
1332 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1333 return true;
1334
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001335 // If there were any alias, link them now. We really need to do this now,
1336 // because all of the aliases that may be referenced need to be available in
1337 // ValueMap
1338 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 // Update the initializers in the Dest module now that all globals that may
1341 // be referenced are in Dest.
1342 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1343
1344 // Link in the function bodies that are defined in the source module into the
1345 // DestModule. This consists basically of copying the function over and
1346 // fixing up references to values.
1347 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1348
1349 // If there were any appending global variables, link them together now.
1350 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1351
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001352 // Resolve all uses of aliases with aliasees
1353 if (ResolveAliases(Dest)) return true;
1354
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 // If the source library's module id is in the dependent library list of the
1356 // destination library, remove it since that module is now linked in.
1357 sys::Path modId;
1358 modId.set(Src->getModuleIdentifier());
1359 if (!modId.isEmpty())
1360 Dest->removeLibrary(modId.getBasename());
1361
1362 return false;
1363}
1364
1365// vim: sw=2