blob: e2cd47a21b39d7abe75bb5884ea9f4bc8abbf212 [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
Chris Lattner8d2de8a2001-10-15 03:12:52 +000013// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +000015// * Merges functions between two modules
Chris Lattner52f7e902001-10-13 07:03:50 +000016//
17//===----------------------------------------------------------------------===//
18
Reid Spencer7cc371a2004-11-14 23:27:04 +000019#include "llvm/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Owen Andersonc9ab7bf2009-07-07 21:07:14 +000022#include "llvm/LLVMContext.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000023#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000024#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000025#include "llvm/ValueSymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000026#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000027#include "llvm/Assembly/Writer.h"
David Greene0fbf0e32010-01-05 01:27:59 +000028#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner74382b72009-08-23 22:45:37 +000030#include "llvm/Support/raw_ostream.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000031#include "llvm/System/Path.h"
Chris Lattner62a81a12008-06-16 21:00:18 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner5c377c52001-10-14 23:29:15 +000035// Error - Simple wrapper function to conditionally assign to E and return true.
36// This just makes error return conditions a little bit simpler...
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +000037static inline bool Error(std::string *E, const Twine &Message) {
38 if (E) *E = Message.str();
Chris Lattner5c377c52001-10-14 23:29:15 +000039 return true;
40}
41
John Criswell700867b2003-11-04 15:22:26 +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.
John Criswell700867b2003-11-04 15:22:26 +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.
Chris Lattner4c00e532003-05-15 16:30:55 +000057//
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000058static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000059 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000060 assert(DestTy && SrcTy && "Can't handle null types");
Chris Lattnere76c57a2003-08-22 06:07:12 +000061
Chris Lattnerbc1c82a2008-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.
Chris Lattner4c00e532003-05-15 16:30:55 +000069 }
70 return false;
71}
72
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +000080
Chris Lattnerfc196f92008-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 Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +000090
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +000098
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +0000107
Chris Lattner62a81a12008-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 Gohman6b345ee2008-07-07 17:46:23 +0000111 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
Chris Lattner62a81a12008-06-16 21:00:18 +0000112 return false; // Already in map.
113 if (Src->isAbstract())
114 Src->addAbstractTypeUser(this);
115 return true;
116 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000117
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +0000127
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +0000136
Chris Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +0000145
Chris Lattner62a81a12008-06-16 21:00:18 +0000146 // for debugging...
147 virtual void dump() const {
David Greene0fbf0e32010-01-05 01:27:59 +0000148 dbgs() << "AbstractTypeSet!\n";
Chris Lattner62a81a12008-06-16 21:00:18 +0000149 }
150};
151}
152
153
Chris Lattnere76c57a2003-08-22 06:07:12 +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 Lattnera4477f92008-06-16 21:17:12 +0000157static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
Chris Lattner62a81a12008-06-16 21:00:18 +0000158 LinkerTypeMap &Pointers) {
Chris Lattnera4477f92008-06-16 21:17:12 +0000159 if (DstTy == SrcTy) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +0000160
Chris Lattnere76c57a2003-08-22 06:07:12 +0000161 // If we found our opaque type, resolve it now!
Chris Lattnera4477f92008-06-16 21:17:12 +0000162 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
163 return ResolveTypes(DstTy, SrcTy);
Misha Brukmanf976c852005-04-21 22:55:34 +0000164
Chris Lattnere76c57a2003-08-22 06:07:12 +0000165 // 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 Lattnera4477f92008-06-16 21:17:12 +0000167 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000168
Chris Lattner56539652008-06-16 20:03:01 +0000169 // If neither type is abstract, then they really are just different types.
Chris Lattnera4477f92008-06-16 21:17:12 +0000170 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
Chris Lattner56539652008-06-16 20:03:01 +0000171 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000172
Chris Lattnere76c57a2003-08-22 06:07:12 +0000173 // Otherwise, resolve the used type used by this derived type...
Chris Lattnera4477f92008-06-16 21:17:12 +0000174 switch (DstTy->getTypeID()) {
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000175 default:
176 return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000177 case Type::FunctionTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000178 const FunctionType *DstFT = cast<FunctionType>(DstTy);
179 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000180 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
181 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000182 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000183
Chris Lattnera4477f92008-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))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000189 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000190 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000191 return false;
192 }
193 case Type::StructTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000194 const StructType *DstST = cast<StructType>(DstTy);
195 const StructType *SrcST = cast<StructType>(SrcTy);
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000196 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000197 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000198
Chris Lattnera4477f92008-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))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000203 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000204 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000205 return false;
206 }
207 case Type::ArrayTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000208 const ArrayType *DAT = cast<ArrayType>(DstTy);
209 const ArrayType *SAT = cast<ArrayType>(SrcTy);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000210 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000211 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000212 Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000213 }
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000214 case Type::VectorTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000215 const VectorType *DVT = cast<VectorType>(DstTy);
216 const VectorType *SVT = cast<VectorType>(SrcTy);
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000217 if (DVT->getNumElements() != SVT->getNumElements()) return true;
218 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
219 Pointers);
220 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000221 case Type::PointerTyID: {
Chris Lattnera4477f92008-06-16 21:17:12 +0000222 const PointerType *DstPT = cast<PointerType>(DstTy);
223 const PointerType *SrcPT = cast<PointerType>(SrcTy);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000224
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000225 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
226 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000227
Chris Lattnere3092c92003-08-23 21:25:54 +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 Lattner62a81a12008-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 Glushenkoveba2cb02009-03-03 07:22:23 +0000235
Chris Lattner62a81a12008-06-16 21:00:18 +0000236 if (DstPT->isAbstract())
237 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
238 return ExistingSrcTy != SrcPT;
Chris Lattnere3092c92003-08-23 21:25:54 +0000239 // Otherwise, add the current pointers to the vector to stop recursion on
240 // this pair.
Chris Lattner62a81a12008-06-16 21:00:18 +0000241 if (DstPT->isAbstract())
242 Pointers.insert(DstPT, SrcPT);
243 if (SrcPT->isAbstract())
244 Pointers.insert(SrcPT, DstPT);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000245
Chris Lattner9ddf2c82008-06-16 19:55:40 +0000246 return RecursiveResolveTypesI(DstPT->getElementType(),
247 SrcPT->getElementType(), Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000248 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000249 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000250}
251
Chris Lattnera4477f92008-06-16 21:17:12 +0000252static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattner62a81a12008-06-16 21:00:18 +0000253 LinkerTypeMap PointerTypes;
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000254 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000255}
256
Chris Lattnere76c57a2003-08-22 06:07:12 +0000257
Chris Lattner2c236f32001-11-03 05:18:24 +0000258// 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.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000261static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000262 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
263 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000264
265 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000266 TypeSymbolTable::const_iterator TI = SrcST->begin();
267 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000268 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000269
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000270 // 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.
Chris Lattner4c00e532003-05-15 16:30:55 +0000273 std::vector<std::string> DelayedTypesToResolve;
274
Reid Spencer567bc2c2004-05-25 08:52:20 +0000275 for ( ; TI != TE; ++TI ) {
276 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000277 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000278
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000279 // Check to see if this type name is already in the dest module.
Reid Spencer78d033e2007-01-06 07:24:44 +0000280 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000281
Chris Lattnerbc1c82a2008-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)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000287 // They look different, save the types 'till later to resolve.
288 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000289 }
290 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000291
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
Chris Lattnere76c57a2003-08-22 06:07:12 +0000297 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000298 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
299 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000300 Type *T1 = SrcST->lookup(Name);
301 Type *T2 = DestST->lookup(Name);
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000302 if (!ResolveTypes(T2, T1)) {
Chris Lattner4c00e532003-05-15 16:30:55 +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) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000311 // Attempt to resolve subelements of types. This allows us to merge these
312 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000313 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
314 const std::string &Name = DelayedTypesToResolve[i];
Chris Lattnera4477f92008-06-16 21:17:12 +0000315 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000316 // We are making progress!
317 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000318
Chris Lattnere76c57a2003-08-22 06:07:12 +0000319 // Go back to the main loop, perhaps we can resolve directly by name
320 // now...
321 break;
322 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000323 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000324
325 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000326 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000327 // Remove the symbol name from the destination.
328 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000329 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000330 }
331 }
332
333
Chris Lattner2c236f32001-11-03 05:18:24 +0000334 return false;
335}
336
Chris Lattner0bb87572008-07-14 05:52:33 +0000337#ifndef NDEBUG
Chris Lattner5c2d3352003-01-30 19:53:34 +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();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000340 I != E; ++I) {
David Greene0fbf0e32010-01-05 01:27:59 +0000341 dbgs() << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000342 I->first->dump();
David Greene0fbf0e32010-01-05 01:27:59 +0000343 dbgs() << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000344 I->second->dump();
David Greene0fbf0e32010-01-05 01:27:59 +0000345 dbgs() << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000346 }
347}
Chris Lattner0bb87572008-07-14 05:52:33 +0000348#endif
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000349
350
Reid Spencer619f0242007-02-04 04:43:17 +0000351// RemapOperand - Use ValueMap to convert constants from one module to another.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000352static Value *RemapOperand(const Value *In,
Chris Lattner2a749d32009-11-01 02:46:39 +0000353 std::map<const Value*, Value*> &ValueMap) {
Chris Lattner0033baf2004-11-16 17:12:38 +0000354 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000355 if (I != ValueMap.end())
Reid Spenceref9b9a72007-02-05 20:47:22 +0000356 return I->second;
Chris Lattner5c377c52001-10-14 23:29:15 +0000357
Reid Spencer619f0242007-02-04 04:43:17 +0000358 // Check to see if it's a constant that we are interested in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000359 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000360 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000361 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000362 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000363 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000364
Chris Lattner18961502002-06-25 16:12:52 +0000365 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000366 std::vector<Constant*> Operands(CPA->getNumOperands());
367 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner2a749d32009-11-01 02:46:39 +0000368 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
369 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000370 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000371 std::vector<Constant*> Operands(CPS->getNumOperands());
372 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner2a749d32009-11-01 02:46:39 +0000373 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
374 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000375 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000376 Result = const_cast<Constant*>(CPV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000377 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
Chris Lattnera88eb922006-01-19 23:15:58 +0000378 std::vector<Constant*> Operands(CP->getNumOperands());
379 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner2a749d32009-11-01 02:46:39 +0000380 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
Owen Andersonaf7ec972009-07-28 21:19:26 +0000381 Result = ConstantVector::get(Operands);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000382 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-07-14 22:21:31 +0000383 std::vector<Constant*> Ops;
384 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
Chris Lattner2a749d32009-11-01 02:46:39 +0000385 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
Chris Lattner27d67212006-07-14 22:21:31 +0000386 Result = CE->getWithOperands(Ops);
Chris Lattner2a749d32009-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());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000391 } else {
Chris Lattner0bb87572008-07-14 05:52:33 +0000392 assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
Torok Edwinc23197a2009-07-14 16:55:14 +0000393 llvm_unreachable("Unknown type of derived type constant value!");
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000394 }
Devang Patelbc5201f2010-01-22 22:52:10 +0000395 } else if (isa<MDNode>(In) || isa<MDString>(In)) {
Devang Patelfaf8fa52009-09-03 20:35:57 +0000396 Result = const_cast<Value*>(In);
Chris Lattner620fd682006-06-01 19:14:22 +0000397 } else if (isa<InlineAsm>(In)) {
398 Result = const_cast<Value*>(In);
399 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000400
Reid Spencer619f0242007-02-04 04:43:17 +0000401 // Cache the mapping in our local map structure
Chris Lattner620fd682006-06-01 19:14:22 +0000402 if (Result) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000403 ValueMap[In] = Result;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000404 return Result;
405 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000406
Chris Lattner0bb87572008-07-14 05:52:33 +0000407#ifndef NDEBUG
David Greene0fbf0e32010-01-05 01:27:59 +0000408 dbgs() << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000409 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000410
David Greene0fbf0e32010-01-05 01:27:59 +0000411 dbgs() << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000412 llvm_unreachable("Couldn't remap value!");
Chris Lattner0bb87572008-07-14 05:52:33 +0000413#endif
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000414 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000415}
416
Reid Spencer8bef0372007-02-04 04:29:21 +0000417/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
418/// in the symbol table. This is good for all clients except for us. Go
419/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000420static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
421 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000422 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000423
424 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000425 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000426 assert(ConflictGV->hasLocalLinkage() &&
Reid Spenceref9b9a72007-02-05 20:47:22 +0000427 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000428 GV->takeName(ConflictGV);
429 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000430 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000431 } else {
432 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000433 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000434}
Reid Spencer8bef0372007-02-04 04:29:21 +0000435
Reid Spenceref9b9a72007-02-05 20:47:22 +0000436/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000437/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000438static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000439 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
440 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
441 DestGV->copyAttributesFrom(SrcGV);
442 DestGV->setAlignment(Alignment);
Chris Lattnerc0036282004-08-04 07:05:54 +0000443}
444
Chris Lattneraee38ea2004-12-03 22:18:41 +0000445/// GetLinkageResult - This analyzes the two global values and determines what
446/// the result will look like in the destination module. In particular, it
447/// computes the resultant linkage type, computes whether the global in the
448/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000449/// one), and computes whether this linkage is an error or not. It also performs
450/// visibility checks: we cannot link together two symbols with different
451/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000452static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000453 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
454 std::string *Err) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000455 assert((!Dest || !Src->hasLocalLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000456 "If Src has internal linkage, Dest shouldn't be set!");
457 if (!Dest) {
458 // Linking something to nothing.
459 LinkFromSrc = true;
460 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000461 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000462 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000463 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000464 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000465 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000466 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000467 LinkFromSrc = true;
468 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000469 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000470 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000471 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000472 LinkFromSrc = true;
473 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000474 } else {
475 LinkFromSrc = false;
476 LT = Dest->getLinkage();
477 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000478 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000479 // If Dest is external but Src is not:
480 LinkFromSrc = true;
481 LT = Src->getLinkage();
482 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
483 if (Src->getLinkage() != Dest->getLinkage())
484 return Error(Err, "Linking globals named '" + Src->getName() +
485 "': can only link appending global with another appending global!");
486 LinkFromSrc = true; // Special cased.
487 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000488 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000489 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
490 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000491 if (Dest->hasExternalWeakLinkage() ||
492 Dest->hasAvailableExternallyLinkage() ||
493 (Dest->hasLinkOnceLinkage() &&
494 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000495 LinkFromSrc = true;
496 LT = Src->getLinkage();
497 } else {
498 LinkFromSrc = false;
499 LT = Dest->getLinkage();
500 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000501 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000502 // At this point we know that Src has External* or DLL* linkage.
503 if (Src->hasExternalWeakLinkage()) {
504 LinkFromSrc = false;
505 LT = Dest->getLinkage();
506 } else {
507 LinkFromSrc = true;
508 LT = GlobalValue::ExternalLinkage;
509 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000510 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000511 assert((Dest->hasExternalLinkage() ||
512 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000513 Dest->hasDLLExportLinkage() ||
514 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000515 (Src->hasExternalLinkage() ||
516 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000517 Src->hasDLLExportLinkage() ||
518 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000519 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000520 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000521 "': symbol multiply defined!");
522 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000523
524 // Check visibility
525 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000526 if (!Src->isDeclaration() && !Dest->isDeclaration())
527 return Error(Err, "Linking globals named '" + Src->getName() +
528 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000529 return false;
530}
Chris Lattner5c377c52001-10-14 23:29:15 +0000531
Devang Patelab67e702009-08-11 18:01:24 +0000532// Insert all of the named mdnoes in Src into the Dest module.
533static void LinkNamedMDNodes(Module *Dest, Module *Src) {
534 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
535 E = Src->named_metadata_end(); I != E; ++I) {
536 const NamedMDNode *SrcNMD = I;
537 NamedMDNode *DestNMD = Dest->getNamedMetadata(SrcNMD->getName());
538 if (!DestNMD)
539 NamedMDNode::Create(SrcNMD, Dest);
540 else {
541 // Add Src elements into Dest node.
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000542 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
543 DestNMD->addOperand(SrcNMD->getOperand(i));
Devang Patelab67e702009-08-11 18:01:24 +0000544 }
545 }
546}
547
Chris Lattner5c377c52001-10-14 23:29:15 +0000548// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000549// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000550static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000551 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000552 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000553 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000554 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000555
Chris Lattner5c377c52001-10-14 23:29:15 +0000556 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner0bb87572008-07-14 05:52:33 +0000557 for (Module::const_global_iterator I = Src->global_begin(),
558 E = Src->global_end(); I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000559 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000560 GlobalValue *DGV = 0;
561
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000562 // Check to see if may have to link the global with the global, alias or
563 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000564 if (SGV->hasName() && !SGV->hasLocalLinkage())
Daniel Dunbar03d76512009-07-25 23:55:21 +0000565 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000566
Chris Lattnerae1132d2008-07-14 06:52:19 +0000567 // If we found a global with the same name in the dest module, but it has
568 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000569 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000570 DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000571
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000572 // If types don't agree due to opaque types, try to resolve them.
573 if (DGV && DGV->getType() != SGV->getType())
574 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000575
Dan Gohmanc3183292007-10-08 15:13:30 +0000576 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
577 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000578 "Global must either be external or have an initializer!");
579
Chris Lattnerb324bd72006-11-09 05:18:12 +0000580 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
581 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000582 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
583 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000584
Chris Lattner6157e382008-07-14 07:23:24 +0000585 if (DGV == 0) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000586 // No linking to be performed, simply create an identical version of the
587 // symbol over in the dest module... the initializer will be filled in
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000588 // later by LinkGlobalInits.
Chris Lattner2719bac2003-04-21 21:15:04 +0000589 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000590 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner2719bac2003-04-21 21:15:04 +0000591 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000592 SGV->getName(), 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000593 SGV->getType()->getAddressSpace());
Reid Spencer471feac2007-02-04 04:30:33 +0000594 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000595 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000596
Chris Lattner2719bac2003-04-21 21:15:04 +0000597 // If the LLVM runtime renamed the global, but it is an externally visible
598 // symbol, DGV must be an existing global with internal linkage. Rename
599 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000600 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
Chris Lattnerc0036282004-08-04 07:05:54 +0000601 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000602
Chris Lattner6157e382008-07-14 07:23:24 +0000603 // Make sure to remember this mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000604 ValueMap[SGV] = NewDGV;
605
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000606 // Keep track that this is an appending variable.
Chris Lattner8166e6e2003-05-13 21:33:43 +0000607 if (SGV->hasAppendingLinkage())
Chris Lattner8166e6e2003-05-13 21:33:43 +0000608 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000609 continue;
610 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000611
Chris Lattner6157e382008-07-14 07:23:24 +0000612 // If the visibilities of the symbols disagree and the destination is a
613 // prototype, take the visibility of its input.
614 if (DGV->isDeclaration())
615 DGV->setVisibility(SGV->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000616
Chris Lattner6157e382008-07-14 07:23:24 +0000617 if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000618 // No linking is performed yet. Just insert a new copy of the global, and
619 // keep track of the fact that it is an appending variable in the
620 // AppendingVars map. The name is cleared out so that no linkage is
621 // performed.
622 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000623 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Chris Lattner8166e6e2003-05-13 21:33:43 +0000624 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000625 "", 0, false,
Chris Lattnera534b0f2008-06-27 03:10:24 +0000626 SGV->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +0000627
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000628 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000629 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000630 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000631 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000632
Chris Lattner8166e6e2003-05-13 21:33:43 +0000633 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000634 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000635
636 // Keep track that this is an appending variable...
637 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattner6157e382008-07-14 07:23:24 +0000638 continue;
639 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000640
Chris Lattner6157e382008-07-14 07:23:24 +0000641 if (LinkFromSrc) {
642 if (isa<GlobalAlias>(DGV))
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000643 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
644 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000645
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000646 // If the types don't match, and if we are to link from the source, nuke
647 // DGV and create a new one of the appropriate type. Note that the thing
648 // we are replacing may be a function (if a prototype, weak, etc) or a
649 // global variable.
650 GlobalVariable *NewDGV =
Owen Andersone9b11b42009-07-08 19:03:57 +0000651 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
Owen Anderson3d29df32009-07-08 01:26:06 +0000652 SGV->isConstant(), NewLinkage, /*init*/0,
Owen Andersone9b11b42009-07-08 19:03:57 +0000653 DGV->getName(), 0, false,
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000654 SGV->getType()->getAddressSpace());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000655
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000656 // Propagate alignment, section, and visibility info.
657 CopyGVAttributes(NewDGV, SGV);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000658 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +0000659 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000660
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000661 // DGV will conflict with NewDGV because they both had the same
662 // name. We must erase this now so ForceRenaming doesn't assert
663 // because DGV might not have internal linkage.
664 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
665 Var->eraseFromParent();
666 else
667 cast<Function>(DGV)->eraseFromParent();
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000668
Chris Lattnerd1ec48c2008-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 Espindolabb46f522009-01-15 20:18:42 +0000671 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000672 ForceRenaming(NewDGV, SGV->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000673
Chris Lattner6157e382008-07-14 07:23:24 +0000674 // Inherit const as appropriate.
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000675 NewDGV->setConstant(SGV->isConstant());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000676
Chris Lattner6157e382008-07-14 07:23:24 +0000677 // Make sure to remember this mapping.
678 ValueMap[SGV] = NewDGV;
679 continue;
Chris Lattner5c377c52001-10-14 23:29:15 +0000680 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000681
Chris Lattner6157e382008-07-14 07:23:24 +0000682 // Not "link from source", keep the one in the DestModule and remap the
683 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000684
Chris Lattner6157e382008-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 Korobeynikovd13726f2008-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 Sandsa05ef5e2009-03-08 13:35:23 +0000695 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000696 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
697 "': symbol multiple defined");
698 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000699
Chris Lattner6157e382008-07-14 07:23:24 +0000700 // Set calculated linkage
701 DGV->setLinkage(NewLinkage);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000702
Chris Lattner6157e382008-07-14 07:23:24 +0000703 // Make sure to remember this mapping...
Owen Andersonbaf3c402009-07-29 18:55:55 +0000704 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000705 }
706 return false;
707}
708
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000709static GlobalValue::LinkageTypes
710CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
Duncan Sands667d4b82009-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 Korobeynikov58887bc2008-03-05 22:22:46 +0000714 return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-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 Korobeynikov58887bc2008-03-05 22:22:46 +0000723 return GlobalValue::InternalLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000724 else if (SL == GlobalValue::LinkerPrivateLinkage &&
725 DL == GlobalValue::LinkerPrivateLinkage)
726 return GlobalValue::LinkerPrivateLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000727 else {
Duncan Sands667d4b82009-03-07 15:45:40 +0000728 assert (SL == GlobalValue::PrivateLinkage &&
729 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000730 return GlobalValue::PrivateLinkage;
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000731 }
732}
733
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000734// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000735// dest module. We're assuming, that all functions/global variables were already
736// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000737static bool LinkAlias(Module *Dest, const Module *Src,
738 std::map<const Value*, Value*> &ValueMap,
739 std::string *Err) {
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +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 Korobeynikov58887bc2008-03-05 22:22:46 +0000743 const GlobalAlias *SGA = I;
744 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
745 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000746
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000747 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000748 // of SAliasee in Dest.
Ted Kremenek58d5e052008-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 Korobeynikovcaa8ae82008-05-10 14:41:43 +0000752 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000753
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000754 // Try to find something 'similar' to SGA in destination module.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000755 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000756 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000757
Anton Korobeynikovcaa8ae82008-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 Lattner5ed2ba22008-07-10 01:09:33 +0000760 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000761 }
762
Rafael Espindolabb46f522009-01-15 20:18:42 +0000763 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-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 Lattner5ed2ba22008-07-10 01:09:33 +0000768 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000769 }
770
Rafael Espindolabb46f522009-01-15 20:18:42 +0000771 if (!DGV && !SGA->hasLocalLinkage()) {
Anton Korobeynikovcaa8ae82008-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 Lattner5ed2ba22008-07-10 01:09:33 +0000776 RecursiveResolveTypes(SGA->getType(), DGV->getType());
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000777 }
778
779 // No linking to be performed on internal stuff.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000780 if (DGV && DGV->hasLocalLinkage())
Anton Korobeynikovcaa8ae82008-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 Korobeynikov58887bc2008-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 Korobeynikov1438b9d2008-03-10 22:34:46 +0000795 return Error(Err, "Alias Collision on '" + SGA->getName()+
796 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000797 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000798 // The only allowed way is to link alias with external declaration or weak
799 // symbol..
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000800 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000801 // But only if aliasee is global too...
802 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000803 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
804 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000805
Anton Korobeynikov58887bc2008-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 Korobeynikovcaa8ae82008-05-10 14:41:43 +0000811 if (SGA->getType() != DGVar->getType())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000812 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000813 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000814 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000815 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000816
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000817 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-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 Korobeynikovcaa8ae82008-05-10 14:41:43 +0000820 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000821
822 // Proceed to 'common' steps
823 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000824 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
825 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000826 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +0000827 // The only allowed way is to link alias with external declaration or weak
828 // symbol...
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000829 if (DF->isDeclaration() || DF->isWeakForLinker()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000830 // But only if aliasee is function too...
831 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000832 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
833 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000834
Anton Korobeynikovb5a4bd82008-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 Andersonbaf3c402009-07-29 18:55:55 +0000841 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
Anton Korobeynikovb5a4bd82008-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 Korobeynikov1438b9d2008-03-10 22:34:46 +0000853 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
854 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000855 } else {
Anton Korobeynikovcaa8ae82008-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...
David Chisnall34722462010-01-09 16:27:31 +0000858 Constant *Aliasee = DAliasee;
859 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
860 // by this, but aliases to GEPs are broken to a lot of other things, so
861 // it's less important.
862 if (SGA->getType() != DAliasee->getType())
863 Aliasee = ConstantExpr::getBitCast(DAliasee, SGA->getType());
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000864 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
David Chisnall34722462010-01-09 16:27:31 +0000865 SGA->getName(), Aliasee, Dest);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000866 CopyGVAttributes(NewGA, SGA);
867
868 // Proceed to 'common' steps
869 }
870
871 assert(NewGA && "No alias was created in destination module!");
872
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000873 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000874 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000875 if (NewGA->getName() != SGA->getName() &&
Rafael Espindolabb46f522009-01-15 20:18:42 +0000876 !NewGA->hasLocalLinkage())
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000877 ForceRenaming(NewGA, SGA->getName());
878
879 // Remember this mapping so uses in the source module get remapped
880 // later by RemapOperand.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000881 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000882 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000883
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000884 return false;
885}
886
Chris Lattner5c377c52001-10-14 23:29:15 +0000887
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000888// LinkGlobalInits - Update the initializers in the Dest module now that all
889// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000890static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000891 std::map<const Value*, Value*> &ValueMap,
892 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000893 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000894 for (Module::const_global_iterator I = Src->global_begin(),
895 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000896 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000897
898 if (SGV->hasInitializer()) { // Only process initialized GV's
899 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000900 Constant *SInit =
Chris Lattner2a749d32009-11-01 02:46:39 +0000901 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000902 // Grab destination global variable or alias.
903 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000904
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000905 // If dest if global variable, check that initializers match.
906 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
907 if (DGVar->hasInitializer()) {
908 if (SGV->hasExternalLinkage()) {
909 if (DGVar->getInitializer() != SInit)
910 return Error(Err, "Global Variable Collision on '" +
911 SGV->getName() +
912 "': global variables have different initializers");
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000913 } else if (DGVar->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000914 // Nothing is required, mapped values will take the new global
915 // automatically.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000916 } else if (SGV->isWeakForLinker()) {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000917 // Nothing is required, mapped values will take the new global
918 // automatically.
919 } else if (DGVar->hasAppendingLinkage()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000920 llvm_unreachable("Appending linkage unimplemented!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000921 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000922 llvm_unreachable("Unknown linkage!");
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000923 }
Chris Lattner4ad02e72003-04-16 20:28:45 +0000924 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000925 // Copy the initializer over now...
926 DGVar->setInitializer(SInit);
Chris Lattner4ad02e72003-04-16 20:28:45 +0000927 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000928 } else {
Anton Korobeynikovd13726f2008-10-15 20:10:50 +0000929 // Destination is alias, the only valid situation is when source is
930 // weak. Also, note, that we already checked linkage in LinkGlobals(),
931 // thus we assert here.
932 // FIXME: Should we weaken this assumption, 'dereference' alias and
933 // check for initializer of aliasee?
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000934 assert(SGV->isWeakForLinker());
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000935 }
936 }
937 }
938 return false;
939}
Chris Lattner5c377c52001-10-14 23:29:15 +0000940
Chris Lattner79df7c02002-03-26 18:01:55 +0000941// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000942// without doing function bodies... this just adds external function prototypes
943// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000944//
Chris Lattner79df7c02002-03-26 18:01:55 +0000945static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000946 std::map<const Value*, Value*> &ValueMap,
947 std::string *Err) {
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000948 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000949
Reid Spencer619f0242007-02-04 04:43:17 +0000950 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000951 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000952 const Function *SF = I; // SrcFunction
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000953 GlobalValue *DGV = 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000954
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000955 // Check to see if may have to link the function with the global, alias or
956 // function.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000957 if (SF->hasName() && !SF->hasLocalLinkage())
Daniel Dunbar03d76512009-07-25 23:55:21 +0000958 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000959
Chris Lattnerae1132d2008-07-14 06:52:19 +0000960 // If we found a global with the same name in the dest module, but it has
961 // internal linkage, we are really not doing any linkage here.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000962 if (DGV && DGV->hasLocalLinkage())
Chris Lattnerae1132d2008-07-14 06:52:19 +0000963 DGV = 0;
964
Chris Lattnerd1ec48c2008-07-14 06:49:45 +0000965 // If types don't agree due to opaque types, try to resolve them.
966 if (DGV && DGV->getType() != SF->getType())
967 RecursiveResolveTypes(SF->getType(), DGV->getType());
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000968
Chris Lattner6157e382008-07-14 07:23:24 +0000969 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
970 bool LinkFromSrc = false;
971 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
972 return true;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000973
Chris Lattner82468492008-06-09 07:36:11 +0000974 // If there is no linkage to be performed, just bring over SF without
975 // modifying it.
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +0000976 if (DGV == 0) {
Chris Lattner82468492008-06-09 07:36:11 +0000977 // Function does not already exist, simply insert an function signature
978 // identical to SF into the dest module.
979 Function *NewDF = Function::Create(SF->getFunctionType(),
980 SF->getLinkage(),
981 SF->getName(), Dest);
982 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000983
Chris Lattner82468492008-06-09 07:36:11 +0000984 // If the LLVM runtime renamed the function, but it is an externally
985 // visible symbol, DF must be an existing function with internal linkage.
986 // Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000987 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
Chris Lattner82468492008-06-09 07:36:11 +0000988 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000989
Chris Lattner82468492008-06-09 07:36:11 +0000990 // ... and remember this mapping...
991 ValueMap[SF] = NewDF;
992 continue;
Chris Lattner6157e382008-07-14 07:23:24 +0000993 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000994
Chris Lattner6157e382008-07-14 07:23:24 +0000995 // If the visibilities of the symbols disagree and the destination is a
996 // prototype, take the visibility of its input.
997 if (DGV->isDeclaration())
998 DGV->setVisibility(SF->getVisibility());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000999
Chris Lattner6157e382008-07-14 07:23:24 +00001000 if (LinkFromSrc) {
1001 if (isa<GlobalAlias>(DGV))
1002 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1003 "': symbol multiple defined");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001004
Chris Lattner6157e382008-07-14 07:23:24 +00001005 // We have a definition of the same name but different type in the
1006 // source module. Copy the prototype to the destination and replace
1007 // uses of the destination's prototype with the new prototype.
1008 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
1009 SF->getName(), Dest);
1010 CopyGVAttributes(NewDF, SF);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001011
Chris Lattner6157e382008-07-14 07:23:24 +00001012 // Any uses of DF need to change to NewDF, with cast
Owen Andersonbaf3c402009-07-29 18:55:55 +00001013 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001014 DGV->getType()));
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001015
Chris Lattner6157e382008-07-14 07:23:24 +00001016 // DF will conflict with NewDF because they both had the same. We must
1017 // erase this now so ForceRenaming doesn't assert because DF might
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001018 // not have internal linkage.
Chris Lattner6157e382008-07-14 07:23:24 +00001019 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
1020 Var->eraseFromParent();
1021 else
1022 cast<Function>(DGV)->eraseFromParent();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001023
Chris Lattner6157e382008-07-14 07:23:24 +00001024 // If the symbol table renamed the function, but it is an externally
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001025 // visible symbol, DF must be an existing function with internal
Chris Lattner6157e382008-07-14 07:23:24 +00001026 // linkage. Rename it.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001027 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
Chris Lattner6157e382008-07-14 07:23:24 +00001028 ForceRenaming(NewDF, SF->getName());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001029
Chris Lattner6157e382008-07-14 07:23:24 +00001030 // Remember this mapping so uses in the source module get remapped
1031 // later by RemapOperand.
1032 ValueMap[SF] = NewDF;
1033 continue;
1034 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001035
Chris Lattner6157e382008-07-14 07:23:24 +00001036 // Not "link from source", keep the one in the DestModule and remap the
1037 // input onto it.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001038
Chris Lattner6157e382008-07-14 07:23:24 +00001039 if (isa<GlobalAlias>(DGV)) {
Anton Korobeynikovf88bc652008-07-05 23:33:22 +00001040 // The only valid mappings are:
1041 // - SF is external declaration, which is effectively a no-op.
1042 // - SF is weak, when we just need to throw SF out.
Duncan Sandsa05ef5e2009-03-08 13:35:23 +00001043 if (!SF->isDeclaration() && !SF->isWeakForLinker())
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +00001044 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
1045 "': symbol multiple defined");
Chris Lattner82468492008-06-09 07:36:11 +00001046 }
Anton Korobeynikov194c2ce2008-07-05 23:03:21 +00001047
Chris Lattner6157e382008-07-14 07:23:24 +00001048 // Set calculated linkage
1049 DGV->setLinkage(NewLinkage);
Chris Lattner5c377c52001-10-14 23:29:15 +00001050
Chris Lattner6157e382008-07-14 07:23:24 +00001051 // Make sure to remember this mapping.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001052 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +00001053 }
1054 return false;
1055}
1056
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001057// LinkFunctionBody - Copy the source function over into the dest function and
1058// fix up references to values. At this point we know that Dest is an external
1059// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001060static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spenceref9b9a72007-02-05 20:47:22 +00001061 std::map<const Value*, Value*> &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001062 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001063 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +00001064
Chris Lattner0033baf2004-11-16 17:12:38 +00001065 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +00001066 Function::arg_iterator DI = Dest->arg_begin();
1067 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +00001068 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +00001069 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +00001070
1071 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +00001072 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +00001073 }
1074
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001075 // Splice the body of the source function into the dest function.
1076 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +00001077
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001078 // At this point, all of the instructions and values of the function are now
1079 // copied over. The only problem is that they are still referencing values in
1080 // the Source function as operands. Loop through all of the operands of the
1081 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +00001082 //
Chris Lattner18961502002-06-25 16:12:52 +00001083 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1084 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1085 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +00001086 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001087 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Chris Lattner2a749d32009-11-01 02:46:39 +00001088 *OI = RemapOperand(*OI, ValueMap);
Chris Lattner0033baf2004-11-16 17:12:38 +00001089
1090 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001091 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1092 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001093 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001094
1095 return false;
1096}
1097
1098
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001099// LinkFunctionBodies - Link in the function bodies that are defined in the
1100// source module into the DestModule. This consists basically of copying the
1101// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001102static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001103 std::map<const Value*, Value*> &ValueMap,
1104 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001105
Reid Spencer8bef0372007-02-04 04:29:21 +00001106 // Loop over all of the functions in the src module, mapping them over as we
1107 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001108 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001109 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001110 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001111
Chris Lattner18961502002-06-25 16:12:52 +00001112 // DF not external SF external?
Chris Lattnerec91ccb2008-06-20 05:29:39 +00001113 if (DF && DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001114 // Only provide the function body if there isn't one already.
1115 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1116 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001117 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001118 }
1119 return false;
1120}
1121
Chris Lattner8166e6e2003-05-13 21:33:43 +00001122// LinkAppendingVars - If there were any appending global variables, link them
1123// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001124static bool LinkAppendingVars(Module *M,
1125 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1126 std::string *ErrorMsg) {
1127 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001128
Chris Lattner8166e6e2003-05-13 21:33:43 +00001129 // Loop over the multimap of appending vars, processing any variables with the
1130 // same name, forming a new appending global variable with both of the
1131 // initializers merged together, then rewrite references to the old variables
1132 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001133 std::vector<Constant*> Inits;
1134 while (AppendingVars.size() > 1) {
1135 // Get the first two elements in the map...
1136 std::multimap<std::string,
1137 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1138
1139 // If the first two elements are for different names, there is no pair...
1140 // Otherwise there is a pair, so link them together...
1141 if (First->first == Second->first) {
1142 GlobalVariable *G1 = First->second, *G2 = Second->second;
1143 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1144 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001145
Chris Lattner8166e6e2003-05-13 21:33:43 +00001146 // Check to see that they two arrays agree on type...
1147 if (T1->getElementType() != T2->getElementType())
1148 return Error(ErrorMsg,
1149 "Appending variables with different element types need to be linked!");
1150 if (G1->isConstant() != G2->isConstant())
1151 return Error(ErrorMsg,
1152 "Appending variables linked with different const'ness!");
1153
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001154 if (G1->getAlignment() != G2->getAlignment())
1155 return Error(ErrorMsg,
1156 "Appending variables with different alignment need to be linked!");
1157
1158 if (G1->getVisibility() != G2->getVisibility())
1159 return Error(ErrorMsg,
1160 "Appending variables with different visibility need to be linked!");
1161
1162 if (G1->getSection() != G2->getSection())
1163 return Error(ErrorMsg,
1164 "Appending variables with different section name need to be linked!");
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001165
Chris Lattner8166e6e2003-05-13 21:33:43 +00001166 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
Owen Andersondebcb012009-07-29 22:17:13 +00001167 ArrayType *NewType = ArrayType::get(T1->getElementType(),
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001168 NewSize);
Chris Lattner8166e6e2003-05-13 21:33:43 +00001169
Chris Lattnered74a4e2005-12-06 17:30:58 +00001170 G1->setName(""); // Clear G1's name in case of a conflict!
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001171
Chris Lattner8166e6e2003-05-13 21:33:43 +00001172 // Create the new global variable...
1173 GlobalVariable *NG =
Owen Andersone9b11b42009-07-08 19:03:57 +00001174 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1175 /*init*/0, First->first, 0, G1->isThreadLocal(),
Chris Lattnera534b0f2008-06-27 03:10:24 +00001176 G1->getType()->getAddressSpace());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001177
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001178 // Propagate alignment, visibility and section info.
1179 CopyGVAttributes(NG, G1);
1180
Chris Lattner8166e6e2003-05-13 21:33:43 +00001181 // Merge the initializer...
1182 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001183 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1184 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001185 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001186 } else {
1187 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001188 Constant *CV = Constant::getNullValue(T1->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001189 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1190 Inits.push_back(CV);
1191 }
1192 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1193 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001194 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001195 } else {
1196 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
Owen Andersona7235ea2009-07-31 20:28:14 +00001197 Constant *CV = Constant::getNullValue(T2->getElementType());
Chris Lattnerde512b52004-02-15 05:55:15 +00001198 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1199 Inits.push_back(CV);
1200 }
Owen Anderson1fd70962009-07-28 18:32:17 +00001201 NG->setInitializer(ConstantArray::get(NewType, Inits));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001202 Inits.clear();
1203
1204 // Replace any uses of the two global variables with uses of the new
1205 // global...
1206
1207 // FIXME: This should rewrite simple/straight-forward uses such as
1208 // getelementptr instructions to not use the Cast!
Owen Andersonbaf3c402009-07-29 18:55:55 +00001209 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001210 G1->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001211 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
Owen Andersonc9ab7bf2009-07-07 21:07:14 +00001212 G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001213
1214 // Remove the two globals from the module now...
1215 M->getGlobalList().erase(G1);
1216 M->getGlobalList().erase(G2);
1217
1218 // Put the new global into the AppendingVars map so that we can handle
1219 // linking of more than two vars...
1220 Second->second = NG;
1221 }
1222 AppendingVars.erase(First);
1223 }
1224
1225 return false;
1226}
Chris Lattner52f7e902001-10-13 07:03:50 +00001227
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001228static bool ResolveAliases(Module *Dest) {
1229 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001230 I != E; ++I)
David Chisnall34722462010-01-09 16:27:31 +00001231 // We can't sue resolveGlobalAlias here because we need to preserve
1232 // bitcasts and GEPs.
1233 if (const Constant *C = I->getAliasee()) {
1234 while (dyn_cast<GlobalAlias>(C))
1235 C = cast<GlobalAlias>(C)->getAliasee();
1236 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1237 if (C != I && !(GV && GV->isDeclaration()))
1238 I->replaceAllUsesWith(const_cast<Constant*>(C));
1239 }
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001240
1241 return false;
1242}
Chris Lattner52f7e902001-10-13 07:03:50 +00001243
1244// LinkModules - This function links two modules together, with the resulting
1245// left module modified to be the composite of the two input modules. If an
1246// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001247// the problem. Upon failure, the Dest module could be in a modified state, and
1248// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001249bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001250Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001251 assert(Dest != 0 && "Invalid Destination module");
1252 assert(Src != 0 && "Invalid Source Module");
1253
Chris Lattnerc36357c2007-01-29 00:21:34 +00001254 if (Dest->getDataLayout().empty()) {
1255 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001256 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001257 } else {
1258 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001259
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001260 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001261 if (Src->getEndianness() == Module::BigEndian)
1262 DataLayout.append("E");
1263 else if (Src->getEndianness() == Module::LittleEndian)
1264 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001265 }
1266
1267 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001268 if (Src->getPointerSize() == Module::Pointer64)
1269 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1270 else if (Src->getPointerSize() == Module::Pointer32)
1271 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001272 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001273 Dest->setDataLayout(DataLayout);
1274 }
1275 }
1276
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001277 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001278 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001279 Dest->setTargetTriple(Src->getTargetTriple());
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001280
Chris Lattnerc36357c2007-01-29 00:21:34 +00001281 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1282 Src->getDataLayout() != Dest->getDataLayout())
Chris Lattnerbdff5482009-08-23 04:37:46 +00001283 errs() << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001284 if (!Src->getTargetTriple().empty() &&
1285 Dest->getTargetTriple() != Src->getTargetTriple())
Chris Lattnerbdff5482009-08-23 04:37:46 +00001286 errs() << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001287
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001288 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001289 if (!Src->getModuleInlineAsm().empty()) {
1290 if (Dest->getModuleInlineAsm().empty())
1291 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001292 else
Chris Lattner66316012006-01-24 04:14:29 +00001293 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1294 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001295 }
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001296
Reid Spencer719012d2004-11-25 09:29:44 +00001297 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001298 // from the source module. There's no opportunity for duplicates here as the
1299 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001300 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001301 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001302 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001303
Chris Lattner2c236f32001-11-03 05:18:24 +00001304 // LinkTypes - Go through the symbol table of the Src module and see if any
1305 // types are named in the src module that are not named in the Dst module.
1306 // Make sure there are no type name conflicts.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +00001307 if (LinkTypes(Dest, Src, ErrorMsg))
Reid Spencer619f0242007-02-04 04:43:17 +00001308 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001309
Chris Lattner5c377c52001-10-14 23:29:15 +00001310 // ValueMap - Mapping of values from what they used to be in Src, to what they
1311 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +00001312 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001313
Chris Lattner8166e6e2003-05-13 21:33:43 +00001314 // AppendingVars - Keep track of global variables in the destination module
1315 // with appending linkage. After the module is linked together, they are
1316 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001317 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001318 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1319 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001320 // Add all of the appending globals already in the Dest module to
1321 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001322 if (I->hasAppendingLinkage())
1323 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001324 }
1325
Devang Patelab67e702009-08-11 18:01:24 +00001326 // Insert all of the named mdnoes in Src into the Dest module.
1327 LinkNamedMDNodes(Dest, Src);
1328
Chris Lattner8166e6e2003-05-13 21:33:43 +00001329 // Insert all of the globals in src into the Dest module... without linking
1330 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001331 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001332 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001333
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001334 // Link the functions together between the two modules, without doing function
1335 // bodies... this just adds external function prototypes to the Dest
1336 // function... We do this so that when we begin processing function bodies,
1337 // all of the global values that may be referenced are available in our
1338 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001339 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001340 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001341
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001342 // If there were any alias, link them now. We really need to do this now,
1343 // because all of the aliases that may be referenced need to be available in
1344 // ValueMap
1345 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1346
Chris Lattner6cdf1972002-07-18 00:13:08 +00001347 // Update the initializers in the Dest module now that all globals that may
1348 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001349 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1350
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001351 // Link in the function bodies that are defined in the source module into the
1352 // DestModule. This consists basically of copying the function over and
1353 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001354 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001355
Chris Lattner8166e6e2003-05-13 21:33:43 +00001356 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001357 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1358
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001359 // Resolve all uses of aliases with aliasees
1360 if (ResolveAliases(Dest)) return true;
1361
Reid Spencer57a0efa2004-09-11 04:25:17 +00001362 // If the source library's module id is in the dependent library list of the
1363 // destination library, remove it since that module is now linked in.
1364 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +00001365 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +00001366 if (!modId.isEmpty())
1367 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +00001368
Chris Lattner52f7e902001-10-13 07:03:50 +00001369 return false;
1370}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001371
Reid Spencer567bc2c2004-05-25 08:52:20 +00001372// vim: sw=2