blob: 64c00327f29041ffddd484bbefe605850e7f7993 [file] [log] [blame]
Reid Spencer7f496022004-11-12 20:37:43 +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"
Chris Lattner5c377c52001-10-14 23:29:15 +000022#include "llvm/Module.h"
Reid Spencer78d033e2007-01-06 07:24:44 +000023#include "llvm/TypeSymbolTable.h"
Reid Spenceref9b9a72007-02-05 20:47:22 +000024#include "llvm/ValueSymbolTable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000025#include "llvm/Instructions.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000026#include "llvm/Assembly/Writer.h"
Bill Wendling41edad72006-11-27 10:09:12 +000027#include "llvm/Support/Streams.h"
Reid Spencer57a0efa2004-09-11 04:25:17 +000028#include "llvm/System/Path.h"
Bill Wendling1a097e32006-12-07 23:41:45 +000029#include <sstream>
Chris Lattnerf7703df2004-01-09 06:12:26 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner5c377c52001-10-14 23:29:15 +000032// Error - Simple wrapper function to conditionally assign to E and return true.
33// This just makes error return conditions a little bit simpler...
Chris Lattner8166e6e2003-05-13 21:33:43 +000034static inline bool Error(std::string *E, const std::string &Message) {
Chris Lattner5c377c52001-10-14 23:29:15 +000035 if (E) *E = Message;
36 return true;
37}
38
Reid Spencer719012d2004-11-25 09:29:44 +000039// ToStr - Simple wrapper function to convert a type to a string.
Chris Lattner72cf7df2004-08-21 00:50:59 +000040static std::string ToStr(const Type *Ty, const Module *M) {
41 std::ostringstream OS;
42 WriteTypeSymbolic(OS, Ty, M);
43 return OS.str();
44}
45
John Criswell700867b2003-11-04 15:22:26 +000046//
47// Function: ResolveTypes()
48//
49// Description:
50// Attempt to link the two specified types together.
51//
52// Inputs:
53// DestTy - The type to which we wish to resolve.
54// SrcTy - The original type which we want to resolve.
John Criswell700867b2003-11-04 15:22:26 +000055//
56// Outputs:
57// DestST - The symbol table in which the new type should be placed.
58//
59// Return value:
60// true - There is an error and the types cannot yet be linked.
61// false - No errors.
Chris Lattner4c00e532003-05-15 16:30:55 +000062//
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000063static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Chris Lattnere76c57a2003-08-22 06:07:12 +000064 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000065 assert(DestTy && SrcTy && "Can't handle null types");
Chris Lattnere76c57a2003-08-22 06:07:12 +000066
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000067 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
68 // Type _is_ in module, just opaque...
69 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
70 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
71 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
72 } else {
73 return true; // Cannot link types... not-equal and neither is opaque.
Chris Lattner4c00e532003-05-15 16:30:55 +000074 }
75 return false;
76}
77
Chris Lattner43f4ba82003-08-22 19:12:55 +000078static const FunctionType *getFT(const PATypeHolder &TH) {
79 return cast<FunctionType>(TH.get());
80}
Chris Lattner9732be72003-08-22 20:16:48 +000081static const StructType *getST(const PATypeHolder &TH) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000082 return cast<StructType>(TH.get());
83}
Chris Lattnere76c57a2003-08-22 06:07:12 +000084
85// RecursiveResolveTypes - This is just like ResolveTypes, except that it
86// recurses down into derived types, merging the used types if the parent types
87// are compatible.
Chris Lattnere3092c92003-08-23 21:25:54 +000088static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
89 const PATypeHolder &SrcTy,
Chris Lattnere3092c92003-08-23 21:25:54 +000090 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
Chris Lattner43f4ba82003-08-22 19:12:55 +000091 const Type *SrcTyT = SrcTy.get();
92 const Type *DestTyT = DestTy.get();
93 if (DestTyT == SrcTyT) return false; // If already equal, noop
Misha Brukmanf976c852005-04-21 22:55:34 +000094
Chris Lattnere76c57a2003-08-22 06:07:12 +000095 // If we found our opaque type, resolve it now!
Chris Lattner43f4ba82003-08-22 19:12:55 +000096 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
Chris Lattnerbc1c82a2008-06-16 18:19:05 +000097 return ResolveTypes(DestTyT, SrcTyT);
Misha Brukmanf976c852005-04-21 22:55:34 +000098
Chris Lattnere76c57a2003-08-22 06:07:12 +000099 // Two types cannot be resolved together if they are of different primitive
100 // type. For example, we cannot resolve an int to a float.
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000101 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000102
103 // Otherwise, resolve the used type used by this derived type...
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000104 switch (DestTyT->getTypeID()) {
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000105 default:
106 return true;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000107 case Type::FunctionTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000108 if (cast<FunctionType>(DestTyT)->isVarArg() !=
Chris Lattner841e00b2003-08-28 16:42:50 +0000109 cast<FunctionType>(SrcTyT)->isVarArg() ||
110 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
111 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
Chris Lattner43f4ba82003-08-22 19:12:55 +0000112 return true;
113 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000114 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000115 getFT(SrcTy)->getContainedType(i), Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000116 return true;
117 return false;
118 }
119 case Type::StructTyID: {
Misha Brukmanf976c852005-04-21 22:55:34 +0000120 if (getST(DestTy)->getNumContainedTypes() !=
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000121 getST(SrcTy)->getNumContainedTypes())
122 return true;
Chris Lattner43f4ba82003-08-22 19:12:55 +0000123 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
Chris Lattnere3092c92003-08-23 21:25:54 +0000124 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000125 getST(SrcTy)->getContainedType(i), Pointers))
Chris Lattnere76c57a2003-08-22 06:07:12 +0000126 return true;
127 return false;
128 }
129 case Type::ArrayTyID: {
Chris Lattner43f4ba82003-08-22 19:12:55 +0000130 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
131 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
Chris Lattnere76c57a2003-08-22 06:07:12 +0000132 if (DAT->getNumElements() != SAT->getNumElements()) return true;
Chris Lattnere3092c92003-08-23 21:25:54 +0000133 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000134 Pointers);
Chris Lattnere76c57a2003-08-22 06:07:12 +0000135 }
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000136 case Type::VectorTyID: {
137 const VectorType *DVT = cast<VectorType>(DestTy.get());
138 const VectorType *SVT = cast<VectorType>(SrcTy.get());
139 if (DVT->getNumElements() != SVT->getNumElements()) return true;
140 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
141 Pointers);
142 }
Chris Lattnere3092c92003-08-23 21:25:54 +0000143 case Type::PointerTyID: {
144 // If this is a pointer type, check to see if we have already seen it. If
145 // so, we are in a recursive branch. Cut off the search now. We cannot use
146 // an associative container for this search, because the type pointers (keys
147 // in the container) change whenever types get resolved...
Chris Lattnere3092c92003-08-23 21:25:54 +0000148 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
149 if (Pointers[i].first == DestTy)
150 return Pointers[i].second != SrcTy;
151
152 // Otherwise, add the current pointers to the vector to stop recursion on
153 // this pair.
154 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
155 bool Result =
156 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
157 cast<PointerType>(SrcTy.get())->getElementType(),
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000158 Pointers);
Chris Lattnere3092c92003-08-23 21:25:54 +0000159 return Result;
160 }
Misha Brukmanf976c852005-04-21 22:55:34 +0000161 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000162}
163
Chris Lattnere3092c92003-08-23 21:25:54 +0000164static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000165 const PATypeHolder &SrcTy) {
Chris Lattnere3092c92003-08-23 21:25:54 +0000166 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000167 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Chris Lattnere3092c92003-08-23 21:25:54 +0000168}
169
Chris Lattnere76c57a2003-08-22 06:07:12 +0000170
Chris Lattner2c236f32001-11-03 05:18:24 +0000171// LinkTypes - Go through the symbol table of the Src module and see if any
172// types are named in the src module that are not named in the Dst module.
173// Make sure there are no type name conflicts.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000174static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
Reid Spencer78d033e2007-01-06 07:24:44 +0000175 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
176 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
Chris Lattner2c236f32001-11-03 05:18:24 +0000177
178 // Look for a type plane for Type's...
Reid Spencer78d033e2007-01-06 07:24:44 +0000179 TypeSymbolTable::const_iterator TI = SrcST->begin();
180 TypeSymbolTable::const_iterator TE = SrcST->end();
Reid Spencer567bc2c2004-05-25 08:52:20 +0000181 if (TI == TE) return false; // No named types, do nothing.
Chris Lattner2c236f32001-11-03 05:18:24 +0000182
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000183 // Some types cannot be resolved immediately because they depend on other
184 // types being resolved to each other first. This contains a list of types we
185 // are waiting to recheck.
Chris Lattner4c00e532003-05-15 16:30:55 +0000186 std::vector<std::string> DelayedTypesToResolve;
187
Reid Spencer567bc2c2004-05-25 08:52:20 +0000188 for ( ; TI != TE; ++TI ) {
189 const std::string &Name = TI->first;
Reid Spencerc28a2242004-07-04 11:52:49 +0000190 const Type *RHS = TI->second;
Chris Lattner2c236f32001-11-03 05:18:24 +0000191
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000192 // Check to see if this type name is already in the dest module.
Reid Spencer78d033e2007-01-06 07:24:44 +0000193 Type *Entry = DestST->lookup(Name);
Chris Lattner2f6bb2b2003-01-30 20:53:43 +0000194
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000195 // If the name is just in the source module, bring it over to the dest.
196 if (Entry == 0) {
197 if (!Name.empty())
198 DestST->insert(Name, const_cast<Type*>(RHS));
199 } else if (ResolveTypes(Entry, RHS)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000200 // They look different, save the types 'till later to resolve.
201 DelayedTypesToResolve.push_back(Name);
Chris Lattner2c236f32001-11-03 05:18:24 +0000202 }
203 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000204
205 // Iteratively resolve types while we can...
206 while (!DelayedTypesToResolve.empty()) {
207 // Loop over all of the types, attempting to resolve them if possible...
208 unsigned OldSize = DelayedTypesToResolve.size();
209
Chris Lattnere76c57a2003-08-22 06:07:12 +0000210 // Try direct resolution by name...
Chris Lattner4c00e532003-05-15 16:30:55 +0000211 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
212 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000213 Type *T1 = SrcST->lookup(Name);
214 Type *T2 = DestST->lookup(Name);
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000215 if (!ResolveTypes(T2, T1)) {
Chris Lattner4c00e532003-05-15 16:30:55 +0000216 // We are making progress!
217 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
218 --i;
219 }
220 }
221
222 // Did we not eliminate any types?
223 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000224 // Attempt to resolve subelements of types. This allows us to merge these
225 // two types: { int* } and { opaque* }
Chris Lattner4c00e532003-05-15 16:30:55 +0000226 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
227 const std::string &Name = DelayedTypesToResolve[i];
Reid Spencer78d033e2007-01-06 07:24:44 +0000228 PATypeHolder T1(SrcST->lookup(Name));
229 PATypeHolder T2(DestST->lookup(Name));
Chris Lattnere76c57a2003-08-22 06:07:12 +0000230
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000231 if (!RecursiveResolveTypes(T2, T1)) {
Chris Lattnere76c57a2003-08-22 06:07:12 +0000232 // We are making progress!
233 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
Misha Brukmanf976c852005-04-21 22:55:34 +0000234
Chris Lattnere76c57a2003-08-22 06:07:12 +0000235 // Go back to the main loop, perhaps we can resolve directly by name
236 // now...
237 break;
238 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000239 }
Chris Lattnere76c57a2003-08-22 06:07:12 +0000240
241 // If we STILL cannot resolve the types, then there is something wrong.
Chris Lattnere76c57a2003-08-22 06:07:12 +0000242 if (DelayedTypesToResolve.size() == OldSize) {
Chris Lattneraeb18ce2003-10-21 22:46:38 +0000243 // Remove the symbol name from the destination.
244 DelayedTypesToResolve.pop_back();
Chris Lattnere76c57a2003-08-22 06:07:12 +0000245 }
Chris Lattner4c00e532003-05-15 16:30:55 +0000246 }
247 }
248
249
Chris Lattner2c236f32001-11-03 05:18:24 +0000250 return false;
251}
252
Chris Lattner5c2d3352003-01-30 19:53:34 +0000253static void PrintMap(const std::map<const Value*, Value*> &M) {
254 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000255 I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000256 cerr << " Fr: " << (void*)I->first << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000257 I->first->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000258 cerr << " To: " << (void*)I->second << " ";
Chris Lattner87182ae2002-04-07 22:31:23 +0000259 I->second->dump();
Bill Wendlinge8156192006-12-07 01:30:32 +0000260 cerr << "\n";
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000261 }
262}
263
264
Reid Spencer619f0242007-02-04 04:43:17 +0000265// RemapOperand - Use ValueMap to convert constants from one module to another.
Chris Lattner5c2d3352003-01-30 19:53:34 +0000266static Value *RemapOperand(const Value *In,
Chris Lattner0033baf2004-11-16 17:12:38 +0000267 std::map<const Value*, Value*> &ValueMap) {
268 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000269 if (I != ValueMap.end())
270 return I->second;
Chris Lattner5c377c52001-10-14 23:29:15 +0000271
Reid Spencer619f0242007-02-04 04:43:17 +0000272 // Check to see if it's a constant that we are interested in transforming.
Chris Lattner620fd682006-06-01 19:14:22 +0000273 Value *Result = 0;
Chris Lattner18961502002-06-25 16:12:52 +0000274 if (const Constant *CPV = dyn_cast<Constant>(In)) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000275 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
Reid Spencera54b7cb2007-01-12 07:05:14 +0000276 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
Chris Lattner0033baf2004-11-16 17:12:38 +0000277 return const_cast<Constant*>(CPV); // Simple constants stay identical.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000278
Chris Lattner18961502002-06-25 16:12:52 +0000279 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000280 std::vector<Constant*> Operands(CPA->getNumOperands());
281 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000282 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000283 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
Chris Lattner18961502002-06-25 16:12:52 +0000284 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +0000285 std::vector<Constant*> Operands(CPS->getNumOperands());
286 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattner0033baf2004-11-16 17:12:38 +0000287 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000288 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
Chris Lattnerb976e662004-10-16 18:08:06 +0000289 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
Chris Lattner18961502002-06-25 16:12:52 +0000290 Result = const_cast<Constant*>(CPV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000291 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
Chris Lattnera88eb922006-01-19 23:15:58 +0000292 std::vector<Constant*> Operands(CP->getNumOperands());
293 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
294 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000295 Result = ConstantVector::get(Operands);
Chris Lattner6cdf1972002-07-18 00:13:08 +0000296 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
Chris Lattner27d67212006-07-14 22:21:31 +0000297 std::vector<Constant*> Ops;
298 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
299 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
300 Result = CE->getWithOperands(Ops);
Reid Spencer619f0242007-02-04 04:43:17 +0000301 } else if (isa<GlobalValue>(CPV)) {
302 assert(0 && "Unmapped global?");
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000303 } else {
304 assert(0 && "Unknown type of derived type constant value!");
305 }
Chris Lattner620fd682006-06-01 19:14:22 +0000306 } else if (isa<InlineAsm>(In)) {
307 Result = const_cast<Value*>(In);
308 }
309
Reid Spencer619f0242007-02-04 04:43:17 +0000310 // Cache the mapping in our local map structure
Chris Lattner620fd682006-06-01 19:14:22 +0000311 if (Result) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000312 ValueMap[In] = Result;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000313 return Result;
314 }
Reid Spencer8bef0372007-02-04 04:29:21 +0000315
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000316
Bill Wendlinge8156192006-12-07 01:30:32 +0000317 cerr << "LinkModules ValueMap: \n";
Chris Lattner0033baf2004-11-16 17:12:38 +0000318 PrintMap(ValueMap);
Chris Lattner2d3e8bb2001-11-03 03:27:29 +0000319
Bill Wendlinge8156192006-12-07 01:30:32 +0000320 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000321 assert(0 && "Couldn't remap value!");
322 return 0;
Chris Lattner5c377c52001-10-14 23:29:15 +0000323}
324
Reid Spencer8bef0372007-02-04 04:29:21 +0000325/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
326/// in the symbol table. This is good for all clients except for us. Go
327/// through the trouble to force this back.
Chris Lattnerc0036282004-08-04 07:05:54 +0000328static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
329 assert(GV->getName() != Name && "Can't force rename to self");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000330 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
Chris Lattnerc0036282004-08-04 07:05:54 +0000331
332 // If there is a conflict, rename the conflict.
Chris Lattner33f29492007-02-11 00:39:38 +0000333 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000334 assert(ConflictGV->hasInternalLinkage() &&
335 "Not conflicting with a static global, should link instead!");
Chris Lattner33f29492007-02-11 00:39:38 +0000336 GV->takeName(ConflictGV);
337 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Reid Spenceref9b9a72007-02-05 20:47:22 +0000338 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000339 } else {
340 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000341 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000342}
Reid Spencer8bef0372007-02-04 04:29:21 +0000343
Reid Spenceref9b9a72007-02-05 20:47:22 +0000344/// CopyGVAttributes - copy additional attributes (those not needed to construct
345/// a GlobalValue) from the SrcGV to the DestGV.
346static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000347 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
348 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
349 DestGV->copyAttributesFrom(SrcGV);
350 DestGV->setAlignment(Alignment);
Chris Lattnerc0036282004-08-04 07:05:54 +0000351}
352
Chris Lattneraee38ea2004-12-03 22:18:41 +0000353/// GetLinkageResult - This analyzes the two global values and determines what
354/// the result will look like in the destination module. In particular, it
355/// computes the resultant linkage type, computes whether the global in the
356/// source should be copied over to the destination (replacing the existing
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000357/// one), and computes whether this linkage is an error or not. It also performs
358/// visibility checks: we cannot link together two symbols with different
359/// visibilities.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000360static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Chris Lattneraee38ea2004-12-03 22:18:41 +0000361 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
362 std::string *Err) {
363 assert((!Dest || !Src->hasInternalLinkage()) &&
364 "If Src has internal linkage, Dest shouldn't be set!");
365 if (!Dest) {
366 // Linking something to nothing.
367 LinkFromSrc = true;
368 LT = Src->getLinkage();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000369 } else if (Src->isDeclaration()) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000370 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000371 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000372 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000373 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000374 if (Dest->isDeclaration()) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000375 LinkFromSrc = true;
376 LT = Src->getLinkage();
377 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000378 } else if (Dest->hasExternalWeakLinkage()) {
379 //If the Dest is weak, use the source linkage
380 LinkFromSrc = true;
381 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000382 } else {
383 LinkFromSrc = false;
384 LT = Dest->getLinkage();
385 }
Reid Spencer5cbf9852007-01-30 20:08:39 +0000386 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000387 // If Dest is external but Src is not:
388 LinkFromSrc = true;
389 LT = Src->getLinkage();
390 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
391 if (Src->getLinkage() != Dest->getLinkage())
392 return Error(Err, "Linking globals named '" + Src->getName() +
393 "': can only link appending global with another appending global!");
394 LinkFromSrc = true; // Special cased.
395 LT = Src->getLinkage();
Dale Johannesenaafce772008-05-14 20:12:51 +0000396 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
397 Src->hasCommonLinkage()) {
398 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
399 // or DLL* linkage.
400 if ((Dest->hasLinkOnceLinkage() &&
401 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000402 Dest->hasExternalWeakLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000403 LinkFromSrc = true;
404 LT = Src->getLinkage();
405 } else {
406 LinkFromSrc = false;
407 LT = Dest->getLinkage();
408 }
Dale Johannesenaafce772008-05-14 20:12:51 +0000409 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
410 Dest->hasCommonLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000411 // At this point we know that Src has External* or DLL* linkage.
412 if (Src->hasExternalWeakLinkage()) {
413 LinkFromSrc = false;
414 LT = Dest->getLinkage();
415 } else {
416 LinkFromSrc = true;
417 LT = GlobalValue::ExternalLinkage;
418 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000419 } else {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000420 assert((Dest->hasExternalLinkage() ||
421 Dest->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000422 Dest->hasDLLExportLinkage() ||
423 Dest->hasExternalWeakLinkage()) &&
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000424 (Src->hasExternalLinkage() ||
425 Src->hasDLLImportLinkage() ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000426 Src->hasDLLExportLinkage() ||
427 Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000428 "Unexpected linkage type!");
Misha Brukmanf976c852005-04-21 22:55:34 +0000429 return Error(Err, "Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000430 "': symbol multiply defined!");
431 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000432
433 // Check visibility
434 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattner97f8b092007-08-19 22:22:54 +0000435 if (!Src->isDeclaration() && !Dest->isDeclaration())
436 return Error(Err, "Linking globals named '" + Src->getName() +
437 "': symbols have different visibilities!");
Chris Lattneraee38ea2004-12-03 22:18:41 +0000438 return false;
439}
Chris Lattner5c377c52001-10-14 23:29:15 +0000440
441// LinkGlobals - Loop through the global variables in the src module and merge
Chris Lattner8166e6e2003-05-13 21:33:43 +0000442// them into the dest module.
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000443static bool LinkGlobals(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000444 std::map<const Value*, Value*> &ValueMap,
Chris Lattner8166e6e2003-05-13 21:33:43 +0000445 std::multimap<std::string, GlobalVariable *> &AppendingVars,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000446 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +0000447 // Loop over all of the globals in the src module, mapping them over as we go
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000448 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
Chris Lattner11273152006-06-16 01:24:04 +0000449 I != E; ++I) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000450 const GlobalVariable *SGV = I;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000451 GlobalValue *DGV = 0;
452
453 // Check to see if may have to link the global with the global
Reid Spenceref9b9a72007-02-05 20:47:22 +0000454 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
455 DGV = Dest->getGlobalVariable(SGV->getName());
456 if (DGV && DGV->getType() != SGV->getType())
457 // If types don't agree due to opaque types, try to resolve them.
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000458 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Reid Spenceref9b9a72007-02-05 20:47:22 +0000459 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000460
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000461 // Check to see if may have to link the global with the alias
Anton Korobeynikovaeb09962008-03-10 22:35:31 +0000462 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000463 DGV = Dest->getNamedAlias(SGV->getName());
464 if (DGV && DGV->getType() != SGV->getType())
465 // If types don't agree due to opaque types, try to resolve them.
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000466 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000467 }
468
Chris Lattneraee38ea2004-12-03 22:18:41 +0000469 if (DGV && DGV->hasInternalLinkage())
470 DGV = 0;
471
Dan Gohmanc3183292007-10-08 15:13:30 +0000472 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
473 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Chris Lattner4ad02e72003-04-16 20:28:45 +0000474 "Global must either be external or have an initializer!");
475
Chris Lattnerb324bd72006-11-09 05:18:12 +0000476 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
477 bool LinkFromSrc = false;
Chris Lattneraee38ea2004-12-03 22:18:41 +0000478 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
479 return true;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000480
Chris Lattneraee38ea2004-12-03 22:18:41 +0000481 if (!DGV) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000482 // No linking to be performed, simply create an identical version of the
483 // symbol over in the dest module... the initializer will be filled in
484 // later by LinkGlobalInits...
Chris Lattner2719bac2003-04-21 21:15:04 +0000485 GlobalVariable *NewDGV =
486 new GlobalVariable(SGV->getType()->getElementType(),
487 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikove20c8142008-03-07 18:32:18 +0000488 SGV->getName(), Dest);
Reid Spencer471feac2007-02-04 04:30:33 +0000489 // Propagate alignment, visibility and section info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000490 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000491
Chris Lattner2719bac2003-04-21 21:15:04 +0000492 // If the LLVM runtime renamed the global, but it is an externally visible
493 // symbol, DGV must be an existing global with internal linkage. Rename
494 // it.
Chris Lattnerc0036282004-08-04 07:05:54 +0000495 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
496 ForceRenaming(NewDGV, SGV->getName());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000497
498 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000499 ValueMap[SGV] = NewDGV;
500
Chris Lattner8166e6e2003-05-13 21:33:43 +0000501 if (SGV->hasAppendingLinkage())
502 // Keep track that this is an appending variable...
503 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Chris Lattneraee38ea2004-12-03 22:18:41 +0000504 } else if (DGV->hasAppendingLinkage()) {
Chris Lattner8166e6e2003-05-13 21:33:43 +0000505 // No linking is performed yet. Just insert a new copy of the global, and
506 // keep track of the fact that it is an appending variable in the
507 // AppendingVars map. The name is cleared out so that no linkage is
508 // performed.
509 GlobalVariable *NewDGV =
510 new GlobalVariable(SGV->getType()->getElementType(),
511 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikove20c8142008-03-07 18:32:18 +0000512 "", Dest);
Chris Lattner8166e6e2003-05-13 21:33:43 +0000513
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000514 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000515 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov75c79152008-03-07 18:34:50 +0000516 // Propagate alignment, section and visibility info.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000517 CopyGVAttributes(NewDGV, SGV);
Andrew Lenharth5dfbaf12007-02-01 17:12:54 +0000518
Chris Lattner8166e6e2003-05-13 21:33:43 +0000519 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000520 ValueMap[SGV] = NewDGV;
Chris Lattner8166e6e2003-05-13 21:33:43 +0000521
522 // Keep track that this is an appending variable...
523 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000524 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
525 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
526 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000527 // linkage calculation was correct.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000528 if (SGV->isDeclaration() && !LinkFromSrc) {
529 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000530 ValueMap[SGV] = DGA;
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000531 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000532 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
533 "': symbol multiple defined");
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000534 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000535 // Otherwise, perform the global-global mapping as instructed by
536 // GetLinkageResult.
Chris Lattneraee38ea2004-12-03 22:18:41 +0000537 if (LinkFromSrc) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000538 // Propagate alignment, section, and visibility info.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000539 CopyGVAttributes(DGVar, SGV);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000540
541 // If the types don't match, and if we are to link from the source, nuke
542 // DGV and create a new one of the appropriate type.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000543 if (SGV->getType() != DGVar->getType()) {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000544 GlobalVariable *NewDGV =
545 new GlobalVariable(SGV->getType()->getElementType(),
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000546 DGVar->isConstant(), DGVar->getLinkage(),
547 /*init*/0, DGVar->getName(), Dest);
548 CopyGVAttributes(NewDGV, DGVar);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000549 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000550 DGVar->getType()));
551 // DGVar will conflict with NewDGV because they both had the same
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000552 // name. We must erase this now so ForceRenaming doesn't assert
553 // because DGV might not have internal linkage.
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000554 DGVar->eraseFromParent();
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000555
556 // If the symbol table renamed the global, but it is an externally
557 // visible symbol, DGV must be an existing global with internal
558 // linkage. Rename it.
559 if (NewDGV->getName() != SGV->getName() &&
560 !NewDGV->hasInternalLinkage())
561 ForceRenaming(NewDGV, SGV->getName());
562
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000563 DGVar = NewDGV;
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000564 }
565
Chris Lattneraee38ea2004-12-03 22:18:41 +0000566 // Inherit const as appropriate
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000567 DGVar->setConstant(SGV->isConstant());
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000568
569 // Set initializer to zero, so we can link the stuff later
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000570 DGVar->setInitializer(0);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000571 } else {
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000572 // Special case for const propagation
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000573 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
574 DGVar->setConstant(true);
Chris Lattneraee38ea2004-12-03 22:18:41 +0000575 }
576
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000577 // Set calculated linkage
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000578 DGVar->setLinkage(NewLinkage);
Anton Korobeynikov968e39a2008-03-10 22:33:53 +0000579
580 // Make sure to remember this mapping...
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000581 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
Chris Lattner5c377c52001-10-14 23:29:15 +0000582 }
583 }
584 return false;
585}
586
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000587static GlobalValue::LinkageTypes
588CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
589 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
590 return GlobalValue::ExternalLinkage;
591 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
592 return GlobalValue::WeakLinkage;
593 else {
594 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
595 "Unexpected linkage type");
596 return GlobalValue::InternalLinkage;
597 }
598}
599
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000600// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000601// dest module. We're assuming, that all functions/global variables were already
602// linked in.
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000603static bool LinkAlias(Module *Dest, const Module *Src,
604 std::map<const Value*, Value*> &ValueMap,
605 std::string *Err) {
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000606 // Loop over all alias in the src module
607 for (Module::const_alias_iterator I = Src->alias_begin(),
608 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000609 const GlobalAlias *SGA = I;
610 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
611 GlobalAlias *NewGA = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000612
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000613 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000614 // of SAliasee in Dest.
Ted Kremenek58d5e052008-03-09 18:32:50 +0000615 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
616 assert(VMI != ValueMap.end() && "Aliasee not linked");
617 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000618 GlobalValue* DGV = NULL;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000619
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000620 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000621 if (!DGV && !SGA->hasInternalLinkage()) {
622 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov4fb28732008-03-05 15:27:21 +0000623
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000624 // If types don't agree due to opaque types, try to resolve them.
625 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000626 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000627 return Error(Err, "Alias Collision on '" + SGA->getName()+
628 "': aliases have different types");
629 }
630
631 if (!DGV && !SGA->hasInternalLinkage()) {
632 DGV = Dest->getGlobalVariable(SGA->getName());
633
634 // If types don't agree due to opaque types, try to resolve them.
635 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000636 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000637 return Error(Err, "Alias Collision on '" + SGA->getName()+
638 "': aliases have different types");
639 }
640
641 if (!DGV && !SGA->hasInternalLinkage()) {
642 DGV = Dest->getFunction(SGA->getName());
643
644 // If types don't agree due to opaque types, try to resolve them.
645 if (DGV && DGV->getType() != SGA->getType())
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000646 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000647 return Error(Err, "Alias Collision on '" + SGA->getName()+
648 "': aliases have different types");
649 }
650
651 // No linking to be performed on internal stuff.
652 if (DGV && DGV->hasInternalLinkage())
653 DGV = NULL;
654
655 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
656 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000657 // globals are already linked we just need query ValueMap to find the
658 // mapping.
659 if (DAliasee == DGA->getAliasedGlobal()) {
660 // This is just two copies of the same alias. Propagate linkage, if
661 // necessary.
662 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
663
664 NewGA = DGA;
665 // Proceed to 'common' steps
666 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000667 return Error(Err, "Alias Collision on '" + SGA->getName()+
668 "': aliases have different aliasees");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000669 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000670 // The only allowed way is to link alias with external declaration.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000671 if (DGVar->isDeclaration()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000672 // But only if aliasee is global too...
673 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000674 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
675 "': aliasee is not global variable");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000676
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000677 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
678 SGA->getName(), DAliasee, Dest);
679 CopyGVAttributes(NewGA, SGA);
680
681 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000682 if (SGA->getType() != DGVar->getType())
683 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
684 DGVar->getType()));
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000685 else
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000686 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000687
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000688 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000689 // name. We must erase this now so ForceRenaming doesn't assert
690 // because DGV might not have internal linkage.
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000691 DGVar->eraseFromParent();
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000692
693 // Proceed to 'common' steps
694 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000695 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
696 "': symbol multiple defined");
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000697 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000698 // The only allowed way is to link alias with external declaration.
699 if (DF->isDeclaration()) {
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000700 // But only if aliasee is function too...
701 if (!isa<Function>(DAliasee))
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000702 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
703 "': aliasee is not function");
Anton Korobeynikoved61c0b2008-03-10 22:36:53 +0000704
Anton Korobeynikovb5a4bd82008-03-05 23:08:16 +0000705 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
706 SGA->getName(), DAliasee, Dest);
707 CopyGVAttributes(NewGA, SGA);
708
709 // Any uses of DF need to change to NewGA, with cast, if needed.
710 if (SGA->getType() != DF->getType())
711 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
712 DF->getType()));
713 else
714 DF->replaceAllUsesWith(NewGA);
715
716 // DF will conflict with NewGA because they both had the same
717 // name. We must erase this now so ForceRenaming doesn't assert
718 // because DF might not have internal linkage.
719 DF->eraseFromParent();
720
721 // Proceed to 'common' steps
722 } else
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000723 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
724 "': symbol multiple defined");
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000725 } else {
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000726 // No linking to be performed, simply create an identical version of the
727 // alias over in the dest module...
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000728
729 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
730 SGA->getName(), DAliasee, Dest);
731 CopyGVAttributes(NewGA, SGA);
732
733 // Proceed to 'common' steps
734 }
735
736 assert(NewGA && "No alias was created in destination module!");
737
Anton Korobeynikovb8cdaf72008-03-10 22:36:35 +0000738 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikovcaa8ae82008-05-10 14:41:43 +0000739 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000740 if (NewGA->getName() != SGA->getName() &&
741 !NewGA->hasInternalLinkage())
742 ForceRenaming(NewGA, SGA->getName());
743
744 // Remember this mapping so uses in the source module get remapped
745 // later by RemapOperand.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000746 ValueMap[SGA] = NewGA;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000747 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000748
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000749 return false;
750}
751
Chris Lattner5c377c52001-10-14 23:29:15 +0000752
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000753// LinkGlobalInits - Update the initializers in the Dest module now that all
754// globals that may be referenced are in Dest.
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000755static bool LinkGlobalInits(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000756 std::map<const Value*, Value*> &ValueMap,
757 std::string *Err) {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000758
759 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner11273152006-06-16 01:24:04 +0000760 for (Module::const_global_iterator I = Src->global_begin(),
761 E = Src->global_end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000762 const GlobalVariable *SGV = I;
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000763
764 if (SGV->hasInitializer()) { // Only process initialized GV's
765 // Figure out what the initializer looks like in the dest module...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000766 Constant *SInit =
Chris Lattner0033baf2004-11-16 17:12:38 +0000767 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000768
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000769 GlobalVariable *DGV =
770 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Chris Lattner4ad02e72003-04-16 20:28:45 +0000771 if (DGV->hasInitializer()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000772 if (SGV->hasExternalLinkage()) {
773 if (DGV->getInitializer() != SInit)
Anton Korobeynikov1438b9d2008-03-10 22:34:46 +0000774 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
775 "': global variables have different initializers");
Dale Johannesenaafce772008-05-14 20:12:51 +0000776 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
777 DGV->hasCommonLinkage()) {
Chris Lattner4ad02e72003-04-16 20:28:45 +0000778 // Nothing is required, mapped values will take the new global
779 // automatically.
Dale Johannesenaafce772008-05-14 20:12:51 +0000780 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
781 SGV->hasCommonLinkage()) {
Chris Lattner57cb9882004-02-17 21:56:04 +0000782 // Nothing is required, mapped values will take the new global
783 // automatically.
Chris Lattner4ad02e72003-04-16 20:28:45 +0000784 } else if (DGV->hasAppendingLinkage()) {
785 assert(0 && "Appending linkage unimplemented!");
786 } else {
787 assert(0 && "Unknown linkage!");
788 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000789 } else {
790 // Copy the initializer over now...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000791 DGV->setInitializer(SInit);
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000792 }
793 }
794 }
795 return false;
796}
Chris Lattner5c377c52001-10-14 23:29:15 +0000797
Chris Lattner79df7c02002-03-26 18:01:55 +0000798// LinkFunctionProtos - Link the functions together between the two modules,
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000799// without doing function bodies... this just adds external function prototypes
800// to the Dest function...
Chris Lattner5c377c52001-10-14 23:29:15 +0000801//
Chris Lattner79df7c02002-03-26 18:01:55 +0000802static bool LinkFunctionProtos(Module *Dest, const Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000803 std::map<const Value*, Value*> &ValueMap,
804 std::string *Err) {
Reid Spencer619f0242007-02-04 04:43:17 +0000805 // Loop over all of the functions in the src module, mapping them over
Chris Lattner5c377c52001-10-14 23:29:15 +0000806 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
Chris Lattner18961502002-06-25 16:12:52 +0000807 const Function *SF = I; // SrcFunction
Chris Lattner82468492008-06-09 07:36:11 +0000808
Chris Lattner4ad02e72003-04-16 20:28:45 +0000809 Function *DF = 0;
Chris Lattner82468492008-06-09 07:36:11 +0000810
811 // If this function is internal or has no name, it doesn't participate in
812 // linkage.
Reid Spencer8bef0372007-02-04 04:29:21 +0000813 if (SF->hasName() && !SF->hasInternalLinkage()) {
814 // Check to see if may have to link the function.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000815 DF = Dest->getFunction(SF->getName());
Chris Lattner82468492008-06-09 07:36:11 +0000816 if (DF && DF->hasInternalLinkage())
817 DF = 0;
Reid Spencer8bef0372007-02-04 04:29:21 +0000818 }
Chris Lattnerbc3d1c72008-06-09 07:25:28 +0000819
Chris Lattner82468492008-06-09 07:36:11 +0000820 // If there is no linkage to be performed, just bring over SF without
821 // modifying it.
822 if (DF == 0) {
823 // Function does not already exist, simply insert an function signature
824 // identical to SF into the dest module.
825 Function *NewDF = Function::Create(SF->getFunctionType(),
826 SF->getLinkage(),
827 SF->getName(), Dest);
828 CopyGVAttributes(NewDF, SF);
829
830 // If the LLVM runtime renamed the function, but it is an externally
831 // visible symbol, DF must be an existing function with internal linkage.
832 // Rename it.
833 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
834 ForceRenaming(NewDF, SF->getName());
835
836 // ... and remember this mapping...
837 ValueMap[SF] = NewDF;
838 continue;
839 }
840
841
842 // If types don't agree because of opaque, try to resolve them.
843 if (SF->getType() != DF->getType())
Chris Lattnerbc1c82a2008-06-16 18:19:05 +0000844 RecursiveResolveTypes(SF->getType(), DF->getType());
Chris Lattner82468492008-06-09 07:36:11 +0000845
846 // Check visibility, merging if a definition overrides a prototype.
847 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattner97f8b092007-08-19 22:22:54 +0000848 // If one is a prototype, ignore its visibility. Prototypes are always
849 // overridden by the definition.
850 if (!SF->isDeclaration() && !DF->isDeclaration())
851 return Error(Err, "Linking functions named '" + SF->getName() +
852 "': symbols have different visibilities!");
Chris Lattnerbc3d1c72008-06-09 07:25:28 +0000853
854 // Otherwise, replace the visibility of DF if DF is a prototype.
855 if (DF->isDeclaration())
856 DF->setVisibility(SF->getVisibility());
Chris Lattner97f8b092007-08-19 22:22:54 +0000857 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000858
Chris Lattner82468492008-06-09 07:36:11 +0000859 if (DF->getType() != SF->getType()) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000860 if (DF->isDeclaration() && !SF->isDeclaration()) {
861 // We have a definition of the same name but different type in the
862 // source module. Copy the prototype to the destination and replace
863 // uses of the destination's prototype with the new prototype.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000864 Function *NewDF = Function::Create(SF->getFunctionType(),
865 SF->getLinkage(),
Gabor Greif051a9502008-04-06 20:25:17 +0000866 SF->getName(), Dest);
Reid Spenceref9b9a72007-02-05 20:47:22 +0000867 CopyGVAttributes(NewDF, SF);
Chris Lattner5c377c52001-10-14 23:29:15 +0000868
Reid Spenceref9b9a72007-02-05 20:47:22 +0000869 // Any uses of DF need to change to NewDF, with cast
870 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
871
872 // DF will conflict with NewDF because they both had the same. We must
873 // erase this now so ForceRenaming doesn't assert because DF might
874 // not have internal linkage.
875 DF->eraseFromParent();
876
877 // If the symbol table renamed the function, but it is an externally
878 // visible symbol, DF must be an existing function with internal
879 // linkage. Rename it.
880 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
881 ForceRenaming(NewDF, SF->getName());
882
883 // Remember this mapping so uses in the source module get remapped
884 // later by RemapOperand.
885 ValueMap[SF] = NewDF;
886 } else if (SF->isDeclaration()) {
887 // We have two functions of the same name but different type and the
888 // source is a declaration while the destination is not. Any use of
889 // the source must be mapped to the destination, with a cast.
890 ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
891 } else {
892 // We have two functions of the same name but different types and they
893 // are both definitions. This is an error.
894 return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
895 ToStr(SF->getFunctionType(), Src) + "' and '" +
896 ToStr(DF->getFunctionType(), Dest) + "'");
897 }
Chris Lattner82468492008-06-09 07:36:11 +0000898 continue;
899 }
900
901 if (SF->isDeclaration()) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000902 // If SF is a declaration or if both SF & DF are declarations, just link
903 // the declarations, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000904 if (SF->hasDLLImportLinkage()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000905 if (DF->isDeclaration()) {
Chris Lattner822143e2008-06-09 07:47:34 +0000906 ValueMap[SF] = DF;
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000907 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000908 }
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000909 } else {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000910 ValueMap[SF] = DF;
Chris Lattner822143e2008-06-09 07:47:34 +0000911 }
912 continue;
913 }
914
915 // If DF is external but SF is not, link the external functions, update
916 // linkage qualifiers.
917 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000918 ValueMap.insert(std::make_pair(SF, DF));
919 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000920 continue;
921 }
922
923 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
924 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
925 SF->hasCommonLinkage()) {
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000926 ValueMap[SF] = DF;
Chris Lattner72ac148d2003-10-16 18:29:00 +0000927
Chris Lattner35956552003-10-27 16:39:39 +0000928 // Linkonce+Weak = Weak
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000929 // *+External Weak = *
Dale Johannesenaafce772008-05-14 20:12:51 +0000930 if ((DF->hasLinkOnceLinkage() &&
931 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000932 DF->hasExternalWeakLinkage())
Chris Lattner35956552003-10-27 16:39:39 +0000933 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000934 continue;
935 }
936
937 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
938 DF->hasCommonLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000939 // At this point we know that SF has LinkOnce or External* linkage.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000940 ValueMap[SF] = DF;
Chris Lattner822143e2008-06-09 07:47:34 +0000941
942 // If the source function has stronger linkage than the destination,
943 // its body and linkage should override ours.
944 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
945 // Don't inherit linkonce & external weak linkage.
Chris Lattner72ac148d2003-10-16 18:29:00 +0000946 DF->setLinkage(SF->getLinkage());
Chris Lattner822143e2008-06-09 07:47:34 +0000947 DF->deleteBody();
948 }
949 continue;
950 }
951
952 if (SF->getLinkage() != DF->getLinkage())
953 return Error(Err, "Functions named '" + SF->getName() +
954 "' have different linkage specifiers!");
955
956 // The function is defined identically in both modules!
957 if (SF->hasExternalLinkage())
Misha Brukmanf976c852005-04-21 22:55:34 +0000958 return Error(Err, "Function '" +
959 ToStr(SF->getFunctionType(), Src) + "':\"" +
Chris Lattnerc2b97d42003-04-23 18:38:39 +0000960 SF->getName() + "\" - Function is already defined!");
Chris Lattner822143e2008-06-09 07:47:34 +0000961 assert(0 && "Unknown linkage configuration found!");
Chris Lattner5c377c52001-10-14 23:29:15 +0000962 }
963 return false;
964}
965
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000966// LinkFunctionBody - Copy the source function over into the dest function and
967// fix up references to values. At this point we know that Dest is an external
968// function, and that Src is not.
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000969static bool LinkFunctionBody(Function *Dest, Function *Src,
Reid Spenceref9b9a72007-02-05 20:47:22 +0000970 std::map<const Value*, Value*> &ValueMap,
Chris Lattner5c2d3352003-01-30 19:53:34 +0000971 std::string *Err) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000972 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000973
Chris Lattner0033baf2004-11-16 17:12:38 +0000974 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnere4d5c442005-03-15 04:54:21 +0000975 Function::arg_iterator DI = Dest->arg_begin();
976 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000977 I != E; ++I, ++DI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000978 DI->setName(I->getName()); // Copy the name information over...
Chris Lattner5c377c52001-10-14 23:29:15 +0000979
980 // Add a mapping to our local map
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000981 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000982 }
983
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000984 // Splice the body of the source function into the dest function.
985 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
Chris Lattner5c377c52001-10-14 23:29:15 +0000986
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000987 // At this point, all of the instructions and values of the function are now
988 // copied over. The only problem is that they are still referencing values in
989 // the Source function as operands. Loop through all of the operands of the
990 // functions and patch them up to point to the local versions...
Chris Lattner5c377c52001-10-14 23:29:15 +0000991 //
Chris Lattner18961502002-06-25 16:12:52 +0000992 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
993 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
994 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
Chris Lattner221d6882002-02-12 21:07:25 +0000995 OI != OE; ++OI)
Chris Lattner4bbfbff2004-11-16 07:31:51 +0000996 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
Reid Spenceref9b9a72007-02-05 20:47:22 +0000997 *OI = RemapOperand(*OI, ValueMap);
Chris Lattner0033baf2004-11-16 17:12:38 +0000998
999 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +00001000 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1001 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +00001002 ValueMap.erase(I);
Chris Lattner5c377c52001-10-14 23:29:15 +00001003
1004 return false;
1005}
1006
1007
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001008// LinkFunctionBodies - Link in the function bodies that are defined in the
1009// source module into the DestModule. This consists basically of copying the
1010// function over and fixing up references to values.
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001011static bool LinkFunctionBodies(Module *Dest, Module *Src,
Chris Lattner5c2d3352003-01-30 19:53:34 +00001012 std::map<const Value*, Value*> &ValueMap,
1013 std::string *Err) {
Chris Lattner5c377c52001-10-14 23:29:15 +00001014
Reid Spencer8bef0372007-02-04 04:29:21 +00001015 // Loop over all of the functions in the src module, mapping them over as we
1016 // go
Chris Lattner4bbfbff2004-11-16 07:31:51 +00001017 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
Reid Spencer619f0242007-02-04 04:43:17 +00001018 if (!SF->isDeclaration()) { // No body if function is external
Chris Lattner18961502002-06-25 16:12:52 +00001019 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
Chris Lattner5c377c52001-10-14 23:29:15 +00001020
Chris Lattner18961502002-06-25 16:12:52 +00001021 // DF not external SF external?
Reid Spenceref9b9a72007-02-05 20:47:22 +00001022 if (DF->isDeclaration())
Chris Lattner35956552003-10-27 16:39:39 +00001023 // Only provide the function body if there isn't one already.
1024 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1025 return true;
Chris Lattnerc2d774b2001-10-23 20:43:42 +00001026 }
Chris Lattner5c377c52001-10-14 23:29:15 +00001027 }
1028 return false;
1029}
1030
Chris Lattner8166e6e2003-05-13 21:33:43 +00001031// LinkAppendingVars - If there were any appending global variables, link them
1032// together now. Return true on error.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001033static bool LinkAppendingVars(Module *M,
1034 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1035 std::string *ErrorMsg) {
1036 if (AppendingVars.empty()) return false; // Nothing to do.
Misha Brukmanf976c852005-04-21 22:55:34 +00001037
Chris Lattner8166e6e2003-05-13 21:33:43 +00001038 // Loop over the multimap of appending vars, processing any variables with the
1039 // same name, forming a new appending global variable with both of the
1040 // initializers merged together, then rewrite references to the old variables
1041 // and delete them.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001042 std::vector<Constant*> Inits;
1043 while (AppendingVars.size() > 1) {
1044 // Get the first two elements in the map...
1045 std::multimap<std::string,
1046 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1047
1048 // If the first two elements are for different names, there is no pair...
1049 // Otherwise there is a pair, so link them together...
1050 if (First->first == Second->first) {
1051 GlobalVariable *G1 = First->second, *G2 = Second->second;
1052 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1053 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
Misha Brukmanf976c852005-04-21 22:55:34 +00001054
Chris Lattner8166e6e2003-05-13 21:33:43 +00001055 // Check to see that they two arrays agree on type...
1056 if (T1->getElementType() != T2->getElementType())
1057 return Error(ErrorMsg,
1058 "Appending variables with different element types need to be linked!");
1059 if (G1->isConstant() != G2->isConstant())
1060 return Error(ErrorMsg,
1061 "Appending variables linked with different const'ness!");
1062
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001063 if (G1->getAlignment() != G2->getAlignment())
1064 return Error(ErrorMsg,
1065 "Appending variables with different alignment need to be linked!");
1066
1067 if (G1->getVisibility() != G2->getVisibility())
1068 return Error(ErrorMsg,
1069 "Appending variables with different visibility need to be linked!");
1070
1071 if (G1->getSection() != G2->getSection())
1072 return Error(ErrorMsg,
1073 "Appending variables with different section name need to be linked!");
1074
Chris Lattner8166e6e2003-05-13 21:33:43 +00001075 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1076 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1077
Chris Lattnered74a4e2005-12-06 17:30:58 +00001078 G1->setName(""); // Clear G1's name in case of a conflict!
1079
Chris Lattner8166e6e2003-05-13 21:33:43 +00001080 // Create the new global variable...
1081 GlobalVariable *NG =
1082 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001083 /*init*/0, First->first, M, G1->isThreadLocal());
Chris Lattner8166e6e2003-05-13 21:33:43 +00001084
Lauro Ramos Venancio9613e872007-06-06 22:01:12 +00001085 // Propagate alignment, visibility and section info.
1086 CopyGVAttributes(NG, G1);
1087
Chris Lattner8166e6e2003-05-13 21:33:43 +00001088 // Merge the initializer...
1089 Inits.reserve(NewSize);
Chris Lattnerde512b52004-02-15 05:55:15 +00001090 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1091 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001092 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001093 } else {
1094 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1095 Constant *CV = Constant::getNullValue(T1->getElementType());
1096 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1097 Inits.push_back(CV);
1098 }
1099 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1100 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
Alkis Evlogimenoscc7ba492004-08-04 08:08:13 +00001101 Inits.push_back(I->getOperand(i));
Chris Lattnerde512b52004-02-15 05:55:15 +00001102 } else {
1103 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1104 Constant *CV = Constant::getNullValue(T2->getElementType());
1105 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1106 Inits.push_back(CV);
1107 }
Chris Lattner8166e6e2003-05-13 21:33:43 +00001108 NG->setInitializer(ConstantArray::get(NewType, Inits));
1109 Inits.clear();
1110
1111 // Replace any uses of the two global variables with uses of the new
1112 // global...
1113
1114 // FIXME: This should rewrite simple/straight-forward uses such as
1115 // getelementptr instructions to not use the Cast!
Reid Spencer4da49122006-12-12 05:05:00 +00001116 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1117 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
Chris Lattner8166e6e2003-05-13 21:33:43 +00001118
1119 // Remove the two globals from the module now...
1120 M->getGlobalList().erase(G1);
1121 M->getGlobalList().erase(G2);
1122
1123 // Put the new global into the AppendingVars map so that we can handle
1124 // linking of more than two vars...
1125 Second->second = NG;
1126 }
1127 AppendingVars.erase(First);
1128 }
1129
1130 return false;
1131}
Chris Lattner52f7e902001-10-13 07:03:50 +00001132
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001133static bool ResolveAliases(Module *Dest) {
1134 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov52419572008-03-11 22:51:09 +00001135 I != E; ++I)
1136 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1137 if (!GV->isDeclaration())
1138 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001139
1140 return false;
1141}
Chris Lattner52f7e902001-10-13 07:03:50 +00001142
1143// LinkModules - This function links two modules together, with the resulting
1144// left module modified to be the composite of the two input modules. If an
1145// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001146// the problem. Upon failure, the Dest module could be in a modified state, and
1147// shouldn't be relied on to be consistent.
Misha Brukmanf976c852005-04-21 22:55:34 +00001148bool
Reid Spencer0ba9e212004-12-13 03:00:16 +00001149Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
Reid Spencer57a0efa2004-09-11 04:25:17 +00001150 assert(Dest != 0 && "Invalid Destination module");
1151 assert(Src != 0 && "Invalid Source Module");
1152
Chris Lattnerc36357c2007-01-29 00:21:34 +00001153 if (Dest->getDataLayout().empty()) {
1154 if (!Src->getDataLayout().empty()) {
Chris Lattnerec9bfdc2007-01-29 02:18:13 +00001155 Dest->setDataLayout(Src->getDataLayout());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001156 } else {
1157 std::string DataLayout;
Reid Spencer26f23852007-01-26 08:11:39 +00001158
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001159 if (Dest->getEndianness() == Module::AnyEndianness) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001160 if (Src->getEndianness() == Module::BigEndian)
1161 DataLayout.append("E");
1162 else if (Src->getEndianness() == Module::LittleEndian)
1163 DataLayout.append("e");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001164 }
1165
1166 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Chris Lattnerc36357c2007-01-29 00:21:34 +00001167 if (Src->getPointerSize() == Module::Pointer64)
1168 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1169 else if (Src->getPointerSize() == Module::Pointer32)
1170 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikova27694d2008-02-20 11:27:04 +00001171 }
Chris Lattnerc36357c2007-01-29 00:21:34 +00001172 Dest->setDataLayout(DataLayout);
1173 }
1174 }
1175
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001176 // Copy the target triple from the source to dest if the dest's is empty.
Chris Lattnerc36357c2007-01-29 00:21:34 +00001177 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
Chris Lattner152f19a2004-12-10 20:26:15 +00001178 Dest->setTargetTriple(Src->getTargetTriple());
Chris Lattnerc36357c2007-01-29 00:21:34 +00001179
1180 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1181 Src->getDataLayout() != Dest->getDataLayout())
Reid Spencer26f23852007-01-26 08:11:39 +00001182 cerr << "WARNING: Linking two modules of different data layouts!\n";
Chris Lattner152f19a2004-12-10 20:26:15 +00001183 if (!Src->getTargetTriple().empty() &&
1184 Dest->getTargetTriple() != Src->getTargetTriple())
Bill Wendlinge8156192006-12-07 01:30:32 +00001185 cerr << "WARNING: Linking two modules of different target triples!\n";
Misha Brukmanf976c852005-04-21 22:55:34 +00001186
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001187 // Append the module inline asm string.
Chris Lattner66316012006-01-24 04:14:29 +00001188 if (!Src->getModuleInlineAsm().empty()) {
1189 if (Dest->getModuleInlineAsm().empty())
1190 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001191 else
Chris Lattner66316012006-01-24 04:14:29 +00001192 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1193 Src->getModuleInlineAsm());
Chris Lattnere1b2e142006-01-23 23:08:37 +00001194 }
1195
Reid Spencer719012d2004-11-25 09:29:44 +00001196 // Update the destination module's dependent libraries list with the libraries
Reid Spencer57a0efa2004-09-11 04:25:17 +00001197 // from the source module. There's no opportunity for duplicates here as the
1198 // Module ensures that duplicate insertions are discarded.
Chris Lattnerf27dfcb2008-02-19 18:49:08 +00001199 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1200 SI != SE; ++SI)
Reid Spencer57a0efa2004-09-11 04:25:17 +00001201 Dest->addLibrary(*SI);
Reid Spencer57a0efa2004-09-11 04:25:17 +00001202
Chris Lattner2c236f32001-11-03 05:18:24 +00001203 // LinkTypes - Go through the symbol table of the Src module and see if any
1204 // types are named in the src module that are not named in the Dst module.
1205 // Make sure there are no type name conflicts.
Reid Spencer619f0242007-02-04 04:43:17 +00001206 if (LinkTypes(Dest, Src, ErrorMsg))
1207 return true;
Chris Lattner2c236f32001-11-03 05:18:24 +00001208
Chris Lattner5c377c52001-10-14 23:29:15 +00001209 // ValueMap - Mapping of values from what they used to be in Src, to what they
1210 // are now in Dest.
Chris Lattner5c2d3352003-01-30 19:53:34 +00001211 std::map<const Value*, Value*> ValueMap;
Chris Lattner5c377c52001-10-14 23:29:15 +00001212
Chris Lattner8166e6e2003-05-13 21:33:43 +00001213 // AppendingVars - Keep track of global variables in the destination module
1214 // with appending linkage. After the module is linked together, they are
1215 // appended and the module is rewritten.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001216 std::multimap<std::string, GlobalVariable *> AppendingVars;
Chris Lattner11273152006-06-16 01:24:04 +00001217 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1218 I != E; ++I) {
Chris Lattner5a837de2004-08-04 07:44:58 +00001219 // Add all of the appending globals already in the Dest module to
1220 // AppendingVars.
Chris Lattnerf4146462003-05-14 12:11:51 +00001221 if (I->hasAppendingLinkage())
1222 AppendingVars.insert(std::make_pair(I->getName(), I));
Chris Lattner5a837de2004-08-04 07:44:58 +00001223 }
1224
Chris Lattner8166e6e2003-05-13 21:33:43 +00001225 // Insert all of the globals in src into the Dest module... without linking
1226 // initializers (which could refer to functions not yet mapped over).
Reid Spenceref9b9a72007-02-05 20:47:22 +00001227 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001228 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001229
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001230 // Link the functions together between the two modules, without doing function
1231 // bodies... this just adds external function prototypes to the Dest
1232 // function... We do this so that when we begin processing function bodies,
1233 // all of the global values that may be referenced are available in our
1234 // ValueMap.
Reid Spenceref9b9a72007-02-05 20:47:22 +00001235 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
Chris Lattner5a837de2004-08-04 07:44:58 +00001236 return true;
Chris Lattner5c377c52001-10-14 23:29:15 +00001237
Anton Korobeynikov4fb28732008-03-05 15:27:21 +00001238 // If there were any alias, link them now. We really need to do this now,
1239 // because all of the aliases that may be referenced need to be available in
1240 // ValueMap
1241 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1242
Chris Lattner6cdf1972002-07-18 00:13:08 +00001243 // Update the initializers in the Dest module now that all globals that may
1244 // be referenced are in Dest.
Chris Lattner6cdf1972002-07-18 00:13:08 +00001245 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1246
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +00001247 // Link in the function bodies that are defined in the source module into the
1248 // DestModule. This consists basically of copying the function over and
1249 // fixing up references to values.
Chris Lattner79df7c02002-03-26 18:01:55 +00001250 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
Chris Lattner52f7e902001-10-13 07:03:50 +00001251
Chris Lattner8166e6e2003-05-13 21:33:43 +00001252 // If there were any appending global variables, link them together now.
Chris Lattner8166e6e2003-05-13 21:33:43 +00001253 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1254
Anton Korobeynikov3db91912008-03-05 23:08:47 +00001255 // Resolve all uses of aliases with aliasees
1256 if (ResolveAliases(Dest)) return true;
1257
Reid Spencer57a0efa2004-09-11 04:25:17 +00001258 // If the source library's module id is in the dependent library list of the
1259 // destination library, remove it since that module is now linked in.
1260 sys::Path modId;
Reid Spencerdd04df02005-07-07 23:21:43 +00001261 modId.set(Src->getModuleIdentifier());
Reid Spencer07adb282004-11-05 22:15:36 +00001262 if (!modId.isEmpty())
1263 Dest->removeLibrary(modId.getBasename());
Reid Spencer57a0efa2004-09-11 04:25:17 +00001264
Chris Lattner52f7e902001-10-13 07:03:50 +00001265 return false;
1266}
Vikram S. Adve9466f512001-10-28 21:38:02 +00001267
Reid Spencer567bc2c2004-05-25 08:52:20 +00001268// vim: sw=2