blob: 8ece835bfe7702822a742c0f262784a14e2f3b0e [file] [log] [blame]
Mikhail Glushenkov0e658572009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
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"
Owen Anderson943fdf12009-07-07 21:07:14 +000022#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Module.h"
24#include "llvm/TypeSymbolTable.h"
25#include "llvm/ValueSymbolTable.h"
26#include "llvm/Instructions.h"
27#include "llvm/Assembly/Writer.h"
Edwin Török675d5622009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb1aa85b2009-08-23 22:45:37 +000029#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/System/Path.h"
Chris Lattner0b228bf2008-06-16 21:00:18 +000031#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032using namespace llvm;
33
34// Error - Simple wrapper function to conditionally assign to E and return true.
35// This just makes error return conditions a little bit simpler...
Daniel Dunbare3572ba2009-07-25 04:41:11 +000036static inline bool Error(std::string *E, const Twine &Message) {
37 if (E) *E = Message.str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038 return true;
39}
40
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041// Function: ResolveTypes()
42//
43// Description:
44// Attempt to link the two specified types together.
45//
46// Inputs:
47// DestTy - The type to which we wish to resolve.
48// SrcTy - The original type which we want to resolve.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049//
50// Outputs:
51// DestST - The symbol table in which the new type should be placed.
52//
53// Return value:
54// true - There is an error and the types cannot yet be linked.
55// false - No errors.
56//
Chris Lattner06638ab2008-06-16 18:19:05 +000057static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattner06638ab2008-06-16 18:19:05 +000059 assert(DestTy && SrcTy && "Can't handle null types");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060
Chris Lattner06638ab2008-06-16 18:19:05 +000061 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
62 // Type _is_ in module, just opaque...
63 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
64 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
65 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
66 } else {
67 return true; // Cannot link types... not-equal and neither is opaque.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 }
69 return false;
70}
71
Chris Lattner0b228bf2008-06-16 21:00:18 +000072/// LinkerTypeMap - This implements a map of types that is stable
73/// even if types are resolved/refined to other types. This is not a general
74/// purpose map, it is specific to the linker's use.
75namespace {
76class LinkerTypeMap : public AbstractTypeUser {
77 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
78 TheMapTy TheMap;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000079
Chris Lattnera9326492008-06-16 23:06:51 +000080 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
81 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
82public:
83 LinkerTypeMap() {}
84 ~LinkerTypeMap() {
Chris Lattner0b228bf2008-06-16 21:00:18 +000085 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
86 E = TheMap.end(); I != E; ++I)
87 I->first->removeAbstractTypeUser(this);
88 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000089
Chris Lattner0b228bf2008-06-16 21:00:18 +000090 /// lookup - Return the value for the specified type or null if it doesn't
91 /// exist.
92 const Type *lookup(const Type *Ty) const {
93 TheMapTy::const_iterator I = TheMap.find(Ty);
94 if (I != TheMap.end()) return I->second;
95 return 0;
96 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000097
Chris Lattner0b228bf2008-06-16 21:00:18 +000098 /// erase - Remove the specified type, returning true if it was in the set.
99 bool erase(const Type *Ty) {
100 if (!TheMap.erase(Ty))
101 return false;
102 if (Ty->isAbstract())
103 Ty->removeAbstractTypeUser(this);
104 return true;
105 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000106
Chris Lattner0b228bf2008-06-16 21:00:18 +0000107 /// insert - This returns true if the pointer was new to the set, false if it
108 /// was already in the set.
109 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman55d19662008-07-07 17:46:23 +0000110 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner0b228bf2008-06-16 21:00:18 +0000111 return false; // Already in map.
112 if (Src->isAbstract())
113 Src->addAbstractTypeUser(this);
114 return true;
115 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000116
Chris Lattner0b228bf2008-06-16 21:00:18 +0000117protected:
118 /// refineAbstractType - The callback method invoked when an abstract type is
119 /// resolved to another type. An object must override this method to update
120 /// its internal state to reference NewType instead of OldType.
121 ///
122 virtual void refineAbstractType(const DerivedType *OldTy,
123 const Type *NewTy) {
124 TheMapTy::iterator I = TheMap.find(OldTy);
125 const Type *DstTy = I->second;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000126
Chris Lattner0b228bf2008-06-16 21:00:18 +0000127 TheMap.erase(I);
128 if (OldTy->isAbstract())
129 OldTy->removeAbstractTypeUser(this);
130
131 // Don't reinsert into the map if the key is concrete now.
132 if (NewTy->isAbstract())
133 insert(NewTy, DstTy);
134 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000135
Chris Lattner0b228bf2008-06-16 21:00:18 +0000136 /// The other case which AbstractTypeUsers must be aware of is when a type
137 /// makes the transition from being abstract (where it has clients on it's
138 /// AbstractTypeUsers list) to concrete (where it does not). This method
139 /// notifies ATU's when this occurs for a type.
140 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
141 TheMap.erase(AbsTy);
142 AbsTy->removeAbstractTypeUser(this);
143 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000144
Chris Lattner0b228bf2008-06-16 21:00:18 +0000145 // for debugging...
146 virtual void dump() const {
Chris Lattner8a6411c2009-08-23 04:37:46 +0000147 errs() << "AbstractTypeSet!\n";
Chris Lattner0b228bf2008-06-16 21:00:18 +0000148 }
149};
150}
151
152
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153// RecursiveResolveTypes - This is just like ResolveTypes, except that it
154// recurses down into derived types, merging the used types if the parent types
155// are compatible.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000156static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner0b228bf2008-06-16 21:00:18 +0000157 LinkerTypeMap &Pointers) {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000158 if (DstTy == SrcTy) return false; // If already equal, noop
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159
160 // If we found our opaque type, resolve it now!
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000161 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
162 return ResolveTypes(DstTy, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163
164 // Two types cannot be resolved together if they are of different primitive
165 // type. For example, we cannot resolve an int to a float.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000166 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
Chris Lattnere174d322008-06-16 20:03:01 +0000168 // If neither type is abstract, then they really are just different types.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000169 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattnere174d322008-06-16 20:03:01 +0000170 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000171
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000173 switch (DstTy->getTypeID()) {
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000174 default:
175 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 case Type::FunctionTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000177 const FunctionType *DstFT = cast<FunctionType>(DstTy);
178 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000179 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
180 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000182
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000183 // Use TypeHolder's so recursive resolution won't break us.
184 PATypeHolder ST(SrcFT), DT(DstFT);
185 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
186 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
187 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000189 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 return false;
191 }
192 case Type::StructTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000193 const StructType *DstST = cast<StructType>(DstTy);
194 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000195 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000196 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000197
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000198 PATypeHolder ST(SrcST), DT(DstST);
199 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
200 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
201 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000203 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 return false;
205 }
206 case Type::ArrayTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000207 const ArrayType *DAT = cast<ArrayType>(DstTy);
208 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 if (DAT->getNumElements() != SAT->getNumElements()) return true;
210 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000211 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 }
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000213 case Type::VectorTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000214 const VectorType *DVT = cast<VectorType>(DstTy);
215 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000216 if (DVT->getNumElements() != SVT->getNumElements()) return true;
217 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
218 Pointers);
219 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 case Type::PointerTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000221 const PointerType *DstPT = cast<PointerType>(DstTy);
222 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000223
Chris Lattner41fed262008-06-16 19:55:40 +0000224 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
225 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000226
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 // If this is a pointer type, check to see if we have already seen it. If
228 // so, we are in a recursive branch. Cut off the search now. We cannot use
229 // an associative container for this search, because the type pointers (keys
Chris Lattner0b228bf2008-06-16 21:00:18 +0000230 // in the container) change whenever types get resolved.
231 if (SrcPT->isAbstract())
232 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
233 return ExistingDestTy != DstPT;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000234
Chris Lattner0b228bf2008-06-16 21:00:18 +0000235 if (DstPT->isAbstract())
236 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
237 return ExistingSrcTy != SrcPT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 // Otherwise, add the current pointers to the vector to stop recursion on
239 // this pair.
Chris Lattner0b228bf2008-06-16 21:00:18 +0000240 if (DstPT->isAbstract())
241 Pointers.insert(DstPT, SrcPT);
242 if (SrcPT->isAbstract())
243 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000244
Chris Lattner41fed262008-06-16 19:55:40 +0000245 return RecursiveResolveTypesI(DstPT->getElementType(),
246 SrcPT->getElementType(), Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 }
249}
250
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000251static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner0b228bf2008-06-16 21:00:18 +0000252 LinkerTypeMap PointerTypes;
Chris Lattner06638ab2008-06-16 18:19:05 +0000253 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254}
255
256
257// LinkTypes - Go through the symbol table of the Src module and see if any
258// types are named in the src module that are not named in the Dst module.
259// Make sure there are no type name conflicts.
260static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
261 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
262 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
263
264 // Look for a type plane for Type's...
265 TypeSymbolTable::const_iterator TI = SrcST->begin();
266 TypeSymbolTable::const_iterator TE = SrcST->end();
267 if (TI == TE) return false; // No named types, do nothing.
268
269 // Some types cannot be resolved immediately because they depend on other
270 // types being resolved to each other first. This contains a list of types we
271 // are waiting to recheck.
272 std::vector<std::string> DelayedTypesToResolve;
273
274 for ( ; TI != TE; ++TI ) {
275 const std::string &Name = TI->first;
276 const Type *RHS = TI->second;
277
Chris Lattner06638ab2008-06-16 18:19:05 +0000278 // Check to see if this type name is already in the dest module.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 Type *Entry = DestST->lookup(Name);
280
Chris Lattner06638ab2008-06-16 18:19:05 +0000281 // If the name is just in the source module, bring it over to the dest.
282 if (Entry == 0) {
283 if (!Name.empty())
284 DestST->insert(Name, const_cast<Type*>(RHS));
285 } else if (ResolveTypes(Entry, RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 // They look different, save the types 'till later to resolve.
287 DelayedTypesToResolve.push_back(Name);
288 }
289 }
290
291 // Iteratively resolve types while we can...
292 while (!DelayedTypesToResolve.empty()) {
293 // Loop over all of the types, attempting to resolve them if possible...
294 unsigned OldSize = DelayedTypesToResolve.size();
295
296 // Try direct resolution by name...
297 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
298 const std::string &Name = DelayedTypesToResolve[i];
299 Type *T1 = SrcST->lookup(Name);
300 Type *T2 = DestST->lookup(Name);
Chris Lattner06638ab2008-06-16 18:19:05 +0000301 if (!ResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 // We are making progress!
303 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
304 --i;
305 }
306 }
307
308 // Did we not eliminate any types?
309 if (DelayedTypesToResolve.size() == OldSize) {
310 // Attempt to resolve subelements of types. This allows us to merge these
311 // two types: { int* } and { opaque* }
312 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
313 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000314 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 // We are making progress!
316 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
317
318 // Go back to the main loop, perhaps we can resolve directly by name
319 // now...
320 break;
321 }
322 }
323
324 // If we STILL cannot resolve the types, then there is something wrong.
325 if (DelayedTypesToResolve.size() == OldSize) {
326 // Remove the symbol name from the destination.
327 DelayedTypesToResolve.pop_back();
328 }
329 }
330 }
331
332
333 return false;
334}
335
Chris Lattnercb13a012008-07-14 05:52:33 +0000336#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337static void PrintMap(const std::map<const Value*, Value*> &M) {
338 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
339 I != E; ++I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +0000340 errs() << " Fr: " << (void*)I->first << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 I->first->dump();
Chris Lattner8a6411c2009-08-23 04:37:46 +0000342 errs() << " To: " << (void*)I->second << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 I->second->dump();
Chris Lattner8a6411c2009-08-23 04:37:46 +0000344 errs() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 }
346}
Chris Lattnercb13a012008-07-14 05:52:33 +0000347#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348
349
350// RemapOperand - Use ValueMap to convert constants from one module to another.
351static Value *RemapOperand(const Value *In,
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000352 std::map<const Value*, Value*> &ValueMap) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000354 if (I != ValueMap.end())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 return I->second;
356
357 // Check to see if it's a constant that we are interested in transforming.
358 Value *Result = 0;
359 if (const Constant *CPV = dyn_cast<Constant>(In)) {
360 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
361 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
362 return const_cast<Constant*>(CPV); // Simple constants stay identical.
363
364 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
365 std::vector<Constant*> Operands(CPA->getNumOperands());
366 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000367 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
368 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
370 std::vector<Constant*> Operands(CPS->getNumOperands());
371 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000372 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
373 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
375 Result = const_cast<Constant*>(CPV);
376 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
377 std::vector<Constant*> Operands(CP->getNumOperands());
378 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000379 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
Owen Anderson2f422e02009-07-28 21:19:26 +0000380 Result = ConstantVector::get(Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
382 std::vector<Constant*> Ops;
383 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000384 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 Result = CE->getWithOperands(Ops);
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000386 } else if (const BlockAddress *CE = dyn_cast<BlockAddress>(CPV)) {
387 Result = BlockAddress::get(
388 cast<Function>(RemapOperand(CE->getFunction(), ValueMap)),
389 CE->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 } else {
Chris Lattnercb13a012008-07-14 05:52:33 +0000391 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
Edwin Törökbd448e32009-07-14 16:55:14 +0000392 llvm_unreachable("Unknown type of derived type constant value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 }
Devang Patel9f876cd2009-09-03 20:35:57 +0000394 } else if (isa<MetadataBase>(In)) {
395 Result = const_cast<Value*>(In);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 } else if (isa<InlineAsm>(In)) {
397 Result = const_cast<Value*>(In);
398 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000399
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 // Cache the mapping in our local map structure
401 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000402 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 return Result;
404 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000405
Chris Lattnercb13a012008-07-14 05:52:33 +0000406#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000407 errs() << "LinkModules ValueMap: \n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 PrintMap(ValueMap);
409
Chris Lattner8a6411c2009-08-23 04:37:46 +0000410 errs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000411 llvm_unreachable("Couldn't remap value!");
Chris Lattnercb13a012008-07-14 05:52:33 +0000412#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 return 0;
414}
415
416/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
417/// in the symbol table. This is good for all clients except for us. Go
418/// through the trouble to force this back.
419static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
420 assert(GV->getName() != Name && "Can't force rename to self");
421 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
422
423 // If there is a conflict, rename the conflict.
424 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000425 assert(ConflictGV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 "Not conflicting with a static global, should link instead!");
427 GV->takeName(ConflictGV);
428 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
429 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
430 } else {
431 GV->setName(Name); // Force the name back
432 }
433}
434
435/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000436/// a GlobalValue) from the SrcGV to the DestGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000438 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
439 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
440 DestGV->copyAttributesFrom(SrcGV);
441 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442}
443
444/// GetLinkageResult - This analyzes the two global values and determines what
445/// the result will look like in the destination module. In particular, it
446/// computes the resultant linkage type, computes whether the global in the
447/// source should be copied over to the destination (replacing the existing
448/// one), and computes whether this linkage is an error or not. It also performs
449/// visibility checks: we cannot link together two symbols with different
450/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000451static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
453 std::string *Err) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000454 assert((!Dest || !Src->hasLocalLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455 "If Src has internal linkage, Dest shouldn't be set!");
456 if (!Dest) {
457 // Linking something to nothing.
458 LinkFromSrc = true;
459 LT = Src->getLinkage();
460 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000461 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 // external globals, we aren't adding anything.
463 if (Src->hasDLLImportLinkage()) {
464 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
465 if (Dest->isDeclaration()) {
466 LinkFromSrc = true;
467 LT = Src->getLinkage();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000468 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands19d161f2009-03-07 15:45:40 +0000470 // If the Dest is weak, use the source linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 LinkFromSrc = true;
472 LT = Src->getLinkage();
473 } else {
474 LinkFromSrc = false;
475 LT = Dest->getLinkage();
476 }
477 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
478 // If Dest is external but Src is not:
479 LinkFromSrc = true;
480 LT = Src->getLinkage();
481 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
482 if (Src->getLinkage() != Dest->getLinkage())
483 return Error(Err, "Linking globals named '" + Src->getName() +
484 "': can only link appending global with another appending global!");
485 LinkFromSrc = true; // Special cased.
486 LT = Src->getLinkage();
Duncan Sands874bb632009-03-08 13:35:23 +0000487 } else if (Src->isWeakForLinker()) {
Dale Johannesen49c44122008-05-14 20:12:51 +0000488 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
489 // or DLL* linkage.
Chris Lattner68433442009-04-13 05:44:34 +0000490 if (Dest->hasExternalWeakLinkage() ||
491 Dest->hasAvailableExternallyLinkage() ||
492 (Dest->hasLinkOnceLinkage() &&
493 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 LinkFromSrc = true;
495 LT = Src->getLinkage();
496 } else {
497 LinkFromSrc = false;
498 LT = Dest->getLinkage();
499 }
Duncan Sands874bb632009-03-08 13:35:23 +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
Devang Patel0e361fb2009-08-11 18:01:24 +0000531// Insert all of the named mdnoes in Src into the Dest module.
532static void LinkNamedMDNodes(Module *Dest, Module *Src) {
533 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
534 E = Src->named_metadata_end(); I != E; ++I) {
535 const NamedMDNode *SrcNMD = I;
536 NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
537 if (!DestNMD)
538 NamedMDNode::Create(SrcNMD, Dest);
539 else {
540 // Add Src elements into Dest node.
541 for (unsigned i = 0, e = SrcNMD->getNumElements(); i != e; ++i)
542 DestNMD->addElement(SrcNMD->getElement(i));
543 }
544 }
545}
546
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547// LinkGlobals - Loop through the global variables in the src module and merge
548// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000549static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 std::map<const Value*, Value*> &ValueMap,
551 std::multimap<std::string, GlobalVariable *> &AppendingVars,
552 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000553 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000554
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnercb13a012008-07-14 05:52:33 +0000556 for (Module::const_global_iterator I = Src->global_begin(),
557 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000558 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000559 GlobalValue *DGV = 0;
560
Chris Lattner0763d412008-07-14 06:49:45 +0000561 // Check to see if may have to link the global with the global, alias or
562 // function.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000563 if (SGV->hasName() && !SGV->hasLocalLinkage())
Daniel Dunbare03513b2009-07-25 23:55:21 +0000564 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000565
Chris Lattner08d002a2008-07-14 06:52:19 +0000566 // If we found a global with the same name in the dest module, but it has
567 // internal linkage, we are really not doing any linkage here.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000568 if (DGV && DGV->hasLocalLinkage())
Chris Lattner08d002a2008-07-14 06:52:19 +0000569 DGV = 0;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000570
Chris Lattner0763d412008-07-14 06:49:45 +0000571 // If types don't agree due to opaque types, try to resolve them.
572 if (DGV && DGV->getType() != SGV->getType())
573 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000574
Dan Gohman930191f2007-10-08 15:13:30 +0000575 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
576 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 "Global must either be external or have an initializer!");
578
579 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
580 bool LinkFromSrc = false;
581 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
582 return true;
583
Chris Lattner910c6142008-07-14 07:23:24 +0000584 if (DGV == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 // No linking to be performed, simply create an identical version of the
586 // symbol over in the dest module... the initializer will be filled in
Chris Lattner0763d412008-07-14 06:49:45 +0000587 // later by LinkGlobalInits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000589 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000591 SGV->getName(), 0, false,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000592 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000593 // Propagate alignment, visibility and section info.
594 CopyGVAttributes(NewDGV, SGV);
595
596 // If the LLVM runtime renamed the global, but it is an externally visible
597 // symbol, DGV must be an existing global with internal linkage. Rename
598 // it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000599 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 ForceRenaming(NewDGV, SGV->getName());
601
Chris Lattner910c6142008-07-14 07:23:24 +0000602 // Make sure to remember this mapping.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000603 ValueMap[SGV] = NewDGV;
604
Chris Lattner0763d412008-07-14 06:49:45 +0000605 // Keep track that this is an appending variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 if (SGV->hasAppendingLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner910c6142008-07-14 07:23:24 +0000608 continue;
609 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000610
Chris Lattner910c6142008-07-14 07:23:24 +0000611 // If the visibilities of the symbols disagree and the destination is a
612 // prototype, take the visibility of its input.
613 if (DGV->isDeclaration())
614 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000615
Chris Lattner910c6142008-07-14 07:23:24 +0000616 if (DGV->hasAppendingLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 // No linking is performed yet. Just insert a new copy of the global, and
618 // keep track of the fact that it is an appending variable in the
619 // AppendingVars map. The name is cleared out so that no linkage is
620 // performed.
621 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000622 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000624 "", 0, false,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000625 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000627 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000629 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 CopyGVAttributes(NewDGV, SGV);
631
632 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000633 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634
635 // Keep track that this is an appending variable...
636 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner910c6142008-07-14 07:23:24 +0000637 continue;
638 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000639
Chris Lattner910c6142008-07-14 07:23:24 +0000640 if (LinkFromSrc) {
641 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000642 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
643 "': symbol multiple defined");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000644
Chris Lattner0763d412008-07-14 06:49:45 +0000645 // If the types don't match, and if we are to link from the source, nuke
646 // DGV and create a new one of the appropriate type. Note that the thing
647 // we are replacing may be a function (if a prototype, weak, etc) or a
648 // global variable.
649 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000650 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Owen Andersone0f136d2009-07-08 01:26:06 +0000651 SGV->isConstant(), NewLinkage, /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000652 DGV->getName(), 0, false,
Chris Lattner0763d412008-07-14 06:49:45 +0000653 SGV->getType()->getAddressSpace());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000654
Chris Lattner0763d412008-07-14 06:49:45 +0000655 // Propagate alignment, section, and visibility info.
656 CopyGVAttributes(NewDGV, SGV);
Owen Anderson02b48c32009-07-29 18:55:55 +0000657 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Owen Anderson943fdf12009-07-07 21:07:14 +0000658 DGV->getType()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000659
Chris Lattner0763d412008-07-14 06:49:45 +0000660 // DGV will conflict with NewDGV because they both had the same
661 // name. We must erase this now so ForceRenaming doesn't assert
662 // because DGV might not have internal linkage.
663 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
664 Var->eraseFromParent();
665 else
666 cast<Function>(DGV)->eraseFromParent();
667 DGV = NewDGV;
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000668
Chris Lattner0763d412008-07-14 06:49:45 +0000669 // If the symbol table renamed the global, but it is an externally visible
670 // symbol, DGV must be an existing global with internal linkage. Rename.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000671 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattner0763d412008-07-14 06:49:45 +0000672 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000673
Chris Lattner910c6142008-07-14 07:23:24 +0000674 // Inherit const as appropriate.
Chris Lattner0763d412008-07-14 06:49:45 +0000675 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000676
Chris Lattner910c6142008-07-14 07:23:24 +0000677 // Make sure to remember this mapping.
678 ValueMap[SGV] = NewDGV;
679 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000681
Chris Lattner910c6142008-07-14 07:23:24 +0000682 // Not "link from source", keep the one in the DestModule and remap the
683 // input onto it.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000684
Chris Lattner910c6142008-07-14 07:23:24 +0000685 // Special case for const propagation.
686 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
687 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
688 DGVar->setConstant(true);
689
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000690 // SGV is global, but DGV is alias.
691 if (isa<GlobalAlias>(DGV)) {
692 // The only valid mappings are:
693 // - SGV is external declaration, which is effectively a no-op.
694 // - SGV is weak, when we just need to throw SGV out.
Duncan Sands874bb632009-03-08 13:35:23 +0000695 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000696 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
697 "': symbol multiple defined");
698 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000699
Chris Lattner910c6142008-07-14 07:23:24 +0000700 // Set calculated linkage
701 DGV->setLinkage(NewLinkage);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000702
Chris Lattner910c6142008-07-14 07:23:24 +0000703 // Make sure to remember this mapping...
Owen Anderson02b48c32009-07-29 18:55:55 +0000704 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 }
706 return false;
707}
708
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000709static GlobalValue::LinkageTypes
710CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands19d161f2009-03-07 15:45:40 +0000711 GlobalValue::LinkageTypes SL = SGV->getLinkage();
712 GlobalValue::LinkageTypes DL = DGV->getLinkage();
713 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000714 return GlobalValue::ExternalLinkage;
Duncan Sands19d161f2009-03-07 15:45:40 +0000715 else if (SL == GlobalValue::WeakAnyLinkage ||
716 DL == GlobalValue::WeakAnyLinkage)
717 return GlobalValue::WeakAnyLinkage;
718 else if (SL == GlobalValue::WeakODRLinkage ||
719 DL == GlobalValue::WeakODRLinkage)
720 return GlobalValue::WeakODRLinkage;
721 else if (SL == GlobalValue::InternalLinkage &&
722 DL == GlobalValue::InternalLinkage)
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000723 return GlobalValue::InternalLinkage;
Bill Wendling41a07852009-07-20 01:03:30 +0000724 else if (SL == GlobalValue::LinkerPrivateLinkage &&
725 DL == GlobalValue::LinkerPrivateLinkage)
726 return GlobalValue::LinkerPrivateLinkage;
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000727 else {
Duncan Sands19d161f2009-03-07 15:45:40 +0000728 assert (SL == GlobalValue::PrivateLinkage &&
729 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000730 return GlobalValue::PrivateLinkage;
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000731 }
732}
733
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000735// dest module. We're assuming, that all functions/global variables were already
736// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000737static bool LinkAlias(Module *Dest, const Module *Src,
738 std::map<const Value*, Value*> &ValueMap,
739 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 // Loop over all alias in the src module
741 for (Module::const_alias_iterator I = Src->alias_begin(),
742 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000743 const GlobalAlias *SGA = I;
744 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
745 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000747 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000748 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000749 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
750 assert(VMI != ValueMap.end() && "Aliasee not linked");
751 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000752 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000754 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000755 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000756 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000757
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000758 // If types don't agree due to opaque types, try to resolve them.
759 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000760 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000761 }
762
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000763 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000764 DGV = Dest->getGlobalVariable(SGA->getName());
765
766 // If types don't agree due to opaque types, try to resolve them.
767 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000768 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000769 }
770
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000771 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000772 DGV = Dest->getFunction(SGA->getName());
773
774 // If types don't agree due to opaque types, try to resolve them.
775 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000776 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000777 }
778
779 // No linking to be performed on internal stuff.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000780 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000781 DGV = NULL;
782
783 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
784 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000785 // globals are already linked we just need query ValueMap to find the
786 // mapping.
787 if (DAliasee == DGA->getAliasedGlobal()) {
788 // This is just two copies of the same alias. Propagate linkage, if
789 // necessary.
790 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
791
792 NewGA = DGA;
793 // Proceed to 'common' steps
794 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000795 return Error(Err, "Alias Collision on '" + SGA->getName()+
796 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000797 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000798 // The only allowed way is to link alias with external declaration or weak
799 // symbol..
Duncan Sands874bb632009-03-08 13:35:23 +0000800 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000801 // But only if aliasee is global too...
802 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000803 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
804 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000805
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000806 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
807 SGA->getName(), DAliasee, Dest);
808 CopyGVAttributes(NewGA, SGA);
809
810 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000811 if (SGA->getType() != DGVar->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +0000812 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000813 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000814 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000815 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000816
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000817 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000818 // name. We must erase this now so ForceRenaming doesn't assert
819 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000820 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000821
822 // Proceed to 'common' steps
823 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000824 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
825 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000826 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000827 // The only allowed way is to link alias with external declaration or weak
828 // symbol...
Duncan Sands874bb632009-03-08 13:35:23 +0000829 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000830 // But only if aliasee is function too...
831 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000832 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
833 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000834
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000835 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
836 SGA->getName(), DAliasee, Dest);
837 CopyGVAttributes(NewGA, SGA);
838
839 // Any uses of DF need to change to NewGA, with cast, if needed.
840 if (SGA->getType() != DF->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +0000841 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000842 DF->getType()));
843 else
844 DF->replaceAllUsesWith(NewGA);
845
846 // DF will conflict with NewGA because they both had the same
847 // name. We must erase this now so ForceRenaming doesn't assert
848 // because DF might not have internal linkage.
849 DF->eraseFromParent();
850
851 // Proceed to 'common' steps
852 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000853 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
854 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000855 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000856 // No linking to be performed, simply create an identical version of the
857 // alias over in the dest module...
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000858
859 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
860 SGA->getName(), DAliasee, Dest);
861 CopyGVAttributes(NewGA, SGA);
862
863 // Proceed to 'common' steps
864 }
865
866 assert(NewGA && "No alias was created in destination module!");
867
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000868 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000869 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000870 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000871 !NewGA->hasLocalLinkage())
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000872 ForceRenaming(NewGA, SGA->getName());
873
874 // Remember this mapping so uses in the source module get remapped
875 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000876 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000878
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 return false;
880}
881
882
883// LinkGlobalInits - Update the initializers in the Dest module now that all
884// globals that may be referenced are in Dest.
885static bool LinkGlobalInits(Module *Dest, const Module *Src,
886 std::map<const Value*, Value*> &ValueMap,
887 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 // Loop over all of the globals in the src module, mapping them over as we go
889 for (Module::const_global_iterator I = Src->global_begin(),
890 E = Src->global_end(); I != E; ++I) {
891 const GlobalVariable *SGV = I;
892
893 if (SGV->hasInitializer()) { // Only process initialized GV's
894 // Figure out what the initializer looks like in the dest module...
895 Constant *SInit =
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000896 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000897 // Grab destination global variable or alias.
898 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000900 // If dest if global variable, check that initializers match.
901 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
902 if (DGVar->hasInitializer()) {
903 if (SGV->hasExternalLinkage()) {
904 if (DGVar->getInitializer() != SInit)
905 return Error(Err, "Global Variable Collision on '" +
906 SGV->getName() +
907 "': global variables have different initializers");
Duncan Sands874bb632009-03-08 13:35:23 +0000908 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000909 // Nothing is required, mapped values will take the new global
910 // automatically.
Duncan Sands874bb632009-03-08 13:35:23 +0000911 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000912 // Nothing is required, mapped values will take the new global
913 // automatically.
914 } else if (DGVar->hasAppendingLinkage()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000915 llvm_unreachable("Appending linkage unimplemented!");
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000916 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +0000917 llvm_unreachable("Unknown linkage!");
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 } else {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000920 // Copy the initializer over now...
921 DGVar->setInitializer(SInit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 }
923 } else {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000924 // Destination is alias, the only valid situation is when source is
925 // weak. Also, note, that we already checked linkage in LinkGlobals(),
926 // thus we assert here.
927 // FIXME: Should we weaken this assumption, 'dereference' alias and
928 // check for initializer of aliasee?
Duncan Sands874bb632009-03-08 13:35:23 +0000929 assert(SGV->isWeakForLinker());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 }
931 }
932 }
933 return false;
934}
935
936// LinkFunctionProtos - Link the functions together between the two modules,
937// without doing function bodies... this just adds external function prototypes
938// to the Dest function...
939//
940static bool LinkFunctionProtos(Module *Dest, const Module *Src,
941 std::map<const Value*, Value*> &ValueMap,
942 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000943 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000944
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 // Loop over all of the functions in the src module, mapping them over
946 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
947 const Function *SF = I; // SrcFunction
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000948 GlobalValue *DGV = 0;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000949
Chris Lattner0763d412008-07-14 06:49:45 +0000950 // Check to see if may have to link the function with the global, alias or
951 // function.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000952 if (SF->hasName() && !SF->hasLocalLinkage())
Daniel Dunbare03513b2009-07-25 23:55:21 +0000953 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000954
Chris Lattner08d002a2008-07-14 06:52:19 +0000955 // If we found a global with the same name in the dest module, but it has
956 // internal linkage, we are really not doing any linkage here.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000957 if (DGV && DGV->hasLocalLinkage())
Chris Lattner08d002a2008-07-14 06:52:19 +0000958 DGV = 0;
959
Chris Lattner0763d412008-07-14 06:49:45 +0000960 // If types don't agree due to opaque types, try to resolve them.
961 if (DGV && DGV->getType() != SF->getType())
962 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000963
Chris Lattner910c6142008-07-14 07:23:24 +0000964 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
965 bool LinkFromSrc = false;
966 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
967 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000968
Chris Lattner1426bfa2008-06-09 07:36:11 +0000969 // If there is no linkage to be performed, just bring over SF without
970 // modifying it.
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000971 if (DGV == 0) {
Chris Lattner1426bfa2008-06-09 07:36:11 +0000972 // Function does not already exist, simply insert an function signature
973 // identical to SF into the dest module.
974 Function *NewDF = Function::Create(SF->getFunctionType(),
975 SF->getLinkage(),
976 SF->getName(), Dest);
977 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000978
Chris Lattner1426bfa2008-06-09 07:36:11 +0000979 // If the LLVM runtime renamed the function, but it is an externally
980 // visible symbol, DF must be an existing function with internal linkage.
981 // Rename it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000982 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner1426bfa2008-06-09 07:36:11 +0000983 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000984
Chris Lattner1426bfa2008-06-09 07:36:11 +0000985 // ... and remember this mapping...
986 ValueMap[SF] = NewDF;
987 continue;
Chris Lattner910c6142008-07-14 07:23:24 +0000988 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000989
Chris Lattner910c6142008-07-14 07:23:24 +0000990 // If the visibilities of the symbols disagree and the destination is a
991 // prototype, take the visibility of its input.
992 if (DGV->isDeclaration())
993 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000994
Chris Lattner910c6142008-07-14 07:23:24 +0000995 if (LinkFromSrc) {
996 if (isa<GlobalAlias>(DGV))
997 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
998 "': symbol multiple defined");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000999
Chris Lattner910c6142008-07-14 07:23:24 +00001000 // We have a definition of the same name but different type in the
1001 // source module. Copy the prototype to the destination and replace
1002 // uses of the destination's prototype with the new prototype.
1003 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1004 SF->getName(), Dest);
1005 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001006
Chris Lattner910c6142008-07-14 07:23:24 +00001007 // Any uses of DF need to change to NewDF, with cast
Owen Anderson02b48c32009-07-29 18:55:55 +00001008 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
Owen Anderson943fdf12009-07-07 21:07:14 +00001009 DGV->getType()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001010
Chris Lattner910c6142008-07-14 07:23:24 +00001011 // DF will conflict with NewDF because they both had the same. We must
1012 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001013 // not have internal linkage.
Chris Lattner910c6142008-07-14 07:23:24 +00001014 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1015 Var->eraseFromParent();
1016 else
1017 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001018
Chris Lattner910c6142008-07-14 07:23:24 +00001019 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001020 // visible symbol, DF must be an existing function with internal
Chris Lattner910c6142008-07-14 07:23:24 +00001021 // linkage. Rename it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001022 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner910c6142008-07-14 07:23:24 +00001023 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001024
Chris Lattner910c6142008-07-14 07:23:24 +00001025 // Remember this mapping so uses in the source module get remapped
1026 // later by RemapOperand.
1027 ValueMap[SF] = NewDF;
1028 continue;
1029 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001030
Chris Lattner910c6142008-07-14 07:23:24 +00001031 // Not "link from source", keep the one in the DestModule and remap the
1032 // input onto it.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001033
Chris Lattner910c6142008-07-14 07:23:24 +00001034 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +00001035 // The only valid mappings are:
1036 // - SF is external declaration, which is effectively a no-op.
1037 // - SF is weak, when we just need to throw SF out.
Duncan Sands874bb632009-03-08 13:35:23 +00001038 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikovfdeba112008-07-05 23:03:21 +00001039 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1040 "': symbol multiple defined");
Chris Lattner1426bfa2008-06-09 07:36:11 +00001041 }
Anton Korobeynikovfdeba112008-07-05 23:03:21 +00001042
Chris Lattner910c6142008-07-14 07:23:24 +00001043 // Set calculated linkage
1044 DGV->setLinkage(NewLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045
Chris Lattner910c6142008-07-14 07:23:24 +00001046 // Make sure to remember this mapping.
Owen Anderson02b48c32009-07-29 18:55:55 +00001047 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 }
1049 return false;
1050}
1051
1052// LinkFunctionBody - Copy the source function over into the dest function and
1053// fix up references to values. At this point we know that Dest is an external
1054// function, and that Src is not.
1055static bool LinkFunctionBody(Function *Dest, Function *Src,
1056 std::map<const Value*, Value*> &ValueMap,
1057 std::string *Err) {
1058 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1059
1060 // Go through and convert function arguments over, remembering the mapping.
1061 Function::arg_iterator DI = Dest->arg_begin();
1062 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1063 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +00001064 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065
1066 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001067 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 }
1069
1070 // Splice the body of the source function into the dest function.
1071 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1072
1073 // At this point, all of the instructions and values of the function are now
1074 // copied over. The only problem is that they are still referencing values in
1075 // the Source function as operands. Loop through all of the operands of the
1076 // functions and patch them up to point to the local versions...
1077 //
1078 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1079 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1080 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1081 OI != OE; ++OI)
1082 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner26cc8cd2009-11-01 02:46:39 +00001083 *OI = RemapOperand(*OI, ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084
1085 // There is no need to map the arguments anymore.
1086 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1087 I != E; ++I)
1088 ValueMap.erase(I);
1089
1090 return false;
1091}
1092
1093
1094// LinkFunctionBodies - Link in the function bodies that are defined in the
1095// source module into the DestModule. This consists basically of copying the
1096// function over and fixing up references to values.
1097static bool LinkFunctionBodies(Module *Dest, Module *Src,
1098 std::map<const Value*, Value*> &ValueMap,
1099 std::string *Err) {
1100
1101 // Loop over all of the functions in the src module, mapping them over as we
1102 // go
1103 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1104 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnera518cc92008-06-20 05:29:39 +00001105 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
1107 // DF not external SF external?
Chris Lattnera518cc92008-06-20 05:29:39 +00001108 if (DF && DF->isDeclaration())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 // Only provide the function body if there isn't one already.
1110 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1111 return true;
1112 }
1113 }
1114 return false;
1115}
1116
1117// LinkAppendingVars - If there were any appending global variables, link them
1118// together now. Return true on error.
1119static bool LinkAppendingVars(Module *M,
1120 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1121 std::string *ErrorMsg) {
1122 if (AppendingVars.empty()) return false; // Nothing to do.
1123
1124 // Loop over the multimap of appending vars, processing any variables with the
1125 // same name, forming a new appending global variable with both of the
1126 // initializers merged together, then rewrite references to the old variables
1127 // and delete them.
1128 std::vector<Constant*> Inits;
1129 while (AppendingVars.size() > 1) {
1130 // Get the first two elements in the map...
1131 std::multimap<std::string,
1132 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1133
1134 // If the first two elements are for different names, there is no pair...
1135 // Otherwise there is a pair, so link them together...
1136 if (First->first == Second->first) {
1137 GlobalVariable *G1 = First->second, *G2 = Second->second;
1138 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1139 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1140
1141 // Check to see that they two arrays agree on type...
1142 if (T1->getElementType() != T2->getElementType())
1143 return Error(ErrorMsg,
1144 "Appending variables with different element types need to be linked!");
1145 if (G1->isConstant() != G2->isConstant())
1146 return Error(ErrorMsg,
1147 "Appending variables linked with different const'ness!");
1148
1149 if (G1->getAlignment() != G2->getAlignment())
1150 return Error(ErrorMsg,
1151 "Appending variables with different alignment need to be linked!");
1152
1153 if (G1->getVisibility() != G2->getVisibility())
1154 return Error(ErrorMsg,
1155 "Appending variables with different visibility need to be linked!");
1156
1157 if (G1->getSection() != G2->getSection())
1158 return Error(ErrorMsg,
1159 "Appending variables with different section name need to be linked!");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001160
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001162 ArrayType *NewType = ArrayType::get(T1->getElementType(),
Owen Anderson943fdf12009-07-07 21:07:14 +00001163 NewSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164
1165 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001166
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 // Create the new global variable...
1168 GlobalVariable *NG =
Owen Andersone17fc1d2009-07-08 19:03:57 +00001169 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1170 /*init*/0, First->first, 0, G1->isThreadLocal(),
Chris Lattner29ae6c52008-06-27 03:10:24 +00001171 G1->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172
1173 // Propagate alignment, visibility and section info.
1174 CopyGVAttributes(NG, G1);
1175
1176 // Merge the initializer...
1177 Inits.reserve(NewSize);
1178 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1179 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1180 Inits.push_back(I->getOperand(i));
1181 } else {
1182 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersonaac28372009-07-31 20:28:14 +00001183 Constant *CV = Constant::getNullValue(T1->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1185 Inits.push_back(CV);
1186 }
1187 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1188 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1189 Inits.push_back(I->getOperand(i));
1190 } else {
1191 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersonaac28372009-07-31 20:28:14 +00001192 Constant *CV = Constant::getNullValue(T2->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1194 Inits.push_back(CV);
1195 }
Owen Anderson7b4f9f82009-07-28 18:32:17 +00001196 NG->setInitializer(ConstantArray::get(NewType, Inits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197 Inits.clear();
1198
1199 // Replace any uses of the two global variables with uses of the new
1200 // global...
1201
1202 // FIXME: This should rewrite simple/straight-forward uses such as
1203 // getelementptr instructions to not use the Cast!
Owen Anderson02b48c32009-07-29 18:55:55 +00001204 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Anderson943fdf12009-07-07 21:07:14 +00001205 G1->getType()));
Owen Anderson02b48c32009-07-29 18:55:55 +00001206 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Anderson943fdf12009-07-07 21:07:14 +00001207 G2->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208
1209 // Remove the two globals from the module now...
1210 M->getGlobalList().erase(G1);
1211 M->getGlobalList().erase(G2);
1212
1213 // Put the new global into the AppendingVars map so that we can handle
1214 // linking of more than two vars...
1215 Second->second = NG;
1216 }
1217 AppendingVars.erase(First);
1218 }
1219
1220 return false;
1221}
1222
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001223static bool ResolveAliases(Module *Dest) {
1224 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001225 I != E; ++I)
Anton Korobeynikovc7b90912008-09-09 20:05:04 +00001226 if (const GlobalValue *GV = I->resolveAliasedGlobal())
Anton Korobeynikov94352452008-09-09 18:23:48 +00001227 if (GV != I && !GV->isDeclaration())
Anton Korobeynikov82192622008-03-11 22:51:09 +00001228 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001229
1230 return false;
1231}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232
1233// LinkModules - This function links two modules together, with the resulting
1234// left module modified to be the composite of the two input modules. If an
1235// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1236// the problem. Upon failure, the Dest module could be in a modified state, and
1237// shouldn't be relied on to be consistent.
1238bool
1239Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1240 assert(Dest != 0 && "Invalid Destination module");
1241 assert(Src != 0 && "Invalid Source Module");
1242
1243 if (Dest->getDataLayout().empty()) {
1244 if (!Src->getDataLayout().empty()) {
1245 Dest->setDataLayout(Src->getDataLayout());
1246 } else {
1247 std::string DataLayout;
1248
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001249 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 if (Src->getEndianness() == Module::BigEndian)
1251 DataLayout.append("E");
1252 else if (Src->getEndianness() == Module::LittleEndian)
1253 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001254 }
1255
1256 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 if (Src->getPointerSize() == Module::Pointer64)
1258 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1259 else if (Src->getPointerSize() == Module::Pointer32)
1260 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 Dest->setDataLayout(DataLayout);
1263 }
1264 }
1265
Chris Lattner85dd49c2008-02-19 18:49:08 +00001266 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1268 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1271 Src->getDataLayout() != Dest->getDataLayout())
Chris Lattner8a6411c2009-08-23 04:37:46 +00001272 errs() << "WARNING: Linking two modules of different data layouts!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 if (!Src->getTargetTriple().empty() &&
1274 Dest->getTargetTriple() != Src->getTargetTriple())
Chris Lattner8a6411c2009-08-23 04:37:46 +00001275 errs() << "WARNING: Linking two modules of different target triples!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276
Chris Lattner85dd49c2008-02-19 18:49:08 +00001277 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 if (!Src->getModuleInlineAsm().empty()) {
1279 if (Dest->getModuleInlineAsm().empty())
1280 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1281 else
1282 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1283 Src->getModuleInlineAsm());
1284 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 // Update the destination module's dependent libraries list with the libraries
1287 // from the source module. There's no opportunity for duplicates here as the
1288 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001289 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001290 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292
1293 // LinkTypes - Go through the symbol table of the Src module and see if any
1294 // types are named in the src module that are not named in the Dst module.
1295 // Make sure there are no type name conflicts.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001296 if (LinkTypes(Dest, Src, ErrorMsg))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 return true;
1298
1299 // ValueMap - Mapping of values from what they used to be in Src, to what they
1300 // are now in Dest.
1301 std::map<const Value*, Value*> ValueMap;
1302
1303 // AppendingVars - Keep track of global variables in the destination module
1304 // with appending linkage. After the module is linked together, they are
1305 // appended and the module is rewritten.
1306 std::multimap<std::string, GlobalVariable *> AppendingVars;
1307 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1308 I != E; ++I) {
1309 // Add all of the appending globals already in the Dest module to
1310 // AppendingVars.
1311 if (I->hasAppendingLinkage())
1312 AppendingVars.insert(std::make_pair(I->getName(), I));
1313 }
1314
Devang Patel0e361fb2009-08-11 18:01:24 +00001315 // Insert all of the named mdnoes in Src into the Dest module.
1316 LinkNamedMDNodes(Dest, Src);
1317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 // Insert all of the globals in src into the Dest module... without linking
1319 // initializers (which could refer to functions not yet mapped over).
1320 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1321 return true;
1322
1323 // Link the functions together between the two modules, without doing function
1324 // bodies... this just adds external function prototypes to the Dest
1325 // function... We do this so that when we begin processing function bodies,
1326 // all of the global values that may be referenced are available in our
1327 // ValueMap.
1328 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1329 return true;
1330
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001331 // If there were any alias, link them now. We really need to do this now,
1332 // because all of the aliases that may be referenced need to be available in
1333 // ValueMap
1334 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1335
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 // Update the initializers in the Dest module now that all globals that may
1337 // be referenced are in Dest.
1338 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1339
1340 // Link in the function bodies that are defined in the source module into the
1341 // DestModule. This consists basically of copying the function over and
1342 // fixing up references to values.
1343 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1344
1345 // If there were any appending global variables, link them together now.
1346 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1347
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001348 // Resolve all uses of aliases with aliasees
1349 if (ResolveAliases(Dest)) return true;
1350
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 // If the source library's module id is in the dependent library list of the
1352 // destination library, remove it since that module is now linked in.
1353 sys::Path modId;
1354 modId.set(Src->getModuleIdentifier());
1355 if (!modId.isEmpty())
1356 Dest->removeLibrary(modId.getBasename());
1357
1358 return false;
1359}
1360
1361// vim: sw=2