blob: 86f3b84f1d767b25c69939f8031d8a5916554548 [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"
David Greene98479932010-01-05 01:27:59 +000028#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattnerb1aa85b2009-08-23 22:45:37 +000030#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/System/Path.h"
Chris Lattner0b228bf2008-06-16 21:00:18 +000032#include "llvm/ADT/DenseMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033using namespace llvm;
34
35// Error - Simple wrapper function to conditionally assign to E and return true.
36// This just makes error return conditions a little bit simpler...
Daniel Dunbare3572ba2009-07-25 04:41:11 +000037static inline bool Error(std::string *E, const Twine &Message) {
38 if (E) *E = Message.str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039 return true;
40}
41
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042// Function: ResolveTypes()
43//
44// Description:
45// Attempt to link the two specified types together.
46//
47// Inputs:
48// DestTy - The type to which we wish to resolve.
49// SrcTy - The original type which we want to resolve.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050//
51// Outputs:
52// DestST - The symbol table in which the new type should be placed.
53//
54// Return value:
55// true - There is an error and the types cannot yet be linked.
56// false - No errors.
57//
Chris Lattner06638ab2008-06-16 18:19:05 +000058static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattner06638ab2008-06-16 18:19:05 +000060 assert(DestTy && SrcTy && "Can't handle null types");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061
Chris Lattner06638ab2008-06-16 18:19:05 +000062 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
63 // Type _is_ in module, just opaque...
64 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
65 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
66 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
67 } else {
68 return true; // Cannot link types... not-equal and neither is opaque.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 }
70 return false;
71}
72
Chris Lattner0b228bf2008-06-16 21:00:18 +000073/// LinkerTypeMap - This implements a map of types that is stable
74/// even if types are resolved/refined to other types. This is not a general
75/// purpose map, it is specific to the linker's use.
76namespace {
77class LinkerTypeMap : public AbstractTypeUser {
78 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
79 TheMapTy TheMap;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000080
Chris Lattnera9326492008-06-16 23:06:51 +000081 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
82 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
83public:
84 LinkerTypeMap() {}
85 ~LinkerTypeMap() {
Chris Lattner0b228bf2008-06-16 21:00:18 +000086 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
87 E = TheMap.end(); I != E; ++I)
88 I->first->removeAbstractTypeUser(this);
89 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000090
Chris Lattner0b228bf2008-06-16 21:00:18 +000091 /// lookup - Return the value for the specified type or null if it doesn't
92 /// exist.
93 const Type *lookup(const Type *Ty) const {
94 TheMapTy::const_iterator I = TheMap.find(Ty);
95 if (I != TheMap.end()) return I->second;
96 return 0;
97 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +000098
Chris Lattner0b228bf2008-06-16 21:00:18 +000099 /// erase - Remove the specified type, returning true if it was in the set.
100 bool erase(const Type *Ty) {
101 if (!TheMap.erase(Ty))
102 return false;
103 if (Ty->isAbstract())
104 Ty->removeAbstractTypeUser(this);
105 return true;
106 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000107
Chris Lattner0b228bf2008-06-16 21:00:18 +0000108 /// insert - This returns true if the pointer was new to the set, false if it
109 /// was already in the set.
110 bool insert(const Type *Src, const Type *Dst) {
Dan Gohman55d19662008-07-07 17:46:23 +0000111 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner0b228bf2008-06-16 21:00:18 +0000112 return false; // Already in map.
113 if (Src->isAbstract())
114 Src->addAbstractTypeUser(this);
115 return true;
116 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000117
Chris Lattner0b228bf2008-06-16 21:00:18 +0000118protected:
119 /// refineAbstractType - The callback method invoked when an abstract type is
120 /// resolved to another type. An object must override this method to update
121 /// its internal state to reference NewType instead of OldType.
122 ///
123 virtual void refineAbstractType(const DerivedType *OldTy,
124 const Type *NewTy) {
125 TheMapTy::iterator I = TheMap.find(OldTy);
126 const Type *DstTy = I->second;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000127
Chris Lattner0b228bf2008-06-16 21:00:18 +0000128 TheMap.erase(I);
129 if (OldTy->isAbstract())
130 OldTy->removeAbstractTypeUser(this);
131
132 // Don't reinsert into the map if the key is concrete now.
133 if (NewTy->isAbstract())
134 insert(NewTy, DstTy);
135 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000136
Chris Lattner0b228bf2008-06-16 21:00:18 +0000137 /// The other case which AbstractTypeUsers must be aware of is when a type
138 /// makes the transition from being abstract (where it has clients on it's
139 /// AbstractTypeUsers list) to concrete (where it does not). This method
140 /// notifies ATU's when this occurs for a type.
141 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
142 TheMap.erase(AbsTy);
143 AbsTy->removeAbstractTypeUser(this);
144 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000145
Chris Lattner0b228bf2008-06-16 21:00:18 +0000146 // for debugging...
147 virtual void dump() const {
David Greene98479932010-01-05 01:27:59 +0000148 dbgs() << "AbstractTypeSet!\n";
Chris Lattner0b228bf2008-06-16 21:00:18 +0000149 }
150};
151}
152
153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154// RecursiveResolveTypes - This is just like ResolveTypes, except that it
155// recurses down into derived types, merging the used types if the parent types
156// are compatible.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000157static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner0b228bf2008-06-16 21:00:18 +0000158 LinkerTypeMap &Pointers) {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000159 if (DstTy == SrcTy) return false; // If already equal, noop
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160
161 // If we found our opaque type, resolve it now!
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000162 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
163 return ResolveTypes(DstTy, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164
165 // Two types cannot be resolved together if they are of different primitive
166 // type. For example, we cannot resolve an int to a float.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000167 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168
Chris Lattnere174d322008-06-16 20:03:01 +0000169 // If neither type is abstract, then they really are just different types.
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000170 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattnere174d322008-06-16 20:03:01 +0000171 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000172
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000174 switch (DstTy->getTypeID()) {
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000175 default:
176 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 case Type::FunctionTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000178 const FunctionType *DstFT = cast<FunctionType>(DstTy);
179 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000180 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
181 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000183
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000184 // Use TypeHolder's so recursive resolution won't break us.
185 PATypeHolder ST(SrcFT), DT(DstFT);
186 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
187 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
188 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000190 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 return false;
192 }
193 case Type::StructTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000194 const StructType *DstST = cast<StructType>(DstTy);
195 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner41fed262008-06-16 19:55:40 +0000196 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000197 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000198
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000199 PATypeHolder ST(SrcST), DT(DstST);
200 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
201 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
202 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 return true;
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000204 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 return false;
206 }
207 case Type::ArrayTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000208 const ArrayType *DAT = cast<ArrayType>(DstTy);
209 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 if (DAT->getNumElements() != SAT->getNumElements()) return true;
211 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000212 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 }
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000214 case Type::VectorTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000215 const VectorType *DVT = cast<VectorType>(DstTy);
216 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattner6b9bdb72008-06-16 18:27:53 +0000217 if (DVT->getNumElements() != SVT->getNumElements()) return true;
218 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
219 Pointers);
220 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 case Type::PointerTyID: {
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000222 const PointerType *DstPT = cast<PointerType>(DstTy);
223 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000224
Chris Lattner41fed262008-06-16 19:55:40 +0000225 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
226 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000227
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 // If this is a pointer type, check to see if we have already seen it. If
229 // so, we are in a recursive branch. Cut off the search now. We cannot use
230 // an associative container for this search, because the type pointers (keys
Chris Lattner0b228bf2008-06-16 21:00:18 +0000231 // in the container) change whenever types get resolved.
232 if (SrcPT->isAbstract())
233 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
234 return ExistingDestTy != DstPT;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000235
Chris Lattner0b228bf2008-06-16 21:00:18 +0000236 if (DstPT->isAbstract())
237 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
238 return ExistingSrcTy != SrcPT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 // Otherwise, add the current pointers to the vector to stop recursion on
240 // this pair.
Chris Lattner0b228bf2008-06-16 21:00:18 +0000241 if (DstPT->isAbstract())
242 Pointers.insert(DstPT, SrcPT);
243 if (SrcPT->isAbstract())
244 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000245
Chris Lattner41fed262008-06-16 19:55:40 +0000246 return RecursiveResolveTypesI(DstPT->getElementType(),
247 SrcPT->getElementType(), Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 }
250}
251
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000252static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner0b228bf2008-06-16 21:00:18 +0000253 LinkerTypeMap PointerTypes;
Chris Lattner06638ab2008-06-16 18:19:05 +0000254 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255}
256
257
258// LinkTypes - Go through the symbol table of the Src module and see if any
259// types are named in the src module that are not named in the Dst module.
260// Make sure there are no type name conflicts.
261static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
262 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
263 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
264
265 // Look for a type plane for Type's...
266 TypeSymbolTable::const_iterator TI = SrcST->begin();
267 TypeSymbolTable::const_iterator TE = SrcST->end();
268 if (TI == TE) return false; // No named types, do nothing.
269
270 // Some types cannot be resolved immediately because they depend on other
271 // types being resolved to each other first. This contains a list of types we
272 // are waiting to recheck.
273 std::vector<std::string> DelayedTypesToResolve;
274
275 for ( ; TI != TE; ++TI ) {
276 const std::string &Name = TI->first;
277 const Type *RHS = TI->second;
278
Chris Lattner06638ab2008-06-16 18:19:05 +0000279 // Check to see if this type name is already in the dest module.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 Type *Entry = DestST->lookup(Name);
281
Chris Lattner06638ab2008-06-16 18:19:05 +0000282 // If the name is just in the source module, bring it over to the dest.
283 if (Entry == 0) {
284 if (!Name.empty())
285 DestST->insert(Name, const_cast<Type*>(RHS));
286 } else if (ResolveTypes(Entry, RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 // They look different, save the types 'till later to resolve.
288 DelayedTypesToResolve.push_back(Name);
289 }
290 }
291
292 // Iteratively resolve types while we can...
293 while (!DelayedTypesToResolve.empty()) {
294 // Loop over all of the types, attempting to resolve them if possible...
295 unsigned OldSize = DelayedTypesToResolve.size();
296
297 // Try direct resolution by name...
298 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
299 const std::string &Name = DelayedTypesToResolve[i];
300 Type *T1 = SrcST->lookup(Name);
301 Type *T2 = DestST->lookup(Name);
Chris Lattner06638ab2008-06-16 18:19:05 +0000302 if (!ResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 // We are making progress!
304 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
305 --i;
306 }
307 }
308
309 // Did we not eliminate any types?
310 if (DelayedTypesToResolve.size() == OldSize) {
311 // Attempt to resolve subelements of types. This allows us to merge these
312 // two types: { int* } and { opaque* }
313 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
314 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnerb2d8a032008-06-16 21:17:12 +0000315 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 // We are making progress!
317 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
318
319 // Go back to the main loop, perhaps we can resolve directly by name
320 // now...
321 break;
322 }
323 }
324
325 // If we STILL cannot resolve the types, then there is something wrong.
326 if (DelayedTypesToResolve.size() == OldSize) {
327 // Remove the symbol name from the destination.
328 DelayedTypesToResolve.pop_back();
329 }
330 }
331 }
332
333
334 return false;
335}
336
Chris Lattnercb13a012008-07-14 05:52:33 +0000337#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338static void PrintMap(const std::map<const Value*, Value*> &M) {
339 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
340 I != E; ++I) {
David Greene98479932010-01-05 01:27:59 +0000341 dbgs() << " Fr: " << (void*)I->first << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 I->first->dump();
David Greene98479932010-01-05 01:27:59 +0000343 dbgs() << " To: " << (void*)I->second << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 I->second->dump();
David Greene98479932010-01-05 01:27:59 +0000345 dbgs() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 }
347}
Chris Lattnercb13a012008-07-14 05:52:33 +0000348#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349
350
351// RemapOperand - Use ValueMap to convert constants from one module to another.
352static Value *RemapOperand(const Value *In,
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000353 std::map<const Value*, Value*> &ValueMap) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000355 if (I != ValueMap.end())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 return I->second;
357
358 // Check to see if it's a constant that we are interested in transforming.
359 Value *Result = 0;
360 if (const Constant *CPV = dyn_cast<Constant>(In)) {
361 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
362 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
363 return const_cast<Constant*>(CPV); // Simple constants stay identical.
364
365 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
366 std::vector<Constant*> Operands(CPA->getNumOperands());
367 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000368 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
369 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
371 std::vector<Constant*> Operands(CPS->getNumOperands());
372 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000373 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
374 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
376 Result = const_cast<Constant*>(CPV);
377 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
378 std::vector<Constant*> Operands(CP->getNumOperands());
379 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000380 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
Owen Anderson2f422e02009-07-28 21:19:26 +0000381 Result = ConstantVector::get(Operands);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
383 std::vector<Constant*> Ops;
384 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000385 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 Result = CE->getWithOperands(Ops);
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000387 } else if (const BlockAddress *CE = dyn_cast<BlockAddress>(CPV)) {
388 Result = BlockAddress::get(
389 cast<Function>(RemapOperand(CE->getFunction(), ValueMap)),
390 CE->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 } else {
Chris Lattnercb13a012008-07-14 05:52:33 +0000392 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
Edwin Törökbd448e32009-07-14 16:55:14 +0000393 llvm_unreachable("Unknown type of derived type constant value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 }
Victor Hernandeze6680072010-01-27 00:30:42 +0000395 } else if (const MDNode *MD = dyn_cast<MDNode>(In)) {
396 if (MD->isFunctionLocal()) {
397 SmallVector<Value*, 4> Elts;
398 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i) {
399 Value *Op = MD->getOperand(i);
400 // LinkFunctionBody() already handled non-argument values.
401 Elts.push_back(isa<Argument>(Op) ? RemapOperand(Op, ValueMap) : Op);
402 }
403 Result = MDNode::get(In->getContext(), Elts.data(), MD->getNumOperands());
404 } else {
405 Result = const_cast<Value*>(In);
406 }
Chris Lattner8cb92c22010-01-27 02:18:21 +0000407 } else if (isa<MDString>(In) || isa<InlineAsm>(In)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 Result = const_cast<Value*>(In);
409 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000410
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 // Cache the mapping in our local map structure
412 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000413 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return Result;
415 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000416
Chris Lattnercb13a012008-07-14 05:52:33 +0000417#ifndef NDEBUG
David Greene98479932010-01-05 01:27:59 +0000418 dbgs() << "LinkModules ValueMap: \n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 PrintMap(ValueMap);
420
David Greene98479932010-01-05 01:27:59 +0000421 dbgs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000422 llvm_unreachable("Couldn't remap value!");
Chris Lattnercb13a012008-07-14 05:52:33 +0000423#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 return 0;
425}
426
427/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
428/// in the symbol table. This is good for all clients except for us. Go
429/// through the trouble to force this back.
430static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
431 assert(GV->getName() != Name && "Can't force rename to self");
432 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
433
434 // If there is a conflict, rename the conflict.
435 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000436 assert(ConflictGV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 "Not conflicting with a static global, should link instead!");
438 GV->takeName(ConflictGV);
439 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
440 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
441 } else {
442 GV->setName(Name); // Force the name back
443 }
444}
445
446/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000447/// a GlobalValue) from the SrcGV to the DestGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000449 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
450 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
451 DestGV->copyAttributesFrom(SrcGV);
452 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453}
454
455/// GetLinkageResult - This analyzes the two global values and determines what
456/// the result will look like in the destination module. In particular, it
457/// computes the resultant linkage type, computes whether the global in the
458/// source should be copied over to the destination (replacing the existing
459/// one), and computes whether this linkage is an error or not. It also performs
460/// visibility checks: we cannot link together two symbols with different
461/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000462static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
464 std::string *Err) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000465 assert((!Dest || !Src->hasLocalLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 "If Src has internal linkage, Dest shouldn't be set!");
467 if (!Dest) {
468 // Linking something to nothing.
469 LinkFromSrc = true;
470 LT = Src->getLinkage();
471 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000472 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 // external globals, we aren't adding anything.
474 if (Src->hasDLLImportLinkage()) {
475 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
476 if (Dest->isDeclaration()) {
477 LinkFromSrc = true;
478 LT = Src->getLinkage();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000479 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands19d161f2009-03-07 15:45:40 +0000481 // If the Dest is weak, use the source linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 LinkFromSrc = true;
483 LT = Src->getLinkage();
484 } else {
485 LinkFromSrc = false;
486 LT = Dest->getLinkage();
487 }
488 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
489 // If Dest is external but Src is not:
490 LinkFromSrc = true;
491 LT = Src->getLinkage();
492 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
493 if (Src->getLinkage() != Dest->getLinkage())
494 return Error(Err, "Linking globals named '" + Src->getName() +
495 "': can only link appending global with another appending global!");
496 LinkFromSrc = true; // Special cased.
497 LT = Src->getLinkage();
Duncan Sands874bb632009-03-08 13:35:23 +0000498 } else if (Src->isWeakForLinker()) {
Dale Johannesen49c44122008-05-14 20:12:51 +0000499 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
500 // or DLL* linkage.
Chris Lattner68433442009-04-13 05:44:34 +0000501 if (Dest->hasExternalWeakLinkage() ||
502 Dest->hasAvailableExternallyLinkage() ||
503 (Dest->hasLinkOnceLinkage() &&
504 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 LinkFromSrc = true;
506 LT = Src->getLinkage();
507 } else {
508 LinkFromSrc = false;
509 LT = Dest->getLinkage();
510 }
Duncan Sands874bb632009-03-08 13:35:23 +0000511 } else if (Dest->isWeakForLinker()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 // At this point we know that Src has External* or DLL* linkage.
513 if (Src->hasExternalWeakLinkage()) {
514 LinkFromSrc = false;
515 LT = Dest->getLinkage();
516 } else {
517 LinkFromSrc = true;
518 LT = GlobalValue::ExternalLinkage;
519 }
520 } else {
521 assert((Dest->hasExternalLinkage() ||
522 Dest->hasDLLImportLinkage() ||
523 Dest->hasDLLExportLinkage() ||
524 Dest->hasExternalWeakLinkage()) &&
525 (Src->hasExternalLinkage() ||
526 Src->hasDLLImportLinkage() ||
527 Src->hasDLLExportLinkage() ||
528 Src->hasExternalWeakLinkage()) &&
529 "Unexpected linkage type!");
530 return Error(Err, "Linking globals named '" + Src->getName() +
531 "': symbol multiply defined!");
532 }
533
534 // Check visibility
535 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000536 if (!Src->isDeclaration() && !Dest->isDeclaration())
537 return Error(Err, "Linking globals named '" + Src->getName() +
538 "': symbols have different visibilities!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 return false;
540}
541
Devang Patel0e361fb2009-08-11 18:01:24 +0000542// Insert all of the named mdnoes in Src into the Dest module.
543static void LinkNamedMDNodes(Module *Dest, Module *Src) {
544 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
545 E = Src->named_metadata_end(); I != E; ++I) {
546 const NamedMDNode *SrcNMD = I;
547 NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
548 if (!DestNMD)
549 NamedMDNode::Create(SrcNMD, Dest);
550 else {
551 // Add Src elements into Dest node.
Chris Lattnerece76b02009-12-31 01:22:29 +0000552 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
553 DestNMD->addOperand(SrcNMD->getOperand(i));
Devang Patel0e361fb2009-08-11 18:01:24 +0000554 }
555 }
556}
557
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558// LinkGlobals - Loop through the global variables in the src module and merge
559// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000560static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 std::map<const Value*, Value*> &ValueMap,
562 std::multimap<std::string, GlobalVariable *> &AppendingVars,
563 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000564 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000565
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnercb13a012008-07-14 05:52:33 +0000567 for (Module::const_global_iterator I = Src->global_begin(),
568 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000569 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000570 GlobalValue *DGV = 0;
571
Chris Lattner0763d412008-07-14 06:49:45 +0000572 // Check to see if may have to link the global with the global, alias or
573 // function.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000574 if (SGV->hasName() && !SGV->hasLocalLinkage())
Daniel Dunbare03513b2009-07-25 23:55:21 +0000575 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000576
Chris Lattner08d002a2008-07-14 06:52:19 +0000577 // If we found a global with the same name in the dest module, but it has
578 // internal linkage, we are really not doing any linkage here.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000579 if (DGV && DGV->hasLocalLinkage())
Chris Lattner08d002a2008-07-14 06:52:19 +0000580 DGV = 0;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000581
Chris Lattner0763d412008-07-14 06:49:45 +0000582 // If types don't agree due to opaque types, try to resolve them.
583 if (DGV && DGV->getType() != SGV->getType())
584 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000585
Dan Gohman930191f2007-10-08 15:13:30 +0000586 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
587 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 "Global must either be external or have an initializer!");
589
590 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
591 bool LinkFromSrc = false;
592 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
593 return true;
594
Chris Lattner910c6142008-07-14 07:23:24 +0000595 if (DGV == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 // No linking to be performed, simply create an identical version of the
597 // symbol over in the dest module... the initializer will be filled in
Chris Lattner0763d412008-07-14 06:49:45 +0000598 // later by LinkGlobalInits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000600 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000602 SGV->getName(), 0, false,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000603 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 // Propagate alignment, visibility and section info.
605 CopyGVAttributes(NewDGV, SGV);
606
607 // If the LLVM runtime renamed the global, but it is an externally visible
608 // symbol, DGV must be an existing global with internal linkage. Rename
609 // it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000610 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 ForceRenaming(NewDGV, SGV->getName());
612
Chris Lattner910c6142008-07-14 07:23:24 +0000613 // Make sure to remember this mapping.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000614 ValueMap[SGV] = NewDGV;
615
Chris Lattner0763d412008-07-14 06:49:45 +0000616 // Keep track that this is an appending variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 if (SGV->hasAppendingLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner910c6142008-07-14 07:23:24 +0000619 continue;
620 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000621
Chris Lattner910c6142008-07-14 07:23:24 +0000622 // If the visibilities of the symbols disagree and the destination is a
623 // prototype, take the visibility of its input.
624 if (DGV->isDeclaration())
625 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000626
Chris Lattner910c6142008-07-14 07:23:24 +0000627 if (DGV->hasAppendingLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 // No linking is performed yet. Just insert a new copy of the global, and
629 // keep track of the fact that it is an appending variable in the
630 // AppendingVars map. The name is cleared out so that no linkage is
631 // performed.
632 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000633 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000635 "", 0, false,
Chris Lattner29ae6c52008-06-27 03:10:24 +0000636 SGV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000638 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000640 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 CopyGVAttributes(NewDGV, SGV);
642
643 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000644 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645
646 // Keep track that this is an appending variable...
647 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner910c6142008-07-14 07:23:24 +0000648 continue;
649 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000650
Chris Lattner910c6142008-07-14 07:23:24 +0000651 if (LinkFromSrc) {
652 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000653 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
654 "': symbol multiple defined");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000655
Chris Lattner0763d412008-07-14 06:49:45 +0000656 // If the types don't match, and if we are to link from the source, nuke
657 // DGV and create a new one of the appropriate type. Note that the thing
658 // we are replacing may be a function (if a prototype, weak, etc) or a
659 // global variable.
660 GlobalVariable *NewDGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +0000661 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Owen Andersone0f136d2009-07-08 01:26:06 +0000662 SGV->isConstant(), NewLinkage, /*init*/0,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000663 DGV->getName(), 0, false,
Chris Lattner0763d412008-07-14 06:49:45 +0000664 SGV->getType()->getAddressSpace());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000665
Chris Lattner0763d412008-07-14 06:49:45 +0000666 // Propagate alignment, section, and visibility info.
667 CopyGVAttributes(NewDGV, SGV);
Owen Anderson02b48c32009-07-29 18:55:55 +0000668 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Owen Anderson943fdf12009-07-07 21:07:14 +0000669 DGV->getType()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000670
Chris Lattner0763d412008-07-14 06:49:45 +0000671 // DGV will conflict with NewDGV because they both had the same
672 // name. We must erase this now so ForceRenaming doesn't assert
673 // because DGV might not have internal linkage.
674 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
675 Var->eraseFromParent();
676 else
677 cast<Function>(DGV)->eraseFromParent();
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000678
Chris Lattner0763d412008-07-14 06:49:45 +0000679 // If the symbol table renamed the global, but it is an externally visible
680 // symbol, DGV must be an existing global with internal linkage. Rename.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000681 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattner0763d412008-07-14 06:49:45 +0000682 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000683
Chris Lattner910c6142008-07-14 07:23:24 +0000684 // Inherit const as appropriate.
Chris Lattner0763d412008-07-14 06:49:45 +0000685 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000686
Chris Lattner910c6142008-07-14 07:23:24 +0000687 // Make sure to remember this mapping.
688 ValueMap[SGV] = NewDGV;
689 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000691
Chris Lattner910c6142008-07-14 07:23:24 +0000692 // Not "link from source", keep the one in the DestModule and remap the
693 // input onto it.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000694
Chris Lattner910c6142008-07-14 07:23:24 +0000695 // Special case for const propagation.
696 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
697 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
698 DGVar->setConstant(true);
699
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000700 // SGV is global, but DGV is alias.
701 if (isa<GlobalAlias>(DGV)) {
702 // The only valid mappings are:
703 // - SGV is external declaration, which is effectively a no-op.
704 // - SGV is weak, when we just need to throw SGV out.
Duncan Sands874bb632009-03-08 13:35:23 +0000705 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000706 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
707 "': symbol multiple defined");
708 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000709
Chris Lattner910c6142008-07-14 07:23:24 +0000710 // Set calculated linkage
711 DGV->setLinkage(NewLinkage);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000712
Chris Lattner910c6142008-07-14 07:23:24 +0000713 // Make sure to remember this mapping...
Owen Anderson02b48c32009-07-29 18:55:55 +0000714 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 }
716 return false;
717}
718
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000719static GlobalValue::LinkageTypes
720CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands19d161f2009-03-07 15:45:40 +0000721 GlobalValue::LinkageTypes SL = SGV->getLinkage();
722 GlobalValue::LinkageTypes DL = DGV->getLinkage();
723 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000724 return GlobalValue::ExternalLinkage;
Duncan Sands19d161f2009-03-07 15:45:40 +0000725 else if (SL == GlobalValue::WeakAnyLinkage ||
726 DL == GlobalValue::WeakAnyLinkage)
727 return GlobalValue::WeakAnyLinkage;
728 else if (SL == GlobalValue::WeakODRLinkage ||
729 DL == GlobalValue::WeakODRLinkage)
730 return GlobalValue::WeakODRLinkage;
731 else if (SL == GlobalValue::InternalLinkage &&
732 DL == GlobalValue::InternalLinkage)
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000733 return GlobalValue::InternalLinkage;
Bill Wendling41a07852009-07-20 01:03:30 +0000734 else if (SL == GlobalValue::LinkerPrivateLinkage &&
735 DL == GlobalValue::LinkerPrivateLinkage)
736 return GlobalValue::LinkerPrivateLinkage;
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000737 else {
Duncan Sands19d161f2009-03-07 15:45:40 +0000738 assert (SL == GlobalValue::PrivateLinkage &&
739 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000740 return GlobalValue::PrivateLinkage;
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000741 }
742}
743
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000745// dest module. We're assuming, that all functions/global variables were already
746// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000747static bool LinkAlias(Module *Dest, const Module *Src,
748 std::map<const Value*, Value*> &ValueMap,
749 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 // Loop over all alias in the src module
751 for (Module::const_alias_iterator I = Src->alias_begin(),
752 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000753 const GlobalAlias *SGA = I;
754 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
755 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000757 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000758 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000759 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
760 assert(VMI != ValueMap.end() && "Aliasee not linked");
761 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000762 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000764 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000765 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000766 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000767
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000768 // If types don't agree due to opaque types, try to resolve them.
769 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000770 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000771 }
772
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000773 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000774 DGV = Dest->getGlobalVariable(SGA->getName());
775
776 // If types don't agree due to opaque types, try to resolve them.
777 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000778 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000779 }
780
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000781 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000782 DGV = Dest->getFunction(SGA->getName());
783
784 // If types don't agree due to opaque types, try to resolve them.
785 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnere97603b2008-07-10 01:09:33 +0000786 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000787 }
788
789 // No linking to be performed on internal stuff.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000790 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000791 DGV = NULL;
792
793 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
794 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000795 // globals are already linked we just need query ValueMap to find the
796 // mapping.
797 if (DAliasee == DGA->getAliasedGlobal()) {
798 // This is just two copies of the same alias. Propagate linkage, if
799 // necessary.
800 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
801
802 NewGA = DGA;
803 // Proceed to 'common' steps
804 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000805 return Error(Err, "Alias Collision on '" + SGA->getName()+
806 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000807 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000808 // The only allowed way is to link alias with external declaration or weak
809 // symbol..
Duncan Sands874bb632009-03-08 13:35:23 +0000810 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000811 // But only if aliasee is global too...
812 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000813 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
814 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000815
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000816 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
817 SGA->getName(), DAliasee, Dest);
818 CopyGVAttributes(NewGA, SGA);
819
820 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000821 if (SGA->getType() != DGVar->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +0000822 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000823 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000824 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000825 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000826
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000827 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000828 // name. We must erase this now so ForceRenaming doesn't assert
829 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000830 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000831
832 // Proceed to 'common' steps
833 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000834 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
835 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000836 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +0000837 // The only allowed way is to link alias with external declaration or weak
838 // symbol...
Duncan Sands874bb632009-03-08 13:35:23 +0000839 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000840 // But only if aliasee is function too...
841 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000842 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
843 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000844
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000845 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
846 SGA->getName(), DAliasee, Dest);
847 CopyGVAttributes(NewGA, SGA);
848
849 // Any uses of DF need to change to NewGA, with cast, if needed.
850 if (SGA->getType() != DF->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +0000851 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000852 DF->getType()));
853 else
854 DF->replaceAllUsesWith(NewGA);
855
856 // DF will conflict with NewGA because they both had the same
857 // name. We must erase this now so ForceRenaming doesn't assert
858 // because DF might not have internal linkage.
859 DF->eraseFromParent();
860
861 // Proceed to 'common' steps
862 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000863 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
864 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000865 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000866 // No linking to be performed, simply create an identical version of the
867 // alias over in the dest module...
David Chisnall75108312010-01-09 16:27:31 +0000868 Constant *Aliasee = DAliasee;
869 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
870 // by this, but aliases to GEPs are broken to a lot of other things, so
871 // it's less important.
872 if (SGA->getType() != DAliasee->getType())
873 Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000874 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
David Chisnall75108312010-01-09 16:27:31 +0000875 SGA->getName(), Aliasee, Dest);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000876 CopyGVAttributes(NewGA, SGA);
877
878 // Proceed to 'common' steps
879 }
880
881 assert(NewGA && "No alias was created in destination module!");
882
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000883 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000884 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000885 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000886 !NewGA->hasLocalLinkage())
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000887 ForceRenaming(NewGA, SGA->getName());
888
889 // Remember this mapping so uses in the source module get remapped
890 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000891 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000893
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 return false;
895}
896
897
898// LinkGlobalInits - Update the initializers in the Dest module now that all
899// globals that may be referenced are in Dest.
900static bool LinkGlobalInits(Module *Dest, const Module *Src,
901 std::map<const Value*, Value*> &ValueMap,
902 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 // Loop over all of the globals in the src module, mapping them over as we go
904 for (Module::const_global_iterator I = Src->global_begin(),
905 E = Src->global_end(); I != E; ++I) {
906 const GlobalVariable *SGV = I;
907
908 if (SGV->hasInitializer()) { // Only process initialized GV's
909 // Figure out what the initializer looks like in the dest module...
910 Constant *SInit =
Chris Lattner26cc8cd2009-11-01 02:46:39 +0000911 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000912 // Grab destination global variable or alias.
913 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000915 // If dest if global variable, check that initializers match.
916 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
917 if (DGVar->hasInitializer()) {
918 if (SGV->hasExternalLinkage()) {
919 if (DGVar->getInitializer() != SInit)
920 return Error(Err, "Global Variable Collision on '" +
921 SGV->getName() +
922 "': global variables have different initializers");
Duncan Sands874bb632009-03-08 13:35:23 +0000923 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000924 // Nothing is required, mapped values will take the new global
925 // automatically.
Duncan Sands874bb632009-03-08 13:35:23 +0000926 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000927 // Nothing is required, mapped values will take the new global
928 // automatically.
929 } else if (DGVar->hasAppendingLinkage()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000930 llvm_unreachable("Appending linkage unimplemented!");
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000931 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +0000932 llvm_unreachable("Unknown linkage!");
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000933 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 } else {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000935 // Copy the initializer over now...
936 DGVar->setInitializer(SInit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 }
938 } else {
Anton Korobeynikov6b92acf2008-10-15 20:10:50 +0000939 // Destination is alias, the only valid situation is when source is
940 // weak. Also, note, that we already checked linkage in LinkGlobals(),
941 // thus we assert here.
942 // FIXME: Should we weaken this assumption, 'dereference' alias and
943 // check for initializer of aliasee?
Duncan Sands874bb632009-03-08 13:35:23 +0000944 assert(SGV->isWeakForLinker());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 }
946 }
947 }
948 return false;
949}
950
951// LinkFunctionProtos - Link the functions together between the two modules,
952// without doing function bodies... this just adds external function prototypes
953// to the Dest function...
954//
955static bool LinkFunctionProtos(Module *Dest, const Module *Src,
956 std::map<const Value*, Value*> &ValueMap,
957 std::string *Err) {
Chris Lattner0763d412008-07-14 06:49:45 +0000958 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000959
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 // Loop over all of the functions in the src module, mapping them over
961 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
962 const Function *SF = I; // SrcFunction
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000963 GlobalValue *DGV = 0;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000964
Chris Lattner0763d412008-07-14 06:49:45 +0000965 // Check to see if may have to link the function with the global, alias or
966 // function.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000967 if (SF->hasName() && !SF->hasLocalLinkage())
Daniel Dunbare03513b2009-07-25 23:55:21 +0000968 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000969
Chris Lattner08d002a2008-07-14 06:52:19 +0000970 // If we found a global with the same name in the dest module, but it has
971 // internal linkage, we are really not doing any linkage here.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000972 if (DGV && DGV->hasLocalLinkage())
Chris Lattner08d002a2008-07-14 06:52:19 +0000973 DGV = 0;
974
Chris Lattner0763d412008-07-14 06:49:45 +0000975 // If types don't agree due to opaque types, try to resolve them.
976 if (DGV && DGV->getType() != SF->getType())
977 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000978
Chris Lattner910c6142008-07-14 07:23:24 +0000979 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
980 bool LinkFromSrc = false;
981 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
982 return true;
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000983
Chris Lattner1426bfa2008-06-09 07:36:11 +0000984 // If there is no linkage to be performed, just bring over SF without
985 // modifying it.
Anton Korobeynikovfdeba112008-07-05 23:03:21 +0000986 if (DGV == 0) {
Chris Lattner1426bfa2008-06-09 07:36:11 +0000987 // Function does not already exist, simply insert an function signature
988 // identical to SF into the dest module.
989 Function *NewDF = Function::Create(SF->getFunctionType(),
990 SF->getLinkage(),
991 SF->getName(), Dest);
992 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000993
Chris Lattner1426bfa2008-06-09 07:36:11 +0000994 // If the LLVM runtime renamed the function, but it is an externally
995 // visible symbol, DF must be an existing function with internal linkage.
996 // Rename it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000997 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner1426bfa2008-06-09 07:36:11 +0000998 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +0000999
Chris Lattner1426bfa2008-06-09 07:36:11 +00001000 // ... and remember this mapping...
1001 ValueMap[SF] = NewDF;
1002 continue;
Chris Lattner910c6142008-07-14 07:23:24 +00001003 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001004
Chris Lattner910c6142008-07-14 07:23:24 +00001005 // If the visibilities of the symbols disagree and the destination is a
1006 // prototype, take the visibility of its input.
1007 if (DGV->isDeclaration())
1008 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001009
Chris Lattner910c6142008-07-14 07:23:24 +00001010 if (LinkFromSrc) {
1011 if (isa<GlobalAlias>(DGV))
1012 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1013 "': symbol multiple defined");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001014
Chris Lattner910c6142008-07-14 07:23:24 +00001015 // We have a definition of the same name but different type in the
1016 // source module. Copy the prototype to the destination and replace
1017 // uses of the destination's prototype with the new prototype.
1018 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1019 SF->getName(), Dest);
1020 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001021
Chris Lattner910c6142008-07-14 07:23:24 +00001022 // Any uses of DF need to change to NewDF, with cast
Owen Anderson02b48c32009-07-29 18:55:55 +00001023 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
Owen Anderson943fdf12009-07-07 21:07:14 +00001024 DGV->getType()));
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001025
Chris Lattner910c6142008-07-14 07:23:24 +00001026 // DF will conflict with NewDF because they both had the same. We must
1027 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001028 // not have internal linkage.
Chris Lattner910c6142008-07-14 07:23:24 +00001029 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1030 Var->eraseFromParent();
1031 else
1032 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001033
Chris Lattner910c6142008-07-14 07:23:24 +00001034 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001035 // visible symbol, DF must be an existing function with internal
Chris Lattner910c6142008-07-14 07:23:24 +00001036 // linkage. Rename it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001037 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner910c6142008-07-14 07:23:24 +00001038 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001039
Chris Lattner910c6142008-07-14 07:23:24 +00001040 // Remember this mapping so uses in the source module get remapped
1041 // later by RemapOperand.
1042 ValueMap[SF] = NewDF;
1043 continue;
1044 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001045
Chris Lattner910c6142008-07-14 07:23:24 +00001046 // Not "link from source", keep the one in the DestModule and remap the
1047 // input onto it.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001048
Chris Lattner910c6142008-07-14 07:23:24 +00001049 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovcfc59112008-07-05 23:33:22 +00001050 // The only valid mappings are:
1051 // - SF is external declaration, which is effectively a no-op.
1052 // - SF is weak, when we just need to throw SF out.
Duncan Sands874bb632009-03-08 13:35:23 +00001053 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikovfdeba112008-07-05 23:03:21 +00001054 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1055 "': symbol multiple defined");
Chris Lattner1426bfa2008-06-09 07:36:11 +00001056 }
Anton Korobeynikovfdeba112008-07-05 23:03:21 +00001057
Chris Lattner910c6142008-07-14 07:23:24 +00001058 // Set calculated linkage
1059 DGV->setLinkage(NewLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060
Chris Lattner910c6142008-07-14 07:23:24 +00001061 // Make sure to remember this mapping.
Owen Anderson02b48c32009-07-29 18:55:55 +00001062 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063 }
1064 return false;
1065}
1066
1067// LinkFunctionBody - Copy the source function over into the dest function and
1068// fix up references to values. At this point we know that Dest is an external
1069// function, and that Src is not.
1070static bool LinkFunctionBody(Function *Dest, Function *Src,
1071 std::map<const Value*, Value*> &ValueMap,
1072 std::string *Err) {
1073 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1074
1075 // Go through and convert function arguments over, remembering the mapping.
1076 Function::arg_iterator DI = Dest->arg_begin();
1077 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1078 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +00001079 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080
1081 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +00001082 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 }
1084
1085 // Splice the body of the source function into the dest function.
1086 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1087
1088 // At this point, all of the instructions and values of the function are now
1089 // copied over. The only problem is that they are still referencing values in
1090 // the Source function as operands. Loop through all of the operands of the
1091 // functions and patch them up to point to the local versions...
1092 //
1093 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1094 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1095 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1096 OI != OE; ++OI)
1097 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner26cc8cd2009-11-01 02:46:39 +00001098 *OI = RemapOperand(*OI, ValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099
1100 // There is no need to map the arguments anymore.
1101 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1102 I != E; ++I)
1103 ValueMap.erase(I);
1104
1105 return false;
1106}
1107
1108
1109// LinkFunctionBodies - Link in the function bodies that are defined in the
1110// source module into the DestModule. This consists basically of copying the
1111// function over and fixing up references to values.
1112static bool LinkFunctionBodies(Module *Dest, Module *Src,
1113 std::map<const Value*, Value*> &ValueMap,
1114 std::string *Err) {
1115
1116 // Loop over all of the functions in the src module, mapping them over as we
1117 // go
1118 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1119 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnera518cc92008-06-20 05:29:39 +00001120 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121
1122 // DF not external SF external?
Chris Lattnera518cc92008-06-20 05:29:39 +00001123 if (DF && DF->isDeclaration())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 // Only provide the function body if there isn't one already.
1125 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1126 return true;
1127 }
1128 }
1129 return false;
1130}
1131
1132// LinkAppendingVars - If there were any appending global variables, link them
1133// together now. Return true on error.
1134static bool LinkAppendingVars(Module *M,
1135 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1136 std::string *ErrorMsg) {
1137 if (AppendingVars.empty()) return false; // Nothing to do.
1138
1139 // Loop over the multimap of appending vars, processing any variables with the
1140 // same name, forming a new appending global variable with both of the
1141 // initializers merged together, then rewrite references to the old variables
1142 // and delete them.
1143 std::vector<Constant*> Inits;
1144 while (AppendingVars.size() > 1) {
1145 // Get the first two elements in the map...
1146 std::multimap<std::string,
1147 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1148
1149 // If the first two elements are for different names, there is no pair...
1150 // Otherwise there is a pair, so link them together...
1151 if (First->first == Second->first) {
1152 GlobalVariable *G1 = First->second, *G2 = Second->second;
1153 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1154 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1155
1156 // Check to see that they two arrays agree on type...
1157 if (T1->getElementType() != T2->getElementType())
1158 return Error(ErrorMsg,
1159 "Appending variables with different element types need to be linked!");
1160 if (G1->isConstant() != G2->isConstant())
1161 return Error(ErrorMsg,
1162 "Appending variables linked with different const'ness!");
1163
1164 if (G1->getAlignment() != G2->getAlignment())
1165 return Error(ErrorMsg,
1166 "Appending variables with different alignment need to be linked!");
1167
1168 if (G1->getVisibility() != G2->getVisibility())
1169 return Error(ErrorMsg,
1170 "Appending variables with different visibility need to be linked!");
1171
1172 if (G1->getSection() != G2->getSection())
1173 return Error(ErrorMsg,
1174 "Appending variables with different section name need to be linked!");
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001175
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001176 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001177 ArrayType *NewType = ArrayType::get(T1->getElementType(),
Owen Anderson943fdf12009-07-07 21:07:14 +00001178 NewSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179
1180 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001181
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 // Create the new global variable...
1183 GlobalVariable *NG =
Owen Andersone17fc1d2009-07-08 19:03:57 +00001184 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1185 /*init*/0, First->first, 0, G1->isThreadLocal(),
Chris Lattner29ae6c52008-06-27 03:10:24 +00001186 G1->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187
1188 // Propagate alignment, visibility and section info.
1189 CopyGVAttributes(NG, G1);
1190
1191 // Merge the initializer...
1192 Inits.reserve(NewSize);
1193 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1194 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1195 Inits.push_back(I->getOperand(i));
1196 } else {
1197 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersonaac28372009-07-31 20:28:14 +00001198 Constant *CV = Constant::getNullValue(T1->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1200 Inits.push_back(CV);
1201 }
1202 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1203 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1204 Inits.push_back(I->getOperand(i));
1205 } else {
1206 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersonaac28372009-07-31 20:28:14 +00001207 Constant *CV = Constant::getNullValue(T2->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1209 Inits.push_back(CV);
1210 }
Owen Anderson7b4f9f82009-07-28 18:32:17 +00001211 NG->setInitializer(ConstantArray::get(NewType, Inits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 Inits.clear();
1213
1214 // Replace any uses of the two global variables with uses of the new
1215 // global...
1216
1217 // FIXME: This should rewrite simple/straight-forward uses such as
1218 // getelementptr instructions to not use the Cast!
Owen Anderson02b48c32009-07-29 18:55:55 +00001219 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Anderson943fdf12009-07-07 21:07:14 +00001220 G1->getType()));
Owen Anderson02b48c32009-07-29 18:55:55 +00001221 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Anderson943fdf12009-07-07 21:07:14 +00001222 G2->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223
1224 // Remove the two globals from the module now...
1225 M->getGlobalList().erase(G1);
1226 M->getGlobalList().erase(G2);
1227
1228 // Put the new global into the AppendingVars map so that we can handle
1229 // linking of more than two vars...
1230 Second->second = NG;
1231 }
1232 AppendingVars.erase(First);
1233 }
1234
1235 return false;
1236}
1237
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001238static bool ResolveAliases(Module *Dest) {
1239 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001240 I != E; ++I)
David Chisnall75108312010-01-09 16:27:31 +00001241 // We can't sue resolveGlobalAlias here because we need to preserve
1242 // bitcasts and GEPs.
1243 if (const Constant *C = I->getAliasee()) {
1244 while (dyn_cast<GlobalAlias>(C))
1245 C = cast<GlobalAlias>(C)->getAliasee();
1246 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1247 if (C != I && !(GV && GV->isDeclaration()))
1248 I->replaceAllUsesWith(const_cast<Constant*>(C));
1249 }
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001250
1251 return false;
1252}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253
1254// LinkModules - This function links two modules together, with the resulting
1255// left module modified to be the composite of the two input modules. If an
1256// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1257// the problem. Upon failure, the Dest module could be in a modified state, and
1258// shouldn't be relied on to be consistent.
1259bool
1260Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1261 assert(Dest != 0 && "Invalid Destination module");
1262 assert(Src != 0 && "Invalid Source Module");
1263
1264 if (Dest->getDataLayout().empty()) {
1265 if (!Src->getDataLayout().empty()) {
1266 Dest->setDataLayout(Src->getDataLayout());
1267 } else {
1268 std::string DataLayout;
1269
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001270 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 if (Src->getEndianness() == Module::BigEndian)
1272 DataLayout.append("E");
1273 else if (Src->getEndianness() == Module::LittleEndian)
1274 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001275 }
1276
1277 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 if (Src->getPointerSize() == Module::Pointer64)
1279 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1280 else if (Src->getPointerSize() == Module::Pointer32)
1281 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001282 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 Dest->setDataLayout(DataLayout);
1284 }
1285 }
1286
Chris Lattner85dd49c2008-02-19 18:49:08 +00001287 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1289 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001290
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1292 Src->getDataLayout() != Dest->getDataLayout())
Chris Lattner8a6411c2009-08-23 04:37:46 +00001293 errs() << "WARNING: Linking two modules of different data layouts!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 if (!Src->getTargetTriple().empty() &&
1295 Dest->getTargetTriple() != Src->getTargetTriple())
Chris Lattner8a6411c2009-08-23 04:37:46 +00001296 errs() << "WARNING: Linking two modules of different target triples!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297
Chris Lattner85dd49c2008-02-19 18:49:08 +00001298 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 if (!Src->getModuleInlineAsm().empty()) {
1300 if (Dest->getModuleInlineAsm().empty())
1301 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1302 else
1303 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1304 Src->getModuleInlineAsm());
1305 }
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 // Update the destination module's dependent libraries list with the libraries
1308 // from the source module. There's no opportunity for duplicates here as the
1309 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001310 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001311 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313
1314 // LinkTypes - Go through the symbol table of the Src module and see if any
1315 // types are named in the src module that are not named in the Dst module.
1316 // Make sure there are no type name conflicts.
Mikhail Glushenkov47d032b2009-03-03 07:22:23 +00001317 if (LinkTypes(Dest, Src, ErrorMsg))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 return true;
1319
1320 // ValueMap - Mapping of values from what they used to be in Src, to what they
1321 // are now in Dest.
1322 std::map<const Value*, Value*> ValueMap;
1323
1324 // AppendingVars - Keep track of global variables in the destination module
1325 // with appending linkage. After the module is linked together, they are
1326 // appended and the module is rewritten.
1327 std::multimap<std::string, GlobalVariable *> AppendingVars;
1328 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1329 I != E; ++I) {
1330 // Add all of the appending globals already in the Dest module to
1331 // AppendingVars.
1332 if (I->hasAppendingLinkage())
1333 AppendingVars.insert(std::make_pair(I->getName(), I));
1334 }
1335
Devang Patel0e361fb2009-08-11 18:01:24 +00001336 // Insert all of the named mdnoes in Src into the Dest module.
1337 LinkNamedMDNodes(Dest, Src);
1338
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 // Insert all of the globals in src into the Dest module... without linking
1340 // initializers (which could refer to functions not yet mapped over).
1341 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1342 return true;
1343
1344 // Link the functions together between the two modules, without doing function
1345 // bodies... this just adds external function prototypes to the Dest
1346 // function... We do this so that when we begin processing function bodies,
1347 // all of the global values that may be referenced are available in our
1348 // ValueMap.
1349 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1350 return true;
1351
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001352 // If there were any alias, link them now. We really need to do this now,
1353 // because all of the aliases that may be referenced need to be available in
1354 // ValueMap
1355 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 // Update the initializers in the Dest module now that all globals that may
1358 // be referenced are in Dest.
1359 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1360
1361 // Link in the function bodies that are defined in the source module into the
1362 // DestModule. This consists basically of copying the function over and
1363 // fixing up references to values.
1364 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1365
1366 // If there were any appending global variables, link them together now.
1367 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1368
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001369 // Resolve all uses of aliases with aliasees
1370 if (ResolveAliases(Dest)) return true;
1371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 // If the source library's module id is in the dependent library list of the
1373 // destination library, remove it since that module is now linked in.
1374 sys::Path modId;
1375 modId.set(Src->getModuleIdentifier());
1376 if (!modId.isEmpty())
1377 Dest->removeLibrary(modId.getBasename());
1378
1379 return false;
1380}
1381
1382// vim: sw=2